blob: 278a7525c9746002b7283da0220ff12e57c9222c [file] [log] [blame]
Matt Jeanneretf1e9c5d2019-02-08 07:41:29 -05001#
2# Copyright 2017 the original author or authors.
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15#
16
17"""
18Broadcom OpenOMCI OLT/ONU adapter handler.
19"""
20
Matt Jeanneretf1e9c5d2019-02-08 07:41:29 -050021import ast
22import structlog
23
24from collections import OrderedDict
25
26from twisted.internet import reactor, task
27from twisted.internet.defer import DeferredQueue, inlineCallbacks, returnValue, TimeoutError
28
29from heartbeat import HeartBeat
Matt Jeanneret72f96fc2019-02-11 10:53:05 -050030from pyvoltha.adapters.extensions.kpi.onu.onu_pm_metrics import OnuPmMetrics
31from pyvoltha.adapters.extensions.kpi.onu.onu_omci_pm import OnuOmciPmMetrics
32from pyvoltha.adapters.extensions.alarms.adapter_alarms import AdapterAlarms
Matt Jeanneretf1e9c5d2019-02-08 07:41:29 -050033
Matt Jeanneret72f96fc2019-02-11 10:53:05 -050034import pyvoltha.common.openflow.utils as fd
35from pyvoltha.common.utils.registry import registry
36from pyvoltha.common.config.config_backend import ConsulStore
37from pyvoltha.common.config.config_backend import EtcdStore
William Kurkian8235c1e2019-03-05 12:58:28 -050038from voltha_protos.common_pb2 import OperStatus, ConnectStatus, AdminState
39from voltha_protos.openflow_13_pb2 import OFPXMC_OPENFLOW_BASIC, ofp_port
Matt Jeannereta32441c2019-03-07 05:16:37 -050040from voltha_protos.inter_container_pb2 import InterAdapterMessageType, InterAdapterOmciMessage
41from voltha_protos.openolt_pb2 import OnuIndication
Matt Jeanneret72f96fc2019-02-11 10:53:05 -050042from pyvoltha.adapters.extensions.omci.onu_configuration import OMCCVersion
43from pyvoltha.adapters.extensions.omci.onu_device_entry import OnuDeviceEvents, \
Matt Jeanneretf1e9c5d2019-02-08 07:41:29 -050044 OnuDeviceEntry, IN_SYNC_KEY
Matt Jeanneret72f96fc2019-02-11 10:53:05 -050045from omci.brcm_mib_download_task import BrcmMibDownloadTask
46from omci.brcm_tp_service_specific_task import BrcmTpServiceSpecificTask
47from omci.brcm_uni_lock_task import BrcmUniLockTask
48from omci.brcm_vlan_filter_task import BrcmVlanFilterTask
49from onu_gem_port import *
50from onu_tcont import *
51from pon_port import *
52from uni_port import *
53from onu_traffic_descriptor import *
54from pyvoltha.common.tech_profile.tech_profile import TechProfile
Matt Jeanneretf1e9c5d2019-02-08 07:41:29 -050055
56OP = EntityOperations
57RC = ReasonCodes
58
Matt Jeanneretf1e9c5d2019-02-08 07:41:29 -050059log = structlog.get_logger()
60
61_STARTUP_RETRY_WAIT = 20
62
63
64class BrcmOpenomciOnuHandler(object):
65
66 def __init__(self, adapter, device_id):
67 self.log = structlog.get_logger(device_id=device_id)
68 self.log.debug('function-entry')
69 self.adapter = adapter
Matt Jeannereta32441c2019-03-07 05:16:37 -050070 self.core_proxy = adapter.core_proxy
71 self.adapter_proxy = adapter.adapter_proxy
Matt Jeanneretf1e9c5d2019-02-08 07:41:29 -050072 self.parent_adapter = None
73 self.parent_id = None
74 self.device_id = device_id
75 self.incoming_messages = DeferredQueue()
76 self.event_messages = DeferredQueue()
77 self.proxy_address = None
78 self.tx_id = 0
79 self._enabled = False
80 self.alarms = None
81 self.pm_metrics = None
82 self._omcc_version = OMCCVersion.Unknown
83 self._total_tcont_count = 0 # From ANI-G ME
84 self._qos_flexibility = 0 # From ONT2_G ME
85
86 self._onu_indication = None
87 self._unis = dict() # Port # -> UniPort
88
89 self._pon = None
90 # TODO: probably shouldnt be hardcoded, determine from olt maybe?
91 self._pon_port_number = 100
92 self.logical_device_id = None
93
94 self._heartbeat = HeartBeat.create(self, device_id)
95
96 # Set up OpenOMCI environment
97 self._onu_omci_device = None
98 self._dev_info_loaded = False
99 self._deferred = None
100
101 self._in_sync_subscription = None
102 self._connectivity_subscription = None
103 self._capabilities_subscription = None
104
105 self.mac_bridge_service_profile_entity_id = 0x201
106 self.gal_enet_profile_entity_id = 0x1
107
108 self._tp_service_specific_task = dict()
109 self._tech_profile_download_done = dict()
110
111 # Initialize KV store client
112 self.args = registry('main').get_args()
113 if self.args.backend == 'etcd':
114 host, port = self.args.etcd.split(':', 1)
115 self.kv_client = EtcdStore(host, port,
116 TechProfile.KV_STORE_TECH_PROFILE_PATH_PREFIX)
117 elif self.args.backend == 'consul':
118 host, port = self.args.consul.split(':', 1)
119 self.kv_client = ConsulStore(host, port,
120 TechProfile.KV_STORE_TECH_PROFILE_PATH_PREFIX)
121 else:
122 self.log.error('Invalid-backend')
123 raise Exception("Invalid-backend-for-kv-store")
124
125 # Handle received ONU event messages
126 reactor.callLater(0, self.handle_onu_events)
127
128 @property
129 def enabled(self):
130 return self._enabled
131
132 @enabled.setter
133 def enabled(self, value):
134 if self._enabled != value:
135 self._enabled = value
136
137 @property
138 def omci_agent(self):
139 return self.adapter.omci_agent
140
141 @property
142 def omci_cc(self):
143 return self._onu_omci_device.omci_cc if self._onu_omci_device is not None else None
144
145 @property
146 def heartbeat(self):
147 return self._heartbeat
148
149 @property
150 def uni_ports(self):
151 return self._unis.values()
152
153 def uni_port(self, port_no_or_name):
154 if isinstance(port_no_or_name, (str, unicode)):
155 return next((uni for uni in self.uni_ports
156 if uni.name == port_no_or_name), None)
157
158 assert isinstance(port_no_or_name, int), 'Invalid parameter type'
159 return next((uni for uni in self.uni_ports
160 if uni.logical_port_number == port_no_or_name), None)
161
162 @property
163 def pon_port(self):
164 return self._pon
165
166 def receive_message(self, msg):
167 if self.omci_cc is not None:
168 self.omci_cc.receive_message(msg)
169
170 # Called once when the adapter creates the device/onu instance
Matt Jeanneret84e56f62019-02-26 10:48:09 -0500171 @inlineCallbacks
Matt Jeanneretf1e9c5d2019-02-08 07:41:29 -0500172 def activate(self, device):
173 self.log.debug('function-entry', device=device)
174
Matt Jeanneretf1e9c5d2019-02-08 07:41:29 -0500175 assert device.parent_id
Matt Jeanneret0c287892019-02-28 11:48:00 -0500176 assert device.parent_port_no
Matt Jeanneretf1e9c5d2019-02-08 07:41:29 -0500177 assert device.proxy_address.device_id
178
Matt Jeanneretf1e9c5d2019-02-08 07:41:29 -0500179 self.proxy_address = device.proxy_address
Matt Jeanneretf1e9c5d2019-02-08 07:41:29 -0500180 self.parent_id = device.parent_id
Matt Jeanneret0c287892019-02-28 11:48:00 -0500181 self._pon_port_number = device.parent_port_no
Matt Jeanneretf1e9c5d2019-02-08 07:41:29 -0500182
183 if self.enabled is not True:
184 self.log.info('activating-new-onu')
185 # populate what we know. rest comes later after mib sync
Matt Jeanneret0c287892019-02-28 11:48:00 -0500186 device.root = False
Matt Jeannereta32441c2019-03-07 05:16:37 -0500187 device.vendor = 'OpenONU'
Matt Jeanneretf1e9c5d2019-02-08 07:41:29 -0500188 device.reason = 'activating-onu'
189
Matt Jeanneret84e56f62019-02-26 10:48:09 -0500190 # TODO NEW CORE: Need to either get logical device id from core or use regular device id
Matt Jeanneretf1e9c5d2019-02-08 07:41:29 -0500191 # pm_metrics requires a logical device id
Matt Jeanneret84e56f62019-02-26 10:48:09 -0500192 #parent_device = yield self.adapter_agent.get_device(device.parent_id)
193 #self.logical_device_id = parent_device.parent_id
194 #assert self.logical_device_id, 'Invalid logical device ID'
Matt Jeanneretf1e9c5d2019-02-08 07:41:29 -0500195
Matt Jeannereta32441c2019-03-07 05:16:37 -0500196 yield self.core_proxy.device_update(device)
197
198 yield self.core_proxy.device_state_update(device.id, oper_status=OperStatus.DISCOVERED,
199 connect_status=ConnectStatus.REACHABLE)
200
Matt Jeanneretf1e9c5d2019-02-08 07:41:29 -0500201
202 self.log.debug('set-device-discovered')
203
204 self._init_pon_state(device)
205
206 ############################################################################
207 # Setup PM configuration for this device
208 # Pass in ONU specific options
209 kwargs = {
210 OnuPmMetrics.DEFAULT_FREQUENCY_KEY: OnuPmMetrics.DEFAULT_ONU_COLLECTION_FREQUENCY,
211 'heartbeat': self.heartbeat,
212 OnuOmciPmMetrics.OMCI_DEV_KEY: self._onu_omci_device
213 }
Matt Jeannereta32441c2019-03-07 05:16:37 -0500214 self.pm_metrics = OnuPmMetrics(self.core_proxy, self.device_id,
Matt Jeanneretf1e9c5d2019-02-08 07:41:29 -0500215 self.logical_device_id, grouped=True,
216 freq_override=False, **kwargs)
217 pm_config = self.pm_metrics.make_proto()
218 self._onu_omci_device.set_pm_config(self.pm_metrics.omci_pm.openomci_interval_pm)
219 self.log.info("initial-pm-config", pm_config=pm_config)
Matt Jeannereta32441c2019-03-07 05:16:37 -0500220 yield self.core_proxy.device_pm_config_update(pm_config, init=True)
Matt Jeanneretf1e9c5d2019-02-08 07:41:29 -0500221
222 ############################################################################
223 # Setup Alarm handler
Matt Jeannereta32441c2019-03-07 05:16:37 -0500224 self.alarms = AdapterAlarms(self.core_proxy, device.id, self.logical_device_id)
Matt Jeanneretf1e9c5d2019-02-08 07:41:29 -0500225 # Note, ONU ID and UNI intf set in add_uni_port method
226 self._onu_omci_device.alarm_synchronizer.set_alarm_params(mgr=self.alarms,
227 ani_ports=[self._pon])
228 self.enabled = True
229 else:
230 self.log.info('onu-already-activated')
231
232 # Called once when the adapter needs to re-create device. usually on vcore restart
233 def reconcile(self, device):
234 self.log.debug('function-entry', device=device)
235
236 # first we verify that we got parent reference and proxy info
237 assert device.parent_id
238 assert device.proxy_address.device_id
239
240 # register for proxied messages right away
241 self.proxy_address = device.proxy_address
242 self.adapter_agent.register_for_proxied_messages(device.proxy_address)
243
244 if self.enabled is not True:
245 self.log.info('reconciling-broadcom-onu-device')
246
247 self._init_pon_state(device)
248
249 # need to restart state machines on vcore restart. there is no indication to do it for us.
250 self._onu_omci_device.start()
251 device.reason = "restarting-openomci"
252 self.adapter_agent.update_device(device)
253
254 # TODO: this is probably a bit heavy handed
255 # Force a reboot for now. We need indications to reflow to reassign tconts and gems given vcore went away
256 # This may not be necessary when mib resync actually works
257 reactor.callLater(1, self.reboot)
258
259 self.enabled = True
260 else:
261 self.log.info('onu-already-activated')
262
263 @inlineCallbacks
264 def handle_onu_events(self):
265 event_msg = yield self.event_messages.get()
266 try:
267 if event_msg['event'] == 'download_tech_profile':
268 tp_path = event_msg['event_data']
269 uni_id = event_msg['uni_id']
270 self.load_and_configure_tech_profile(uni_id, tp_path)
271
272 except Exception as e:
273 self.log.error("exception-handling-onu-event", e=e)
274
275 # Handle next event
276 reactor.callLater(0, self.handle_onu_events)
277
Matt Jeanneret84e56f62019-02-26 10:48:09 -0500278 @inlineCallbacks
Matt Jeanneretf1e9c5d2019-02-08 07:41:29 -0500279 def _init_pon_state(self, device):
280 self.log.debug('function-entry', device=device)
281
282 self._pon = PonPort.create(self, self._pon_port_number)
Matt Jeanneret0c287892019-02-28 11:48:00 -0500283 self._pon.add_peer(self.parent_id, self._pon_port_number)
284 self.log.debug('adding-pon-port-to-agent', pon=self._pon.get_port())
285
Matt Jeannereta32441c2019-03-07 05:16:37 -0500286 yield self.core_proxy.port_created(device.id, self._pon.get_port())
Matt Jeanneretf1e9c5d2019-02-08 07:41:29 -0500287
Matt Jeanneret0c287892019-02-28 11:48:00 -0500288 self.log.debug('added-pon-port-to-agent', pon=self._pon.get_port())
Matt Jeanneretf1e9c5d2019-02-08 07:41:29 -0500289
290 # Create and start the OpenOMCI ONU Device Entry for this ONU
291 self._onu_omci_device = self.omci_agent.add_device(self.device_id,
Matt Jeannereta32441c2019-03-07 05:16:37 -0500292 self.core_proxy,
293 self.adapter_proxy,
Matt Jeanneretf1e9c5d2019-02-08 07:41:29 -0500294 support_classes=self.adapter.broadcom_omci,
295 custom_me_map=self.adapter.custom_me_entities())
296 # Port startup
297 if self._pon is not None:
298 self._pon.enabled = True
299
300 # TODO: move to UniPort
301 def update_logical_port(self, logical_device_id, port_id, state):
302 try:
303 self.log.info('updating-logical-port', logical_port_id=port_id,
304 logical_device_id=logical_device_id, state=state)
305 logical_port = self.adapter_agent.get_logical_port(logical_device_id,
306 port_id)
307 logical_port.ofp_port.state = state
308 self.adapter_agent.update_logical_port(logical_device_id,
309 logical_port)
310 except Exception as e:
311 self.log.exception("exception-updating-port", e=e)
312
313 def delete(self, device):
314 self.log.info('delete-onu', device=device)
315 if self.parent_adapter:
316 try:
317 self.parent_adapter.delete_child_device(self.parent_id, device)
318 except AttributeError:
319 self.log.debug('parent-device-delete-child-not-implemented')
320 else:
321 self.log.debug("parent-adapter-not-available")
322
323 def _create_tconts(self, uni_id, us_scheduler):
324 alloc_id = us_scheduler['alloc_id']
325 q_sched_policy = us_scheduler['q_sched_policy']
326 self.log.debug('create-tcont', us_scheduler=us_scheduler)
327
328 tcontdict = dict()
329 tcontdict['alloc-id'] = alloc_id
330 tcontdict['q_sched_policy'] = q_sched_policy
331 tcontdict['uni_id'] = uni_id
332
333 # TODO: Not sure what to do with any of this...
334 tddata = dict()
335 tddata['name'] = 'not-sure-td-profile'
336 tddata['fixed-bandwidth'] = "not-sure-fixed"
337 tddata['assured-bandwidth'] = "not-sure-assured"
338 tddata['maximum-bandwidth'] = "not-sure-max"
339 tddata['additional-bw-eligibility-indicator'] = "not-sure-additional"
340
341 td = OnuTrafficDescriptor.create(tddata)
342 tcont = OnuTCont.create(self, tcont=tcontdict, td=td)
343
344 self._pon.add_tcont(tcont)
345
346 self.log.debug('pon-add-tcont', tcont=tcont)
347
348 # Called when there is an olt up indication, providing the gem port id chosen by the olt handler
349 def _create_gemports(self, uni_id, gem_ports, alloc_id_ref, direction):
350 self.log.debug('create-gemport',
351 gem_ports=gem_ports, direction=direction)
352
353 for gem_port in gem_ports:
354 gemdict = dict()
355 gemdict['gemport_id'] = gem_port['gemport_id']
356 gemdict['direction'] = direction
357 gemdict['alloc_id_ref'] = alloc_id_ref
358 gemdict['encryption'] = gem_port['aes_encryption']
359 gemdict['discard_config'] = dict()
360 gemdict['discard_config']['max_probability'] = \
361 gem_port['discard_config']['max_probability']
362 gemdict['discard_config']['max_threshold'] = \
363 gem_port['discard_config']['max_threshold']
364 gemdict['discard_config']['min_threshold'] = \
365 gem_port['discard_config']['min_threshold']
366 gemdict['discard_policy'] = gem_port['discard_policy']
367 gemdict['max_q_size'] = gem_port['max_q_size']
368 gemdict['pbit_map'] = gem_port['pbit_map']
369 gemdict['priority_q'] = gem_port['priority_q']
370 gemdict['scheduling_policy'] = gem_port['scheduling_policy']
371 gemdict['weight'] = gem_port['weight']
372 gemdict['uni_id'] = uni_id
373
374 gem_port = OnuGemPort.create(self, gem_port=gemdict)
375
376 self._pon.add_gem_port(gem_port)
377
378 self.log.debug('pon-add-gemport', gem_port=gem_port)
379
380 def _do_tech_profile_configuration(self, uni_id, tp):
381 num_of_tconts = tp['num_of_tconts']
382 us_scheduler = tp['us_scheduler']
383 alloc_id = us_scheduler['alloc_id']
384 self._create_tconts(uni_id, us_scheduler)
385 upstream_gem_port_attribute_list = tp['upstream_gem_port_attribute_list']
386 self._create_gemports(uni_id, upstream_gem_port_attribute_list, alloc_id, "UPSTREAM")
387 downstream_gem_port_attribute_list = tp['downstream_gem_port_attribute_list']
388 self._create_gemports(uni_id, downstream_gem_port_attribute_list, alloc_id, "DOWNSTREAM")
389
390 def load_and_configure_tech_profile(self, uni_id, tp_path):
391 self.log.debug("loading-tech-profile-configuration", uni_id=uni_id, tp_path=tp_path)
392
393 if uni_id not in self._tp_service_specific_task:
394 self._tp_service_specific_task[uni_id] = dict()
395
396 if uni_id not in self._tech_profile_download_done:
397 self._tech_profile_download_done[uni_id] = dict()
398
399 if tp_path not in self._tech_profile_download_done[uni_id]:
400 self._tech_profile_download_done[uni_id][tp_path] = False
401
402 if not self._tech_profile_download_done[uni_id][tp_path]:
403 try:
404 if tp_path in self._tp_service_specific_task[uni_id]:
405 self.log.info("tech-profile-config-already-in-progress",
406 tp_path=tp_path)
407 return
408
409 tp = self.kv_client[tp_path]
410 tp = ast.literal_eval(tp)
411 self.log.debug("tp-instance", tp=tp)
412 self._do_tech_profile_configuration(uni_id, tp)
413
414 def success(_results):
415 self.log.info("tech-profile-config-done-successfully")
416 device = self.adapter_agent.get_device(self.device_id)
417 device.reason = 'tech-profile-config-download-success'
418 self.adapter_agent.update_device(device)
419 if tp_path in self._tp_service_specific_task[uni_id]:
420 del self._tp_service_specific_task[uni_id][tp_path]
421 self._tech_profile_download_done[uni_id][tp_path] = True
422
423 def failure(_reason):
424 self.log.warn('tech-profile-config-failure-retrying',
425 _reason=_reason)
426 device = self.adapter_agent.get_device(self.device_id)
427 device.reason = 'tech-profile-config-download-failure-retrying'
428 self.adapter_agent.update_device(device)
429 if tp_path in self._tp_service_specific_task[uni_id]:
430 del self._tp_service_specific_task[uni_id][tp_path]
431 self._deferred = reactor.callLater(_STARTUP_RETRY_WAIT, self.load_and_configure_tech_profile,
432 uni_id, tp_path)
433
434 self.log.info('downloading-tech-profile-configuration')
435 self._tp_service_specific_task[uni_id][tp_path] = \
436 BrcmTpServiceSpecificTask(self.omci_agent, self, uni_id)
437 self._deferred = \
438 self._onu_omci_device.task_runner.queue_task(self._tp_service_specific_task[uni_id][tp_path])
439 self._deferred.addCallbacks(success, failure)
440
441 except Exception as e:
442 self.log.exception("error-loading-tech-profile", e=e)
443 else:
444 self.log.info("tech-profile-config-already-done")
445
446 def update_pm_config(self, device, pm_config):
447 # TODO: This has not been tested
448 self.log.info('update_pm_config', pm_config=pm_config)
449 self.pm_metrics.update(pm_config)
450
451 # Calling this assumes the onu is active/ready and had at least an initial mib downloaded. This gets called from
452 # flow decomposition that ultimately comes from onos
453 def update_flow_table(self, device, flows):
454 self.log.debug('function-entry', device=device, flows=flows)
455
456 #
457 # We need to proxy through the OLT to get to the ONU
458 # Configuration from here should be using OMCI
459 #
460 # self.log.info('bulk-flow-update', device_id=device.id, flows=flows)
461
462 # no point in pushing omci flows if the device isnt reachable
463 if device.connect_status != ConnectStatus.REACHABLE or \
464 device.admin_state != AdminState.ENABLED:
465 self.log.warn("device-disabled-or-offline-skipping-flow-update",
466 admin=device.admin_state, connect=device.connect_status)
467 return
468
469 def is_downstream(port):
470 return port == self._pon_port_number
471
472 def is_upstream(port):
473 return not is_downstream(port)
474
475 for flow in flows:
476 _type = None
477 _port = None
478 _vlan_vid = None
479 _udp_dst = None
480 _udp_src = None
481 _ipv4_dst = None
482 _ipv4_src = None
483 _metadata = None
484 _output = None
485 _push_tpid = None
486 _field = None
487 _set_vlan_vid = None
488 self.log.debug('bulk-flow-update', device_id=device.id, flow=flow)
489 try:
490 _in_port = fd.get_in_port(flow)
491 assert _in_port is not None
492
493 _out_port = fd.get_out_port(flow) # may be None
494
495 if is_downstream(_in_port):
496 self.log.debug('downstream-flow', in_port=_in_port, out_port=_out_port)
497 uni_port = self.uni_port(_out_port)
498 elif is_upstream(_in_port):
499 self.log.debug('upstream-flow', in_port=_in_port, out_port=_out_port)
500 uni_port = self.uni_port(_in_port)
501 else:
502 raise Exception('port should be 1 or 2 by our convention')
503
504 self.log.debug('flow-ports', in_port=_in_port, out_port=_out_port, uni_port=str(uni_port))
505
506 for field in fd.get_ofb_fields(flow):
507 if field.type == fd.ETH_TYPE:
508 _type = field.eth_type
509 self.log.debug('field-type-eth-type',
510 eth_type=_type)
511
512 elif field.type == fd.IP_PROTO:
513 _proto = field.ip_proto
514 self.log.debug('field-type-ip-proto',
515 ip_proto=_proto)
516
517 elif field.type == fd.IN_PORT:
518 _port = field.port
519 self.log.debug('field-type-in-port',
520 in_port=_port)
521
522 elif field.type == fd.VLAN_VID:
523 _vlan_vid = field.vlan_vid & 0xfff
524 self.log.debug('field-type-vlan-vid',
525 vlan=_vlan_vid)
526
527 elif field.type == fd.VLAN_PCP:
528 _vlan_pcp = field.vlan_pcp
529 self.log.debug('field-type-vlan-pcp',
530 pcp=_vlan_pcp)
531
532 elif field.type == fd.UDP_DST:
533 _udp_dst = field.udp_dst
534 self.log.debug('field-type-udp-dst',
535 udp_dst=_udp_dst)
536
537 elif field.type == fd.UDP_SRC:
538 _udp_src = field.udp_src
539 self.log.debug('field-type-udp-src',
540 udp_src=_udp_src)
541
542 elif field.type == fd.IPV4_DST:
543 _ipv4_dst = field.ipv4_dst
544 self.log.debug('field-type-ipv4-dst',
545 ipv4_dst=_ipv4_dst)
546
547 elif field.type == fd.IPV4_SRC:
548 _ipv4_src = field.ipv4_src
549 self.log.debug('field-type-ipv4-src',
550 ipv4_dst=_ipv4_src)
551
552 elif field.type == fd.METADATA:
553 _metadata = field.table_metadata
554 self.log.debug('field-type-metadata',
555 metadata=_metadata)
556
557 else:
558 raise NotImplementedError('field.type={}'.format(
559 field.type))
560
561 for action in fd.get_actions(flow):
562
563 if action.type == fd.OUTPUT:
564 _output = action.output.port
565 self.log.debug('action-type-output',
566 output=_output, in_port=_in_port)
567
568 elif action.type == fd.POP_VLAN:
569 self.log.debug('action-type-pop-vlan',
570 in_port=_in_port)
571
572 elif action.type == fd.PUSH_VLAN:
573 _push_tpid = action.push.ethertype
574 self.log.debug('action-type-push-vlan',
575 push_tpid=_push_tpid, in_port=_in_port)
576 if action.push.ethertype != 0x8100:
577 self.log.error('unhandled-tpid',
578 ethertype=action.push.ethertype)
579
580 elif action.type == fd.SET_FIELD:
581 _field = action.set_field.field.ofb_field
582 assert (action.set_field.field.oxm_class ==
583 OFPXMC_OPENFLOW_BASIC)
584 self.log.debug('action-type-set-field',
585 field=_field, in_port=_in_port)
586 if _field.type == fd.VLAN_VID:
587 _set_vlan_vid = _field.vlan_vid & 0xfff
588 self.log.debug('set-field-type-vlan-vid',
589 vlan_vid=_set_vlan_vid)
590 else:
591 self.log.error('unsupported-action-set-field-type',
592 field_type=_field.type)
593 else:
594 self.log.error('unsupported-action-type',
595 action_type=action.type, in_port=_in_port)
596
597 # TODO: We only set vlan omci flows. Handle omci matching ethertypes at some point in another task
598 if _type is not None:
599 self.log.warn('ignoring-flow-with-ethType', ethType=_type)
600 elif _set_vlan_vid is None or _set_vlan_vid == 0:
601 self.log.warn('ignorning-flow-that-does-not-set-vlanid')
602 else:
603 self.log.warn('set-vlanid', uni_id=uni_port.port_number, set_vlan_vid=_set_vlan_vid)
604 self._add_vlan_filter_task(device, uni_port, _set_vlan_vid)
605
606 except Exception as e:
607 self.log.exception('failed-to-install-flow', e=e, flow=flow)
608
609
610 def _add_vlan_filter_task(self, device, uni_port, _set_vlan_vid):
611 assert uni_port is not None
612
613 def success(_results):
614 self.log.info('vlan-tagging-success', uni_port=uni_port, vlan=_set_vlan_vid)
615 device.reason = 'omci-flows-pushed'
616 self._vlan_filter_task = None
617
618 def failure(_reason):
619 self.log.warn('vlan-tagging-failure', uni_port=uni_port, vlan=_set_vlan_vid)
620 device.reason = 'omci-flows-failed-retrying'
621 self._vlan_filter_task = reactor.callLater(_STARTUP_RETRY_WAIT,
622 self._add_vlan_filter_task, device, uni_port, _set_vlan_vid)
623
624 self.log.info('setting-vlan-tag')
625 self._vlan_filter_task = BrcmVlanFilterTask(self.omci_agent, self.device_id, uni_port, _set_vlan_vid)
626 self._deferred = self._onu_omci_device.task_runner.queue_task(self._vlan_filter_task)
627 self._deferred.addCallbacks(success, failure)
628
629 def get_tx_id(self):
630 self.log.debug('function-entry')
631 self.tx_id += 1
632 return self.tx_id
633
Matt Jeannereta32441c2019-03-07 05:16:37 -0500634 def process_inter_adapter_message(self, request):
635 self.log.debug('process-inter-adapter-message', msg=request)
636 try:
637 if request.header.type == InterAdapterMessageType.OMCI_REQUEST:
638 omci_msg = InterAdapterOmciMessage()
639 request.body.Unpack(omci_msg)
640 self.log.debug('inter-adapter-recv-omci', omci_msg=omci_msg)
Matt Jeanneretf1e9c5d2019-02-08 07:41:29 -0500641
Matt Jeannereta32441c2019-03-07 05:16:37 -0500642 self.receive_message(omci_msg.message)
643
644 elif request.header.type == InterAdapterMessageType.ONU_IND_REQUEST:
645 onu_indication = OnuIndication()
646 request.body.Unpack(onu_indication)
647 self.log.debug('inter-adapter-recv-onu-ind', onu_indication=onu_indication)
648
649 if onu_indication.oper_state == "up":
650 self.create_interface(onu_indication)
651 elif onu_indication.oper_state == "down":
652 self.update_interface(onu_indication)
653 else:
654 self.log.error("unknown-onu-indication", onu_indication=onu_indication)
655
656 else:
657 self.log.error("inter-adapter-unhandled-type", request=request)
658
659 except Exception as e:
660 self.log.exception("error-processing-inter-adapter-message", e=e)
661
662 # Called each time there is an onu "up" indication from the olt handler
663 @inlineCallbacks
664 def create_interface(self, onu_indication):
665 self.log.debug('function-entry', onu_indication=onu_indication)
666 self._onu_indication = onu_indication
667
668 onu_device = yield self.core_proxy.get_device(self.device_id)
Matt Jeanneretf1e9c5d2019-02-08 07:41:29 -0500669
670 self.log.debug('starting-openomci-statemachine')
671 self._subscribe_to_events()
672 reactor.callLater(1, self._onu_omci_device.start)
673 onu_device.reason = "starting-openomci"
Matt Jeannereta32441c2019-03-07 05:16:37 -0500674 yield self.core_proxy.device_update(onu_device)
Matt Jeanneretf1e9c5d2019-02-08 07:41:29 -0500675 self._heartbeat.enabled = True
676
677 # Currently called each time there is an onu "down" indication from the olt handler
678 # TODO: possibly other reasons to "update" from the olt?
Matt Jeannereta32441c2019-03-07 05:16:37 -0500679 @inlineCallbacks
680 def update_interface(self, onu_indication):
681 self.log.debug('function-entry', onu_indication=onu_indication)
Matt Jeanneretf1e9c5d2019-02-08 07:41:29 -0500682
Matt Jeannereta32441c2019-03-07 05:16:37 -0500683 onu_device = yield self.core_proxy.get_device(self.device_id)
Matt Jeanneretf1e9c5d2019-02-08 07:41:29 -0500684
Matt Jeannereta32441c2019-03-07 05:16:37 -0500685 if onu_indication.oper_state == 'down':
Matt Jeanneretf1e9c5d2019-02-08 07:41:29 -0500686 self.log.debug('stopping-openomci-statemachine')
687 reactor.callLater(0, self._onu_omci_device.stop)
688
689 # Let TP download happen again
690 for uni_id in self._tp_service_specific_task:
691 self._tp_service_specific_task[uni_id].clear()
692 for uni_id in self._tech_profile_download_done:
693 self._tech_profile_download_done[uni_id].clear()
694
695 self.disable_ports(onu_device)
696 onu_device.reason = "stopping-openomci"
697 onu_device.connect_status = ConnectStatus.UNREACHABLE
698 onu_device.oper_status = OperStatus.DISCOVERED
699 self.adapter_agent.update_device(onu_device)
700 else:
701 self.log.debug('not-changing-openomci-statemachine')
702
703 # Not currently called by olt or anything else
704 def remove_interface(self, data):
705 self.log.debug('function-entry', data=data)
706
707 onu_device = self.adapter_agent.get_device(self.device_id)
708
709 self.log.debug('stopping-openomci-statemachine')
710 reactor.callLater(0, self._onu_omci_device.stop)
711
712 # Let TP download happen again
713 for uni_id in self._tp_service_specific_task:
714 self._tp_service_specific_task[uni_id].clear()
715 for uni_id in self._tech_profile_download_done:
716 self._tech_profile_download_done[uni_id].clear()
717
718 self.disable_ports(onu_device)
719 onu_device.reason = "stopping-openomci"
720 self.adapter_agent.update_device(onu_device)
721
722 # TODO: im sure there is more to do here
723
724 # Not currently called. Would be called presumably from the olt handler
725 def remove_gemport(self, data):
726 self.log.debug('remove-gemport', data=data)
Matt Jeanneretf1e9c5d2019-02-08 07:41:29 -0500727 device = self.adapter_agent.get_device(self.device_id)
728 if device.connect_status != ConnectStatus.REACHABLE:
729 self.log.error('device-unreachable')
730 return
731
732 # Not currently called. Would be called presumably from the olt handler
733 def remove_tcont(self, tcont_data, traffic_descriptor_data):
734 self.log.debug('remove-tcont', tcont_data=tcont_data, traffic_descriptor_data=traffic_descriptor_data)
735 device = self.adapter_agent.get_device(self.device_id)
736 if device.connect_status != ConnectStatus.REACHABLE:
737 self.log.error('device-unreachable')
738 return
739
740 # TODO: Create some omci task that encompases this what intended
741
742 # Not currently called. Would be called presumably from the olt handler
743 def create_multicast_gemport(self, data):
744 self.log.debug('function-entry', data=data)
745
746 # TODO: create objects and populate for later omci calls
747
748 def disable(self, device):
749 self.log.debug('function-entry', device=device)
750 try:
751 self.log.info('sending-uni-lock-towards-device', device=device)
752
753 def stop_anyway(reason):
754 # proceed with disable regardless if we could reach the onu. for example onu is unplugged
755 self.log.debug('stopping-openomci-statemachine')
756 reactor.callLater(0, self._onu_omci_device.stop)
757
758 # Let TP download happen again
759 for uni_id in self._tp_service_specific_task:
760 self._tp_service_specific_task[uni_id].clear()
761 for uni_id in self._tech_profile_download_done:
762 self._tech_profile_download_done[uni_id].clear()
763
764 self.disable_ports(device)
765 device.oper_status = OperStatus.UNKNOWN
766 device.reason = "omci-admin-lock"
767 self.adapter_agent.update_device(device)
768
769 # lock all the unis
770 task = BrcmUniLockTask(self.omci_agent, self.device_id, lock=True)
771 self._deferred = self._onu_omci_device.task_runner.queue_task(task)
772 self._deferred.addCallbacks(stop_anyway, stop_anyway)
773 except Exception as e:
774 log.exception('exception-in-onu-disable', exception=e)
775
776 def reenable(self, device):
777 self.log.debug('function-entry', device=device)
778 try:
779 # Start up OpenOMCI state machines for this device
780 # this will ultimately resync mib and unlock unis on successful redownloading the mib
781 self.log.debug('restarting-openomci-statemachine')
782 self._subscribe_to_events()
783 device.reason = "restarting-openomci"
784 self.adapter_agent.update_device(device)
785 reactor.callLater(1, self._onu_omci_device.start)
786 self._heartbeat.enabled = True
787 except Exception as e:
788 log.exception('exception-in-onu-reenable', exception=e)
789
790 def reboot(self):
791 self.log.info('reboot-device')
792 device = self.adapter_agent.get_device(self.device_id)
793 if device.connect_status != ConnectStatus.REACHABLE:
794 self.log.error("device-unreachable")
795 return
796
797 def success(_results):
798 self.log.info('reboot-success', _results=_results)
799 self.disable_ports(device)
800 device.connect_status = ConnectStatus.UNREACHABLE
801 device.oper_status = OperStatus.DISCOVERED
802 device.reason = "rebooting"
803 self.adapter_agent.update_device(device)
804
805 def failure(_reason):
806 self.log.info('reboot-failure', _reason=_reason)
807
808 self._deferred = self._onu_omci_device.reboot()
809 self._deferred.addCallbacks(success, failure)
810
811 def disable_ports(self, onu_device):
812 self.log.info('disable-ports', device_id=self.device_id,
813 onu_device=onu_device)
814
815 # Disable all ports on that device
816 self.adapter_agent.disable_all_ports(self.device_id)
817
818 parent_device = self.adapter_agent.get_device(onu_device.parent_id)
819 assert parent_device
820 logical_device_id = parent_device.parent_id
821 assert logical_device_id
822 ports = self.adapter_agent.get_ports(onu_device.id, Port.ETHERNET_UNI)
823 for port in ports:
824 port_id = 'uni-{}'.format(port.port_no)
825 # TODO: move to UniPort
826 self.update_logical_port(logical_device_id, port_id, OFPPS_LINK_DOWN)
827
828 def enable_ports(self, onu_device):
829 self.log.info('enable-ports', device_id=self.device_id, onu_device=onu_device)
830
831 # Disable all ports on that device
832 self.adapter_agent.enable_all_ports(self.device_id)
833
834 parent_device = self.adapter_agent.get_device(onu_device.parent_id)
835 assert parent_device
836 logical_device_id = parent_device.parent_id
837 assert logical_device_id
838 ports = self.adapter_agent.get_ports(onu_device.id, Port.ETHERNET_UNI)
839 for port in ports:
840 port_id = 'uni-{}'.format(port.port_no)
841 # TODO: move to UniPort
842 self.update_logical_port(logical_device_id, port_id, OFPPS_LIVE)
843
844 # Called just before openomci state machine is started. These listen for events from selected state machines,
845 # most importantly, mib in sync. Which ultimately leads to downloading the mib
846 def _subscribe_to_events(self):
847 self.log.debug('function-entry')
848
849 # OMCI MIB Database sync status
850 bus = self._onu_omci_device.event_bus
851 topic = OnuDeviceEntry.event_bus_topic(self.device_id,
852 OnuDeviceEvents.MibDatabaseSyncEvent)
853 self._in_sync_subscription = bus.subscribe(topic, self.in_sync_handler)
854
855 # OMCI Capabilities
856 bus = self._onu_omci_device.event_bus
857 topic = OnuDeviceEntry.event_bus_topic(self.device_id,
858 OnuDeviceEvents.OmciCapabilitiesEvent)
859 self._capabilities_subscription = bus.subscribe(topic, self.capabilties_handler)
860
861 # Called when the mib is in sync
862 def in_sync_handler(self, _topic, msg):
863 self.log.debug('function-entry', _topic=_topic, msg=msg)
864 if self._in_sync_subscription is not None:
865 try:
866 in_sync = msg[IN_SYNC_KEY]
867
868 if in_sync:
869 # Only call this once
870 bus = self._onu_omci_device.event_bus
871 bus.unsubscribe(self._in_sync_subscription)
872 self._in_sync_subscription = None
873
874 # Start up device_info load
875 self.log.debug('running-mib-sync')
876 reactor.callLater(0, self._mib_in_sync)
877
878 except Exception as e:
879 self.log.exception('in-sync', e=e)
880
881 def capabilties_handler(self, _topic, _msg):
882 self.log.debug('function-entry', _topic=_topic, msg=_msg)
883 if self._capabilities_subscription is not None:
884 self.log.debug('capabilities-handler-done')
885
886 # Mib is in sync, we can now query what we learned and actually start pushing ME (download) to the ONU.
887 # Currently uses a basic mib download task that create a bridge with a single gem port and uni, only allowing EAP
888 # Implement your own MibDownloadTask if you wish to setup something different by default
889 def _mib_in_sync(self):
890 self.log.debug('function-entry')
891
892 omci = self._onu_omci_device
893 in_sync = omci.mib_db_in_sync
894
895 device = self.adapter_agent.get_device(self.device_id)
896 device.reason = 'discovery-mibsync-complete'
897 self.adapter_agent.update_device(device)
898
899 if not self._dev_info_loaded:
900 self.log.info('loading-device-data-from-mib', in_sync=in_sync, already_loaded=self._dev_info_loaded)
901
902 omci_dev = self._onu_omci_device
903 config = omci_dev.configuration
904
905 # TODO: run this sooner somehow. shouldnt have to wait for mib sync to push an initial download
906 # In Sync, we can register logical ports now. Ideally this could occur on
907 # the first time we received a successful (no timeout) OMCI Rx response.
908 try:
909
910 # sort the lists so we get consistent port ordering.
911 ani_list = sorted(config.ani_g_entities) if config.ani_g_entities else []
912 uni_list = sorted(config.uni_g_entities) if config.uni_g_entities else []
913 pptp_list = sorted(config.pptp_entities) if config.pptp_entities else []
914 veip_list = sorted(config.veip_entities) if config.veip_entities else []
915
916 if ani_list is None or (pptp_list is None and veip_list is None):
917 device.reason = 'onu-missing-required-elements'
918 self.log.warn("no-ani-or-unis")
919 self.adapter_agent.update_device(device)
920 raise Exception("onu-missing-required-elements")
921
922 # Currently logging the ani, pptp, veip, and uni for information purposes.
923 # Actually act on the veip/pptp as its ME is the most correct one to use in later tasks.
924 # And in some ONU the UNI-G list is incomplete or incorrect...
925 for entity_id in ani_list:
926 ani_value = config.ani_g_entities[entity_id]
927 self.log.debug("discovered-ani", entity_id=entity_id, value=ani_value)
928 # TODO: currently only one OLT PON port/ANI, so this works out. With NGPON there will be 2..?
929 self._total_tcont_count = ani_value.get('total-tcont-count')
930 self.log.debug("set-total-tcont-count", tcont_count=self._total_tcont_count)
931
932 for entity_id in uni_list:
933 uni_value = config.uni_g_entities[entity_id]
934 self.log.debug("discovered-uni", entity_id=entity_id, value=uni_value)
935
936 uni_entities = OrderedDict()
937 for entity_id in pptp_list:
938 pptp_value = config.pptp_entities[entity_id]
939 self.log.debug("discovered-pptp", entity_id=entity_id, value=pptp_value)
940 uni_entities[entity_id] = UniType.PPTP
941
942 for entity_id in veip_list:
943 veip_value = config.veip_entities[entity_id]
944 self.log.debug("discovered-veip", entity_id=entity_id, value=veip_value)
945 uni_entities[entity_id] = UniType.VEIP
946
947 uni_id = 0
948 for entity_id, uni_type in uni_entities.iteritems():
949 try:
950 self._add_uni_port(entity_id, uni_id, uni_type)
951 uni_id += 1
952 except AssertionError as e:
953 self.log.warn("could not add UNI", entity_id=entity_id, uni_type=uni_type, e=e)
954
955 multi_uni = len(self._unis) > 1
956 for uni_port in self._unis.itervalues():
957 uni_port.add_logical_port(uni_port.port_number, multi_uni)
958
959 self.adapter_agent.update_device(device)
960
961 self._qos_flexibility = config.qos_configuration_flexibility or 0
962 self._omcc_version = config.omcc_version or OMCCVersion.Unknown
963
964 if self._unis:
965 self._dev_info_loaded = True
966 else:
967 device.reason = 'no-usable-unis'
968 self.adapter_agent.update_device(device)
969 self.log.warn("no-usable-unis")
970 raise Exception("no-usable-unis")
971
972 except Exception as e:
973 self.log.exception('device-info-load', e=e)
974 self._deferred = reactor.callLater(_STARTUP_RETRY_WAIT, self._mib_in_sync)
975
976 else:
977 self.log.info('device-info-already-loaded', in_sync=in_sync, already_loaded=self._dev_info_loaded)
978
979 if self._dev_info_loaded:
980 if device.admin_state == AdminState.ENABLED:
981 def success(_results):
982 self.log.info('mib-download-success', _results=_results)
983 device = self.adapter_agent.get_device(self.device_id)
984 device.reason = 'initial-mib-downloaded'
985 device.oper_status = OperStatus.ACTIVE
986 device.connect_status = ConnectStatus.REACHABLE
987 self.enable_ports(device)
988 self.adapter_agent.update_device(device)
989 self._mib_download_task = None
990
991 def failure(_reason):
992 self.log.warn('mib-download-failure-retrying', _reason=_reason)
993 device.reason = 'initial-mib-download-failure-retrying'
994 self.adapter_agent.update_device(device)
995 self._deferred = reactor.callLater(_STARTUP_RETRY_WAIT, self._mib_in_sync)
996
997 # Download an initial mib that creates simple bridge that can pass EAP. On success (above) finally set
998 # the device to active/reachable. This then opens up the handler to openflow pushes from outside
999 self.log.info('downloading-initial-mib-configuration')
1000 self._mib_download_task = BrcmMibDownloadTask(self.omci_agent, self)
1001 self._deferred = self._onu_omci_device.task_runner.queue_task(self._mib_download_task)
1002 self._deferred.addCallbacks(success, failure)
1003 else:
1004 self.log.info('admin-down-disabling')
1005 self.disable(device)
1006 else:
1007 self.log.info('device-info-not-loaded-skipping-mib-download')
1008
1009
1010 def _add_uni_port(self, entity_id, uni_id, uni_type=UniType.PPTP):
1011 self.log.debug('function-entry')
1012
1013 device = self.adapter_agent.get_device(self.device_id)
1014 parent_device = self.adapter_agent.get_device(device.parent_id)
1015
1016 parent_adapter_agent = registry('adapter_loader').get_agent(parent_device.adapter)
1017 if parent_adapter_agent is None:
1018 self.log.error('parent-adapter-could-not-be-retrieved')
1019
1020 # TODO: This knowledge is locked away in openolt. and it assumes one onu equals one uni...
1021 parent_device = self.adapter_agent.get_device(device.parent_id)
1022 parent_adapter = parent_adapter_agent.adapter.devices[parent_device.id]
1023 uni_no = parent_adapter.platform.mk_uni_port_num(
1024 self._onu_indication.intf_id, self._onu_indication.onu_id, uni_id)
1025
1026 # TODO: Some or parts of this likely need to move to UniPort. especially the format stuff
1027 uni_name = "uni-{}".format(uni_no)
1028
1029 mac_bridge_port_num = uni_id + 1 # TODO +1 is only to test non-zero index
1030
1031 self.log.debug('uni-port-inputs', uni_no=uni_no, uni_id=uni_id, uni_name=uni_name, uni_type=uni_type,
1032 entity_id=entity_id, mac_bridge_port_num=mac_bridge_port_num)
1033
1034 uni_port = UniPort.create(self, uni_name, uni_id, uni_no, uni_name, uni_type)
1035 uni_port.entity_id = entity_id
1036 uni_port.enabled = True
1037 uni_port.mac_bridge_port_num = mac_bridge_port_num
1038
1039 self.log.debug("created-uni-port", uni=uni_port)
1040
1041 self.adapter_agent.add_port(device.id, uni_port.get_port())
1042 parent_adapter_agent.add_port(device.parent_id, uni_port.get_port())
1043
1044 self._unis[uni_port.port_number] = uni_port
1045
1046 self._onu_omci_device.alarm_synchronizer.set_alarm_params(onu_id=self._onu_indication.onu_id,
1047 uni_ports=self._unis.values())
1048 # TODO: this should be in the PonPortclass
1049 pon_port = self._pon.get_port()
1050
1051 # Delete reference to my own UNI as peer from parent.
1052 # TODO why is this here, add_port_reference_to_parent already prunes duplicates
1053 me_as_peer = Port.PeerPort(device_id=device.parent_id, port_no=uni_port.port_number)
1054 partial_pon_port = Port(port_no=pon_port.port_no, label=pon_port.label,
1055 type=pon_port.type, admin_state=pon_port.admin_state,
1056 oper_status=pon_port.oper_status,
1057 peers=[me_as_peer]) # only list myself as a peer to avoid deleting all other UNIs from parent
1058 self.adapter_agent.delete_port_reference_from_parent(self.device_id, partial_pon_port)
1059
1060 pon_port.peers.extend([me_as_peer])
1061
1062 self._pon._port = pon_port
1063
1064 self.adapter_agent.add_port_reference_to_parent(self.device_id,
1065 pon_port)