blob: 54161eced144d7629be4808022fe87836ee2e5f6 [file] [log] [blame]
Matt Jeanneretf1e9c5d2019-02-08 07:41:29 -05001#!/usr/bin/env python
2#
3# Copyright 2018 the original author or authors.
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16#
17
18"""OpenONU Adapter main entry point"""
19
Matt Jeanneret2e3cb8d2019-11-16 09:22:41 -050020from __future__ import absolute_import
Matt Jeanneretf1e9c5d2019-02-08 07:41:29 -050021import argparse
22import os
23import time
Matt Jeanneret08a8e862019-12-20 14:02:32 -050024import types
Rohan Agrawalac066a02020-03-09 12:33:58 +000025import sys
Matt Jeanneretf1e9c5d2019-02-08 07:41:29 -050026
27import arrow
28import yaml
Matt Jeanneret2e3cb8d2019-11-16 09:22:41 -050029import socketserver
Matt Jeanneret08a8e862019-12-20 14:02:32 -050030import configparser
Rohan Agrawalc5bdbbc2019-11-14 12:39:39 +000031
Matt Jeanneretf1e9c5d2019-02-08 07:41:29 -050032from simplejson import dumps
Neha Sharma61446d32020-03-23 14:32:31 +000033from twisted.internet.defer import inlineCallbacks, returnValue, Deferred
Matt Jeanneretf1e9c5d2019-02-08 07:41:29 -050034from twisted.internet.task import LoopingCall
35from zope.interface import implementer
36
Rohan Agrawaldfd5e802020-03-25 20:39:47 +000037from pyvoltha.common.structlog_setup import setup_logging, update_logging, string_to_int
Matt Jeanneret72f96fc2019-02-11 10:53:05 -050038from pyvoltha.common.utils.asleep import asleep
39from pyvoltha.common.utils.deferred_utils import TimeOutError
40from pyvoltha.common.utils.dockerhelpers import get_my_containers_name
41from pyvoltha.common.utils.nethelpers import get_my_primary_local_ipv4, \
Matt Jeanneretf1e9c5d2019-02-08 07:41:29 -050042 get_my_primary_interface
Matt Jeanneret72f96fc2019-02-11 10:53:05 -050043from pyvoltha.common.utils.registry import registry, IComponent
44from pyvoltha.adapters.kafka.adapter_proxy import AdapterProxy
45from pyvoltha.adapters.kafka.adapter_request_facade import AdapterRequestFacade
46from pyvoltha.adapters.kafka.core_proxy import CoreProxy
47from pyvoltha.adapters.kafka.kafka_inter_container_library import IKafkaMessagingProxy, \
Matt Jeanneretf1e9c5d2019-02-08 07:41:29 -050048 get_messaging_proxy
Matt Jeanneret72f96fc2019-02-11 10:53:05 -050049from pyvoltha.adapters.kafka.kafka_proxy import KafkaProxy, get_kafka_proxy
William Kurkian8235c1e2019-03-05 12:58:28 -050050from voltha_protos.adapter_pb2 import AdapterConfig
Matt Jeanneret72f96fc2019-02-11 10:53:05 -050051
Matt Jeanneret2e3cb8d2019-11-16 09:22:41 -050052from brcm_openomci_onu_adapter import BrcmOpenomciOnuAdapter
Rohan Agrawalc5bdbbc2019-11-14 12:39:39 +000053from probe import Probe
Rohan Agrawaldfd5e802020-03-25 20:39:47 +000054from pyvoltha.adapters.log_controller import LogController, KV_STORE_DATA_PATH_PREFIX
Rohan Agrawalc5bdbbc2019-11-14 12:39:39 +000055
Matt Jeanneretf1e9c5d2019-02-08 07:41:29 -050056defs = dict(
Matt Jeanneret08a8e862019-12-20 14:02:32 -050057 build_info_file='./BUILDINFO',
Matt Jeanneretf1e9c5d2019-02-08 07:41:29 -050058 config=os.environ.get('CONFIG', './openonu.yml'),
59 container_name_regex=os.environ.get('CONTAINER_NUMBER_EXTRACTOR', '^.*\.(['
60 '0-9]+)\..*$'),
61 consul=os.environ.get('CONSUL', 'localhost:8500'),
Matteo Scandolobb3317d2020-03-31 10:49:42 -070062 name=os.environ.get('NAME', 'brcm_openomci_onu'),
Matt Jeanneretf1e9c5d2019-02-08 07:41:29 -050063 vendor=os.environ.get('VENDOR', 'Voltha Project'),
64 device_type=os.environ.get('DEVICE_TYPE', 'openonu'),
65 accept_bulk_flow=os.environ.get('ACCEPT_BULK_FLOW', True),
66 accept_atomic_flow=os.environ.get('ACCEPT_ATOMIC_FLOW', True),
67 etcd=os.environ.get('ETCD', 'localhost:2379'),
68 core_topic=os.environ.get('CORE_TOPIC', 'rwcore'),
Devmalya Paulffc89df2019-07-31 17:43:13 -040069 event_topic=os.environ.get('EVENT_TOPIC', 'voltha.events'),
Matt Jeanneretf1e9c5d2019-02-08 07:41:29 -050070 interface=os.environ.get('INTERFACE', get_my_primary_interface()),
71 instance_id=os.environ.get('INSTANCE_ID', os.environ.get('HOSTNAME', '1')),
72 kafka_adapter=os.environ.get('KAFKA_ADAPTER', '192.168.0.20:9092'),
73 kafka_cluster=os.environ.get('KAFKA_CLUSTER', '10.100.198.220:9092'),
74 backend=os.environ.get('BACKEND', 'none'),
75 retry_interval=os.environ.get('RETRY_INTERVAL', 2),
76 heartbeat_topic=os.environ.get('HEARTBEAT_TOPIC', "adapters.heartbeat"),
Rohan Agrawalac066a02020-03-09 12:33:58 +000077 probe=os.environ.get('PROBE', ':8080'),
Rohan Agrawaldfd5e802020-03-25 20:39:47 +000078 log_level=os.environ.get('LOG_LEVEL', 'WARN'),
Matteo Scandolobb3317d2020-03-31 10:49:42 -070079 current_replica=1,
80 total_replicas=1,
Rohan Agrawaldfd5e802020-03-25 20:39:47 +000081 component_name=os.environ.get('COMPONENT_NAME', "adapter-open-onu")
Matt Jeanneretf1e9c5d2019-02-08 07:41:29 -050082)
83
84
85def parse_args():
86 parser = argparse.ArgumentParser()
87
88 _help = ('Path to openonu.yml config file (default: %s). '
89 'If relative, it is relative to main.py of openonu adapter.'
90 % defs['config'])
91 parser.add_argument('-c', '--config',
92 dest='config',
93 action='store',
94 default=defs['config'],
95 help=_help)
96
97 _help = 'Regular expression for extracting conatiner number from ' \
98 'container name (default: %s)' % defs['container_name_regex']
99 parser.add_argument('-X', '--container-number-extractor',
100 dest='container_name_regex',
101 action='store',
102 default=defs['container_name_regex'],
103 help=_help)
104
105 _help = '<hostname>:<port> to consul agent (default: %s)' % defs['consul']
106 parser.add_argument('-C', '--consul',
107 dest='consul',
108 action='store',
109 default=defs['consul'],
110 help=_help)
111
Matteo Scandolobb3317d2020-03-31 10:49:42 -0700112 # NOTE this is really the adapter type
Matt Jeanneretf1e9c5d2019-02-08 07:41:29 -0500113 _help = 'name of this adapter (default: %s)' % defs['name']
114 parser.add_argument('-na', '--name',
115 dest='name',
116 action='store',
117 default=defs['name'],
118 help=_help)
119
120 _help = 'vendor of this adapter (default: %s)' % defs['vendor']
121 parser.add_argument('-ven', '--vendor',
122 dest='vendor',
123 action='store',
124 default=defs['vendor'],
125 help=_help)
126
127 _help = 'supported device type of this adapter (default: %s)' % defs[
128 'device_type']
129 parser.add_argument('-dt', '--device_type',
130 dest='device_type',
131 action='store',
132 default=defs['device_type'],
133 help=_help)
134
135 _help = 'specifies whether the device type accepts bulk flow updates ' \
136 'adapter (default: %s)' % defs['accept_bulk_flow']
137 parser.add_argument('-abf', '--accept_bulk_flow',
138 dest='accept_bulk_flow',
139 action='store',
140 default=defs['accept_bulk_flow'],
141 help=_help)
142
143 _help = 'specifies whether the device type accepts add/remove flow ' \
144 '(default: %s)' % defs['accept_atomic_flow']
145 parser.add_argument('-aaf', '--accept_atomic_flow',
146 dest='accept_atomic_flow',
147 action='store',
148 default=defs['accept_atomic_flow'],
149 help=_help)
150
151 _help = '<hostname>:<port> to etcd server (default: %s)' % defs['etcd']
152 parser.add_argument('-e', '--etcd',
153 dest='etcd',
154 action='store',
155 default=defs['etcd'],
156 help=_help)
157
158 _help = ('unique string id of this container instance (default: %s)'
159 % defs['instance_id'])
160 parser.add_argument('-i', '--instance-id',
161 dest='instance_id',
162 action='store',
163 default=defs['instance_id'],
164 help=_help)
165
166 _help = 'ETH interface to recieve (default: %s)' % defs['interface']
167 parser.add_argument('-I', '--interface',
168 dest='interface',
169 action='store',
170 default=defs['interface'],
171 help=_help)
172
173 _help = 'omit startup banner log lines'
174 parser.add_argument('-n', '--no-banner',
175 dest='no_banner',
176 action='store_true',
177 default=False,
178 help=_help)
179
180 _help = 'do not emit periodic heartbeat log messages'
181 parser.add_argument('-N', '--no-heartbeat',
182 dest='no_heartbeat',
183 action='store_true',
184 default=False,
185 help=_help)
186
Rohan Agrawalac066a02020-03-09 12:33:58 +0000187 _help = 'enable logging'
188 parser.add_argument('-l', '--log_level',
189 dest='log_level',
190 action='store',
191 default=defs['log_level'],
Matt Jeanneretf1e9c5d2019-02-08 07:41:29 -0500192 help=_help)
193
Rohan Agrawaldfd5e802020-03-25 20:39:47 +0000194 _help = 'get the component name'
195 parser.add_argument('-cn', '--component_name',
196 dest='env',
197 action='store',
198 help=_help)
199
Matt Jeanneretf1e9c5d2019-02-08 07:41:29 -0500200 _help = ('use docker container name as conatiner instance id'
201 ' (overrides -i/--instance-id option)')
202 parser.add_argument('--instance-id-is-container-name',
203 dest='instance_id_is_container_name',
204 action='store_true',
205 default=False,
206 help=_help)
207
208 _help = ('<hostname>:<port> of the kafka adapter broker (default: %s). ('
209 'If not '
210 'specified (None), the address from the config file is used'
211 % defs['kafka_adapter'])
212 parser.add_argument('-KA', '--kafka_adapter',
213 dest='kafka_adapter',
214 action='store',
215 default=defs['kafka_adapter'],
216 help=_help)
217
218 _help = ('<hostname>:<port> of the kafka cluster broker (default: %s). ('
219 'If not '
220 'specified (None), the address from the config file is used'
221 % defs['kafka_cluster'])
222 parser.add_argument('-KC', '--kafka_cluster',
223 dest='kafka_cluster',
224 action='store',
225 default=defs['kafka_cluster'],
226 help=_help)
227
228 _help = 'backend to use for config persitence'
229 parser.add_argument('-b', '--backend',
230 default=defs['backend'],
231 choices=['none', 'consul', 'etcd'],
232 help=_help)
233
234 _help = 'topic of core on the kafka bus'
235 parser.add_argument('-ct', '--core_topic',
236 dest='core_topic',
237 action='store',
238 default=defs['core_topic'],
239 help=_help)
240
Devmalya Paulffc89df2019-07-31 17:43:13 -0400241 _help = 'topic of events on the kafka bus'
242 parser.add_argument('-et', '--event_topic',
243 dest='event_topic',
244 action='store',
245 default=defs['event_topic'],
246 help=_help)
247
Rohan Agrawalc5bdbbc2019-11-14 12:39:39 +0000248 _help = '<hostname>:<port> for liveness and readiness probes (default: %s)' % defs['probe']
249 parser.add_argument(
250 '-P', '--probe', dest='probe', action='store',
251 default=defs['probe'],
252 help=_help)
253
Matteo Scandolobb3317d2020-03-31 10:49:42 -0700254 _help = 'Replica number of this particular instance (default: %s)' % defs['current_replica']
255 parser.add_argument(
256 '--currentReplica', dest='current_replica', action='store',
257 default=defs['current_replica'],
258 type=int,
259 help=_help)
260
261 _help = 'Total number of instances for this adapter (default: %s)' % defs['total_replicas']
262 parser.add_argument(
263 '--totalReplicas', dest='total_replicas', action='store',
264 default=defs['total_replicas'],
265 type=int,
266 help=_help)
267
Matt Jeanneretf1e9c5d2019-02-08 07:41:29 -0500268 args = parser.parse_args()
269
270 # post-processing
271
272 if args.instance_id_is_container_name:
273 args.instance_id = get_my_containers_name()
274
275 return args
276
277
278def load_config(args):
279 path = args.config
280 if path.startswith('.'):
281 dir = os.path.dirname(os.path.abspath(__file__))
282 path = os.path.join(dir, path)
283 path = os.path.abspath(path)
284 with open(path) as fd:
285 config = yaml.load(fd)
286 return config
287
288
Matt Jeanneret08a8e862019-12-20 14:02:32 -0500289def get_build_info():
290 path = defs['build_info_file']
291 if not path.startswith('/'):
292 dir = os.path.dirname(os.path.abspath(__file__))
293 path = os.path.join(dir, path)
294 path = os.path.abspath(path)
295 build_info = configparser.ConfigParser()
296 build_info.read(path)
297 results = types.SimpleNamespace(
298 version=build_info.get('buildinfo', 'version', fallback='unknown'),
299 vcs_ref=build_info.get('buildinfo', 'vcs_ref', fallback='unknown'),
300 vcs_dirty=build_info.get('buildinfo', 'vcs_dirty', fallback='unknown'),
301 build_time=build_info.get('buildinfo', 'build_time', fallback='unknown')
302 )
303 return results
304
305
Matt Jeanneretf1e9c5d2019-02-08 07:41:29 -0500306def print_banner(log):
Matt Jeanneret08a8e862019-12-20 14:02:32 -0500307 log.info(' ___________ _____ _ _ _____ _ _ _ _ ')
308 log.info(' | _ | ___ \ ___| \ | | _ | \ | | | | | ')
309 log.info(' | | | | |_/ / |__ | \| | | | | \| | | | | ')
310 log.info(' | | | | __/| __|| . ` | | | | . ` | | | | ')
311 log.info(' \ \_/ / | | |___| |\ \ \_/ / |\ | |_| | ')
312 log.info(' \___/\_| \____/\_| \_/\___/\_| \_/\___/ ')
313 log.info(' ')
Matt Jeanneretf1e9c5d2019-02-08 07:41:29 -0500314
315
316@implementer(IComponent)
317class Main(object):
318
319 def __init__(self):
320
321 self.args = args = parse_args()
322 self.config = load_config(args)
323
Matteo Scandolod8d73172019-11-26 12:15:15 -0700324 # log levels in python are:
Rohan Agrawaldfd5e802020-03-25 20:39:47 +0000325 # 1 - DEBUG => verbosity_adjust = 10
326 # 2 - INFO => verbosity_adjust = 20
327 # 3 - WARNING => verbosity_adjust = 30
328 # 4 - ERROR => verbosity_adjust = 40
329 # 5 - CRITICAL => verbosity_adjust = 50
Matteo Scandolod8d73172019-11-26 12:15:15 -0700330
Rohan Agrawaldfd5e802020-03-25 20:39:47 +0000331 verbosity_adjust = string_to_int(str(args.log_level))
332
333 if verbosity_adjust == 0:
334 raise ValueError("Invalid loglevel is given: " + str(args.log_level))
335 sys.exit(1)
Rohan Agrawalac066a02020-03-09 12:33:58 +0000336
Matt Jeanneretf1e9c5d2019-02-08 07:41:29 -0500337 self.log = setup_logging(self.config.get('logging', {}),
338 args.instance_id,
339 verbosity_adjust=verbosity_adjust)
340 self.log.info('container-number-extractor',
341 regex=args.container_name_regex)
342
Matt Jeanneret08a8e862019-12-20 14:02:32 -0500343 self.build_info = get_build_info()
344 self.log.info('OpenONU-Adapter-Version', build_version=self.build_info)
Matt Jeanneretf1e9c5d2019-02-08 07:41:29 -0500345
346 if not args.no_banner:
347 print_banner(self.log)
348
Rohan Agrawaldfd5e802020-03-25 20:39:47 +0000349 self.etcd_host = str(args.etcd).split(':')[0]
350 self.etcd_port = str(args.etcd).split(':')[1]
351
352 self.controller = LogController(self.etcd_host, self.etcd_port)
353
Matt Jeanneretf1e9c5d2019-02-08 07:41:29 -0500354 self.adapter = None
355 # Create a unique instance id using the passed-in instance id and
356 # UTC timestamp
357 current_time = arrow.utcnow().timestamp
358 self.instance_id = self.args.instance_id + '_' + str(current_time)
359
Matt Jeanneret2e3cb8d2019-11-16 09:22:41 -0500360 self.core_topic = str(args.core_topic)
361 self.event_topic = str(args.event_topic)
Matteo Scandolobb3317d2020-03-31 10:49:42 -0700362 self.listening_topic = "%s_%s" % (args.name, args.current_replica)
363 self.id = "%s_%s" % (args.name, args.current_replica)
Matt Jeanneretf1e9c5d2019-02-08 07:41:29 -0500364 self.startup_components()
365
366 if not args.no_heartbeat:
Matt Jeanneretf1e9c5d2019-02-08 07:41:29 -0500367 self.start_kafka_cluster_heartbeat(self.instance_id)
368
Matt Jeanneretf1e9c5d2019-02-08 07:41:29 -0500369 def start(self):
370 self.start_reactor() # will not return except Keyboard interrupt
371
372 def stop(self):
373 pass
374
375 def get_args(self):
376 """Allow access to command line args"""
377 return self.args
378
379 def get_config(self):
380 """Allow access to content of config file"""
381 return self.config
382
383 def _get_adapter_config(self):
384 cfg = AdapterConfig()
385 return cfg
386
387 @inlineCallbacks
388 def startup_components(self):
389 try:
390 self.log.info('starting-internal-components',
391 consul=self.args.consul,
392 etcd=self.args.etcd)
393
394 registry.register('main', self)
395
Matt Jeanneretf1e9c5d2019-02-08 07:41:29 -0500396 yield registry.register(
397 'kafka_cluster_proxy',
398 KafkaProxy(
399 self.args.consul,
400 self.args.kafka_cluster,
401 config=self.config.get('kafka-cluster-proxy', {})
402 )
403 ).start()
Rohan Agrawalc5bdbbc2019-11-14 12:39:39 +0000404 Probe.kafka_cluster_proxy_running = True
Neha Sharma61446d32020-03-23 14:32:31 +0000405 Probe.kafka_proxy_faulty = False
Matt Jeanneretf1e9c5d2019-02-08 07:41:29 -0500406
407 config = self._get_adapter_config()
408
409 self.core_proxy = CoreProxy(
410 kafka_proxy=None,
Matt Jeanneretc288ee42019-02-28 13:31:59 -0500411 default_core_topic=self.core_topic,
Devmalya Paulffc89df2019-07-31 17:43:13 -0400412 default_event_topic=self.event_topic,
Matt Jeanneretf1e9c5d2019-02-08 07:41:29 -0500413 my_listening_topic=self.listening_topic)
414
415 self.adapter_proxy = AdapterProxy(
416 kafka_proxy=None,
417 core_topic=self.core_topic,
418 my_listening_topic=self.listening_topic)
419
420 self.adapter = BrcmOpenomciOnuAdapter(
Matteo Scandolobb3317d2020-03-31 10:49:42 -0700421 id=self.id,
422 core_proxy=self.core_proxy,
423 adapter_proxy=self.adapter_proxy,
Matt Jeanneret08a8e862019-12-20 14:02:32 -0500424 config=config,
Matteo Scandolobb3317d2020-03-31 10:49:42 -0700425 build_info=self.build_info,
426 current_replica=self.args.current_replica,
427 total_replicas=self.args.total_replicas,
428 endpoint=self.listening_topic
429 )
Matt Jeanneretc288ee42019-02-28 13:31:59 -0500430
Matt Jeannereta32441c2019-03-07 05:16:37 -0500431 self.adapter.start()
432
Matt Jeanneretc288ee42019-02-28 13:31:59 -0500433 openonu_request_handler = AdapterRequestFacade(adapter=self.adapter,
434 core_proxy=self.core_proxy)
Matt Jeanneretf1e9c5d2019-02-08 07:41:29 -0500435
436 yield registry.register(
437 'kafka_adapter_proxy',
438 IKafkaMessagingProxy(
439 kafka_host_port=self.args.kafka_adapter,
440 # TODO: Add KV Store object reference
441 kv_store=self.args.backend,
Matteo Scandolobb3317d2020-03-31 10:49:42 -0700442 default_topic=self.listening_topic,
Matt Jeanneretf1e9c5d2019-02-08 07:41:29 -0500443 group_id_prefix=self.args.instance_id,
444 target_cls=openonu_request_handler
445 )
446 ).start()
Rohan Agrawalc5bdbbc2019-11-14 12:39:39 +0000447 Probe.kafka_adapter_proxy_running = True
Matt Jeanneretf1e9c5d2019-02-08 07:41:29 -0500448
449 self.core_proxy.kafka_proxy = get_messaging_proxy()
450 self.adapter_proxy.kafka_proxy = get_messaging_proxy()
451
452 # retry for ever
453 res = yield self._register_with_core(-1)
Neha Sharma61446d32020-03-23 14:32:31 +0000454 Probe.adapter_registered_with_core = True
Matt Jeanneretf1e9c5d2019-02-08 07:41:29 -0500455
456 self.log.info('started-internal-services')
457
458 except Exception as e:
459 self.log.exception('Failure-to-start-all-components', e=e)
460
461 @inlineCallbacks
462 def shutdown_components(self):
463 """Execute before the reactor is shut down"""
464 self.log.info('exiting-on-keyboard-interrupt')
465 for component in reversed(registry.iterate()):
466 yield component.stop()
467
Neha Sharma61446d32020-03-23 14:32:31 +0000468 self.server.shutdown()
469
Matt Jeanneretf1e9c5d2019-02-08 07:41:29 -0500470 import threading
471 self.log.info('THREADS:')
472 main_thread = threading.current_thread()
473 for t in threading.enumerate():
474 if t is main_thread:
475 continue
476 if not t.isDaemon():
477 continue
478 self.log.info('joining thread {} {}'.format(
479 t.getName(), "daemon" if t.isDaemon() else "not-daemon"))
480 t.join()
481
482 def start_reactor(self):
Rohan Agrawaldfd5e802020-03-25 20:39:47 +0000483 from twisted.internet import reactor, defer
Matt Jeanneretf1e9c5d2019-02-08 07:41:29 -0500484 reactor.callWhenRunning(
485 lambda: self.log.info('twisted-reactor-started'))
486 reactor.addSystemEventTrigger('before', 'shutdown',
487 self.shutdown_components)
Rohan Agrawalc5bdbbc2019-11-14 12:39:39 +0000488 reactor.callInThread(self.start_probe)
Rohan Agrawaldfd5e802020-03-25 20:39:47 +0000489 defer.maybeDeferred(self.controller.start_watch_log_config_change, self.args.instance_id, str(self.args.log_level))
Matt Jeanneretf1e9c5d2019-02-08 07:41:29 -0500490 reactor.run()
491
Rohan Agrawalc5bdbbc2019-11-14 12:39:39 +0000492 def start_probe(self):
493 args = self.args
494 host = args.probe.split(':')[0]
495 port = args.probe.split(':')[1]
Neha Sharma61446d32020-03-23 14:32:31 +0000496 socketserver.TCPServer.allow_reuse_address = True
497 self.server = socketserver.TCPServer((host, int(port)), Probe)
498 self.server.serve_forever()
Rohan Agrawalc5bdbbc2019-11-14 12:39:39 +0000499
Matt Jeanneretf1e9c5d2019-02-08 07:41:29 -0500500 @inlineCallbacks
501 def _register_with_core(self, retries):
502 while 1:
503 try:
504 resp = yield self.core_proxy.register(
505 self.adapter.adapter_descriptor(),
506 self.adapter.device_types())
507 if resp:
508 self.log.info('registered-with-core',
509 coreId=resp.instance_id)
510
511 returnValue(resp)
512 except TimeOutError as e:
513 self.log.warn("timeout-when-registering-with-core", e=e)
514 if retries == 0:
515 self.log.exception("no-more-retries", e=e)
516 raise
517 else:
518 retries = retries if retries < 0 else retries - 1
519 yield asleep(defs['retry_interval'])
520 except Exception as e:
521 self.log.exception("failed-registration", e=e)
522 raise
523
Matt Jeanneretf1e9c5d2019-02-08 07:41:29 -0500524 # Temporary function to send a heartbeat message to the external kafka
525 # broker
526 def start_kafka_cluster_heartbeat(self, instance_id):
527 # For heartbeat we will send a message to a specific "voltha-heartbeat"
528 # topic. The message is a protocol buf
529 # message
530 message = dict(
531 type='heartbeat',
532 adapter=self.args.name,
533 instance=instance_id,
534 ip=get_my_primary_local_ipv4()
535 )
536 topic = defs['heartbeat_topic']
537
Neha Sharma61446d32020-03-23 14:32:31 +0000538 def send_heartbeat_msg():
Matt Jeanneretf1e9c5d2019-02-08 07:41:29 -0500539 try:
540 kafka_cluster_proxy = get_kafka_proxy()
Neha Sharma61446d32020-03-23 14:32:31 +0000541 if kafka_cluster_proxy:
Matt Jeanneretf1e9c5d2019-02-08 07:41:29 -0500542 message['ts'] = arrow.utcnow().timestamp
Neha Sharma61446d32020-03-23 14:32:31 +0000543 self.log.debug('sending-kafka-heartbeat-message')
544
545 # Creating a handler to receive the message callbacks
546 df = Deferred()
547 df.addCallback(self.process_kafka_alive_state_update)
548 kafka_cluster_proxy.register_alive_state_update(df)
549 kafka_cluster_proxy.send_heartbeat_message(topic, dumps(message))
Matt Jeanneretf1e9c5d2019-02-08 07:41:29 -0500550 else:
Rohan Agrawalc5bdbbc2019-11-14 12:39:39 +0000551 Probe.kafka_cluster_proxy_running = False
Matt Jeanneretf1e9c5d2019-02-08 07:41:29 -0500552 self.log.error('kafka-proxy-unavailable')
Matt Jeanneret2e3cb8d2019-11-16 09:22:41 -0500553 except Exception as e:
Matt Jeanneretf1e9c5d2019-02-08 07:41:29 -0500554 self.log.exception('failed-sending-message-heartbeat', e=e)
555
Neha Sharma61446d32020-03-23 14:32:31 +0000556 def check_heartbeat_delivery():
557 try:
558 kafka_cluster_proxy = get_kafka_proxy()
559 if kafka_cluster_proxy:
560 kafka_cluster_proxy.check_heartbeat_delivery()
561 except Exception as e:
562 self.log.exception('failed-checking-heartbeat-delivery', e=e)
Matt Jeanneretf1e9c5d2019-02-08 07:41:29 -0500563
Neha Sharma61446d32020-03-23 14:32:31 +0000564 def schedule_periodic_heartbeat():
565 try:
566 # Sending the heartbeat message in a loop
567 lc_heartbeat = LoopingCall(send_heartbeat_msg)
568 lc_heartbeat.start(10)
569 # Polling the delivery status more frequently to get early notification
570 lc_poll = LoopingCall(check_heartbeat_delivery)
571 lc_poll.start(2)
572 except Exception as e:
573 self.log.exception('failed-kafka-heartbeat-startup', e=e)
574
575 from twisted.internet import reactor
576 # Delaying heartbeat initially to let kafka connection be established
577 reactor.callLater(5, schedule_periodic_heartbeat)
578
579 # Receiving the callback and updating the probe accordingly
580 def process_kafka_alive_state_update(self, alive_state):
581 self.log.debug('process-kafka-alive-state-update', alive_state=alive_state)
582 Probe.kafka_cluster_proxy_running = alive_state
583
584 kafka_cluster_proxy = get_kafka_proxy()
585 if kafka_cluster_proxy:
586 Probe.kafka_proxy_faulty = kafka_cluster_proxy.is_faulty()
Matt Jeanneretf1e9c5d2019-02-08 07:41:29 -0500587
588if __name__ == '__main__':
589 Main().start()