blob: 500be83b3216d6f9ce26e17ebb28c269c4e7b87b [file] [log] [blame]
William Kurkian6f436d02019-02-06 16:25:01 -05001#
2# Copyright 2018 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#
16import threading
17import binascii
18import grpc
19import socket
20import re
21import structlog
William Kurkianfefd4642019-02-07 15:30:03 -050022import time
William Kurkian6f436d02019-02-06 16:25:01 -050023from twisted.internet import reactor
William Kurkian92bd7122019-02-14 15:26:59 -050024from twisted.internet.defer import inlineCallbacks, returnValue
William Kurkian6f436d02019-02-06 16:25:01 -050025from scapy.layers.l2 import Ether, Dot1Q
26from transitions import Machine
27
William Kurkian44cd7bb2019-02-11 16:39:12 -050028from pyvoltha.protos import openolt_pb2_grpc, openolt_pb2
William Kurkian6f436d02019-02-06 16:25:01 -050029
William Kurkian44cd7bb2019-02-11 16:39:12 -050030from pyvoltha.adapters.extensions.alarms.onu.onu_discovery_alarm import OnuDiscoveryAlarm
William Kurkian6f436d02019-02-06 16:25:01 -050031
William Kurkian44cd7bb2019-02-11 16:39:12 -050032from pyvoltha.common.utils.nethelpers import mac_str_to_tuple
33from pyvoltha.protos.openflow_13_pb2 import OFPPS_LIVE, OFPPF_FIBER, \
William Kurkian6f436d02019-02-06 16:25:01 -050034 OFPPS_LINK_DOWN, OFPPF_1GB_FD, \
35 OFPC_GROUP_STATS, OFPC_PORT_STATS, OFPC_TABLE_STATS, OFPC_FLOW_STATS, \
36 ofp_switch_features, ofp_port, ofp_port_stats, ofp_desc
William Kurkian44cd7bb2019-02-11 16:39:12 -050037from pyvoltha.common.utils.registry import registry
38from pyvoltha.protos import third_party
39from pyvoltha.protos.common_pb2 import AdminState, OperStatus, ConnectStatus
40from pyvoltha.protos.common_pb2 import LogLevel
41from pyvoltha.protos.device_pb2 import Port, Device
William Kurkian6f436d02019-02-06 16:25:01 -050042
William Kurkian44cd7bb2019-02-11 16:39:12 -050043from pyvoltha.protos.logical_device_pb2 import LogicalDevice, LogicalPort
William Kurkian6f436d02019-02-06 16:25:01 -050044
Matt Jeanneret9fd36df2019-02-14 19:14:36 -050045
William Kurkian6f436d02019-02-06 16:25:01 -050046class OpenoltDevice(object):
47 """
48 OpenoltDevice state machine:
49
50 null ----> init ------> connected -----> up -----> down
51 ^ ^ | ^ | |
52 | | | | | |
53 | +-------------+ +---------+ |
54 | |
55 +-----------------------------------------+
56 """
57 # pylint: disable=too-many-instance-attributes
58 # pylint: disable=R0904
59 states = [
60 'state_null',
61 'state_init',
62 'state_connected',
63 'state_up',
64 'state_down']
65
66 transitions = [
67 {'trigger': 'go_state_init',
68 'source': ['state_null', 'state_connected', 'state_down'],
69 'dest': 'state_init',
70 'before': 'do_state_init',
71 'after': 'post_init'},
72 {'trigger': 'go_state_connected',
73 'source': 'state_init',
74 'dest': 'state_connected',
75 'before': 'do_state_connected'},
76 {'trigger': 'go_state_up',
77 'source': ['state_connected', 'state_down'],
78 'dest': 'state_up',
79 'before': 'do_state_up'},
80 {'trigger': 'go_state_down',
81 'source': ['state_up'],
82 'dest': 'state_down',
83 'before': 'do_state_down',
84 'after': 'post_down'}]
85
86 def __init__(self, **kwargs):
87 super(OpenoltDevice, self).__init__()
88
Matt Jeanneret7906d232019-02-14 14:57:38 -050089 self.adapter_proxy = kwargs['adapter_proxy']
William Kurkian6f436d02019-02-06 16:25:01 -050090 self.adapter_agent = kwargs['adapter_agent']
91 self.device_num = kwargs['device_num']
92 device = kwargs['device']
93
94 self.platform_class = kwargs['support_classes']['platform']
95 self.resource_mgr_class = kwargs['support_classes']['resource_mgr']
96 self.flow_mgr_class = kwargs['support_classes']['flow_mgr']
97 self.alarm_mgr_class = kwargs['support_classes']['alarm_mgr']
98 self.stats_mgr_class = kwargs['support_classes']['stats_mgr']
99 self.bw_mgr_class = kwargs['support_classes']['bw_mgr']
Matt Jeanneret7906d232019-02-14 14:57:38 -0500100
William Kurkian6f436d02019-02-06 16:25:01 -0500101 is_reconciliation = kwargs.get('reconciliation', False)
102 self.device_id = device.id
103 self.host_and_port = device.host_and_port
104 self.extra_args = device.extra_args
105 self.log = structlog.get_logger(id=self.device_id,
106 ip=self.host_and_port)
Matt Jeanneret6e315092019-02-20 10:42:57 -0500107
108 # TODO NEW CORE: this isnt implemented. Need to use kafka api calls to get device info
Matt Jeanneret9fd36df2019-02-14 19:14:36 -0500109 # self.proxy = registry('core').get_proxy('/')
William Kurkian6f436d02019-02-06 16:25:01 -0500110
111 self.log.info('openolt-device-init')
112
113 # default device id and device serial number. If device_info provides better results, they will be updated
114 self.dpid = kwargs.get('dp_id')
115 self.serial_number = self.host_and_port # FIXME
116
117 # Device already set in the event of reconciliation
118 if not is_reconciliation:
119 self.log.info('updating-device')
120 # It is a new device
121 # Update device
122 device.root = True
123 device.connect_status = ConnectStatus.UNREACHABLE
124 device.oper_status = OperStatus.ACTIVATING
William Kurkianfefd4642019-02-07 15:30:03 -0500125 self.adapter_agent.device_update(device)
William Kurkian6f436d02019-02-06 16:25:01 -0500126
127 # If logical device does exist use it, else create one after connecting to device
128 if device.parent_id:
129 # logical device already exists
130 self.logical_device_id = device.parent_id
131 if is_reconciliation:
132 self.adapter_agent.reconcile_logical_device(
133 self.logical_device_id)
134
135 # Initialize the OLT state machine
136 self.machine = Machine(model=self, states=OpenoltDevice.states,
137 transitions=OpenoltDevice.transitions,
138 send_event=True, initial='state_null')
139 self.go_state_init()
140
Matt Jeanneret9fd36df2019-02-14 19:14:36 -0500141 def create_logical_device(self, device_info):
William Kurkian6f436d02019-02-06 16:25:01 -0500142 dpid = device_info.device_id
143 serial_number = device_info.device_serial_number
144
145 if dpid is None: dpid = self.dpid
146 if serial_number is None: serial_number = self.serial_number
147
148 if dpid == None or dpid == '':
149 uri = self.host_and_port.split(":")[0]
150 try:
151 socket.inet_pton(socket.AF_INET, uri)
152 dpid = '00:00:' + self.ip_hex(uri)
153 except socket.error:
154 # this is not an IP
155 dpid = self.stringToMacAddr(uri)
156
157 if serial_number == None or serial_number == '':
158 serial_number = self.host_and_port
159
160 self.log.info('creating-openolt-logical-device', dp_id=dpid, serial_number=serial_number)
161
162 mfr_desc = device_info.vendor
163 sw_desc = device_info.firmware_version
164 hw_desc = device_info.model
165 if device_info.hardware_version: hw_desc += '-' + device_info.hardware_version
William Kurkian92bd7122019-02-14 15:26:59 -0500166
William Kurkian6f436d02019-02-06 16:25:01 -0500167 # Create logical OF device
168 ld = LogicalDevice(
169 root_device_id=self.device_id,
170 switch_features=ofp_switch_features(
171 n_buffers=256, # TODO fake for now
172 n_tables=2, # TODO ditto
173 capabilities=( # TODO and ditto
174 OFPC_FLOW_STATS
175 | OFPC_TABLE_STATS
176 | OFPC_PORT_STATS
177 | OFPC_GROUP_STATS
178 )
179 ),
180 desc=ofp_desc(
181 serial_num=serial_number
182 )
183 )
184 ld_init = self.adapter_agent.create_logical_device(ld,
William Kurkian92bd7122019-02-14 15:26:59 -0500185 dpid=dpid)
186
William Kurkian6f436d02019-02-06 16:25:01 -0500187 self.logical_device_id = ld_init.id
188
189 device = self.adapter_agent.get_device(self.device_id)
190 device.serial_number = serial_number
William Kurkian92bd7122019-02-14 15:26:59 -0500191 self.adapter_agent.update_device(device)
William Kurkian6f436d02019-02-06 16:25:01 -0500192
193 self.dpid = dpid
194 self.serial_number = serial_number
195
196 self.log.info('created-openolt-logical-device', logical_device_id=ld_init.id)
197
198 def stringToMacAddr(self, uri):
199 regex = re.compile('[^a-zA-Z]')
200 uri = regex.sub('', uri)
201
202 l = len(uri)
203 if l > 6:
204 uri = uri[0:6]
205 else:
206 uri = uri + uri[0:6 - l]
207
William Kurkian6f436d02019-02-06 16:25:01 -0500208 return ":".join([hex(ord(x))[-2:] for x in uri])
209
210 def do_state_init(self, event):
211 # Initialize gRPC
Matt Jeanneret7906d232019-02-14 14:57:38 -0500212 self.log.debug("grpc-host-port", self.host_and_port)
William Kurkian6f436d02019-02-06 16:25:01 -0500213 self.channel = grpc.insecure_channel(self.host_and_port)
214 self.channel_ready_future = grpc.channel_ready_future(self.channel)
215
216 self.log.info('openolt-device-created', device_id=self.device_id)
217
218 def post_init(self, event):
219 self.log.debug('post_init')
220
221 # We have reached init state, starting the indications thread
222
223 # Catch RuntimeError exception
224 try:
225 # Start indications thread
226 self.indications_thread_handle = threading.Thread(
227 target=self.indications_thread)
228 # Old getter/setter API for daemon; use it directly as a
229 # property instead. The Jinkins error will happon on the reason of
230 # Exception in thread Thread-1 (most likely raised # during
231 # interpreter shutdown)
Matt Jeanneret7906d232019-02-14 14:57:38 -0500232 self.log.debug('starting indications thread')
William Kurkian6f436d02019-02-06 16:25:01 -0500233 self.indications_thread_handle.setDaemon(True)
234 self.indications_thread_handle.start()
235 except Exception as e:
236 self.log.exception('post_init failed', e=e)
237
238 def do_state_connected(self, event):
239 self.log.debug("do_state_connected")
240
241 device = self.adapter_agent.get_device(self.device_id)
242
243 self.stub = openolt_pb2_grpc.OpenoltStub(self.channel)
244
William Kurkianfefd4642019-02-07 15:30:03 -0500245 delay = 1
246 while True:
247 try:
248 device_info = self.stub.GetDeviceInfo(openolt_pb2.Empty())
249 break
250 except Exception as e:
251 reraise = True
252 if delay > 120:
253 self.log.error("gRPC failure too many times")
254 else:
255 self.log.warn("gRPC failure, retry in %ds: %s"
256 % (delay, repr(e)))
257 time.sleep(delay)
258 delay += delay
259 reraise = False
260
261 if reraise:
262 raise
263
William Kurkian6f436d02019-02-06 16:25:01 -0500264 self.log.info('Device connected', device_info=device_info)
265
Matt Jeanneret7906d232019-02-14 14:57:38 -0500266 # self.create_logical_device(device_info)
267 self.logical_device_id = 0
William Kurkian6f436d02019-02-06 16:25:01 -0500268 device.serial_number = self.serial_number
Matt Jeanneret7906d232019-02-14 14:57:38 -0500269
William Kurkian6f436d02019-02-06 16:25:01 -0500270 self.resource_mgr = self.resource_mgr_class(self.device_id,
271 self.host_and_port,
272 self.extra_args,
273 device_info)
274 self.platform = self.platform_class(self.log, self.resource_mgr)
275 self.flow_mgr = self.flow_mgr_class(self.adapter_agent, self.log,
276 self.stub, self.device_id,
277 self.logical_device_id,
278 self.platform, self.resource_mgr)
279
280 self.alarm_mgr = self.alarm_mgr_class(self.log, self.adapter_agent,
281 self.device_id,
282 self.logical_device_id,
283 self.platform)
Matt Jeanneret7906d232019-02-14 14:57:38 -0500284 self.stats_mgr = self.stats_mgr_class(self, self.log, self.platform)
William Kurkian92bd7122019-02-14 15:26:59 -0500285 self.bw_mgr = self.bw_mgr_class(self.log, self.adapter_agent)
Matt Jeanneret7906d232019-02-14 14:57:38 -0500286
William Kurkian6f436d02019-02-06 16:25:01 -0500287 device.vendor = device_info.vendor
288 device.model = device_info.model
289 device.hardware_version = device_info.hardware_version
290 device.firmware_version = device_info.firmware_version
291
292 # TODO: check for uptime and reboot if too long (VOL-1192)
293
294 device.connect_status = ConnectStatus.REACHABLE
Matt Jeanneret9fd36df2019-02-14 19:14:36 -0500295 device.mac_address = "AA:BB:CC:DD:EE:FF"
William Kurkianfefd4642019-02-07 15:30:03 -0500296 self.adapter_agent.device_update(device)
Matt Jeanneret9fd36df2019-02-14 19:14:36 -0500297
Matt Jeanneret6e315092019-02-20 10:42:57 -0500298
299 @inlineCallbacks
William Kurkian6f436d02019-02-06 16:25:01 -0500300 def do_state_up(self, event):
301 self.log.debug("do_state_up")
302
Matt Jeanneret6e315092019-02-20 10:42:57 -0500303 yield self.adapter_agent.device_state_update(self.device_id,
Matt Jeanneret9fd36df2019-02-14 19:14:36 -0500304 connect_status=ConnectStatus.REACHABLE,
305 oper_status=OperStatus.ACTIVE)
William Kurkian6f436d02019-02-06 16:25:01 -0500306
307 def do_state_down(self, event):
308 self.log.debug("do_state_down")
309 oper_state = OperStatus.UNKNOWN
310 connect_state = ConnectStatus.UNREACHABLE
311
312 # Propagating to the children
313
314 # Children ports
315 child_devices = self.adapter_agent.get_child_devices(self.device_id)
316 for onu_device in child_devices:
317 onu_adapter_agent = \
318 registry('adapter_loader').get_agent(onu_device.adapter)
319 onu_adapter_agent.update_interface(onu_device,
320 {'oper_state': 'down'})
321 self.onu_ports_down(onu_device, oper_state)
322
323 # Children devices
324 self.adapter_agent.update_child_devices_state(
325 self.device_id, oper_status=oper_state,
326 connect_status=connect_state)
327 # Device Ports
328 device_ports = self.adapter_agent.get_ports(self.device_id,
329 Port.ETHERNET_NNI)
330 logical_ports_ids = [port.label for port in device_ports]
331 device_ports += self.adapter_agent.get_ports(self.device_id,
332 Port.PON_OLT)
333
334 for port in device_ports:
335 port.oper_status = oper_state
336 self.adapter_agent.add_port(self.device_id, port)
337
338 # Device logical port
339 for logical_port_id in logical_ports_ids:
340 logical_port = self.adapter_agent.get_logical_port(
341 self.logical_device_id, logical_port_id)
342 logical_port.ofp_port.state = OFPPS_LINK_DOWN
343 self.adapter_agent.update_logical_port(self.logical_device_id,
344 logical_port)
345
346 # Device
347 device = self.adapter_agent.get_device(self.device_id)
348 device.oper_status = oper_state
349 device.connect_status = connect_state
350
William Kurkianfefd4642019-02-07 15:30:03 -0500351 reactor.callLater(2, self.adapter_agent.device_update, device)
William Kurkian6f436d02019-02-06 16:25:01 -0500352
353 # def post_up(self, event):
354 # self.log.debug('post-up')
355 # self.flow_mgr.reseed_flows()
356
357 def post_down(self, event):
358 self.log.debug('post_down')
359 self.flow_mgr.reset_flows()
360
361 def indications_thread(self):
362 self.log.debug('starting-indications-thread')
363 self.log.debug('connecting to olt', device_id=self.device_id)
364 self.channel_ready_future.result() # blocking call
365 self.log.info('connected to olt', device_id=self.device_id)
366 self.go_state_connected()
367
368 self.indications = self.stub.EnableIndication(openolt_pb2.Empty())
369
370 while True:
371 try:
372 # get the next indication from olt
373 ind = next(self.indications)
374 except Exception as e:
375 self.log.warn('gRPC connection lost', error=e)
376 reactor.callFromThread(self.go_state_down)
377 reactor.callFromThread(self.go_state_init)
378 break
379 else:
380 self.log.debug("rx indication", indication=ind)
381
382 # indication handlers run in the main event loop
383 if ind.HasField('olt_ind'):
384 reactor.callFromThread(self.olt_indication, ind.olt_ind)
385 elif ind.HasField('intf_ind'):
386 reactor.callFromThread(self.intf_indication, ind.intf_ind)
387 elif ind.HasField('intf_oper_ind'):
388 reactor.callFromThread(self.intf_oper_indication,
389 ind.intf_oper_ind)
390 elif ind.HasField('onu_disc_ind'):
391 reactor.callFromThread(self.onu_discovery_indication,
392 ind.onu_disc_ind)
393 elif ind.HasField('onu_ind'):
394 reactor.callFromThread(self.onu_indication, ind.onu_ind)
395 elif ind.HasField('omci_ind'):
396 reactor.callFromThread(self.omci_indication, ind.omci_ind)
397 elif ind.HasField('pkt_ind'):
398 reactor.callFromThread(self.packet_indication, ind.pkt_ind)
399 elif ind.HasField('port_stats'):
400 reactor.callFromThread(
401 self.stats_mgr.port_statistics_indication,
402 ind.port_stats)
403 elif ind.HasField('flow_stats'):
404 reactor.callFromThread(
405 self.stats_mgr.flow_statistics_indication,
406 ind.flow_stats)
407 elif ind.HasField('alarm_ind'):
408 reactor.callFromThread(self.alarm_mgr.process_alarms,
409 ind.alarm_ind)
410 else:
411 self.log.warn('unknown indication type')
412
413 def olt_indication(self, olt_indication):
414 if olt_indication.oper_state == "up":
415 self.go_state_up()
416 elif olt_indication.oper_state == "down":
417 self.go_state_down()
418
419 def intf_indication(self, intf_indication):
420 self.log.debug("intf indication", intf_id=intf_indication.intf_id,
421 oper_state=intf_indication.oper_state)
422
423 if intf_indication.oper_state == "up":
424 oper_status = OperStatus.ACTIVE
425 else:
426 oper_status = OperStatus.DISCOVERED
427
428 # add_port update the port if it exists
429 self.add_port(intf_indication.intf_id, Port.PON_OLT, oper_status)
430
431 def intf_oper_indication(self, intf_oper_indication):
432 self.log.debug("Received interface oper state change indication",
433 intf_id=intf_oper_indication.intf_id,
434 type=intf_oper_indication.type,
435 oper_state=intf_oper_indication.oper_state)
436
437 if intf_oper_indication.oper_state == "up":
438 oper_state = OperStatus.ACTIVE
439 else:
440 oper_state = OperStatus.DISCOVERED
441
442 if intf_oper_indication.type == "nni":
443
444 # add_(logical_)port update the port if it exists
445 port_no, label = self.add_port(intf_oper_indication.intf_id,
446 Port.ETHERNET_NNI, oper_state)
447 self.log.debug("int_oper_indication", port_no=port_no, label=label)
Matt Jeanneret6e315092019-02-20 10:42:57 -0500448
449 # TODO NEW CORE: Is this needed anymore, or does the new core synthesize this
450 #self.add_logical_port(port_no, intf_oper_indication.intf_id,
451 # oper_state)
William Kurkian6f436d02019-02-06 16:25:01 -0500452
453 elif intf_oper_indication.type == "pon":
454 # FIXME - handle PON oper state change
455 pass
456
Matt Jeanneret6e315092019-02-20 10:42:57 -0500457 @inlineCallbacks
William Kurkian6f436d02019-02-06 16:25:01 -0500458 def onu_discovery_indication(self, onu_disc_indication):
459 intf_id = onu_disc_indication.intf_id
460 serial_number = onu_disc_indication.serial_number
461
462 serial_number_str = self.stringify_serial_number(serial_number)
463
464 self.log.debug("onu discovery indication", intf_id=intf_id,
465 serial_number=serial_number_str)
466
467 # Post ONU Discover alarm 20180809_0805
468 try:
469 OnuDiscoveryAlarm(self.alarm_mgr.alarms, pon_id=intf_id,
470 serial_number=serial_number_str).raise_alarm()
471 except Exception as disc_alarm_error:
472 self.log.exception("onu-discovery-alarm-error",
473 errmsg=disc_alarm_error.message)
474 # continue for now.
475
Matt Jeanneret6e315092019-02-20 10:42:57 -0500476 # TODO NEW CORE: this isnt implemented... cheat for now
477 #onu_device = yield self.adapter_agent.get_child_device(
478 # self.device_id,
479 # channel_id=serial_number_str)
480 onu_device = None
William Kurkian6f436d02019-02-06 16:25:01 -0500481
482 if onu_device is None:
483 try:
484 onu_id = self.resource_mgr.get_onu_id(intf_id)
485 if onu_id is None:
486 raise Exception("onu-id-unavailable")
487
488 self.add_onu_device(
489 intf_id,
490 self.platform.intf_id_to_port_no(intf_id, Port.PON_OLT),
491 onu_id, serial_number)
492 self.activate_onu(intf_id, onu_id, serial_number,
493 serial_number_str)
494 except Exception as e:
495 self.log.exception('onu-activation-failed', e=e)
496
497 else:
498 if onu_device.connect_status != ConnectStatus.REACHABLE:
499 onu_device.connect_status = ConnectStatus.REACHABLE
William Kurkianfefd4642019-02-07 15:30:03 -0500500 self.adapter_agent.device_update(onu_device)
William Kurkian6f436d02019-02-06 16:25:01 -0500501
502 onu_id = onu_device.proxy_address.onu_id
503 if onu_device.oper_status == OperStatus.DISCOVERED \
504 or onu_device.oper_status == OperStatus.ACTIVATING:
505 self.log.debug("ignore onu discovery indication, \
506 the onu has been discovered and should be \
507 activating shorlty", intf_id=intf_id,
508 onu_id=onu_id, state=onu_device.oper_status)
509 elif onu_device.oper_status == OperStatus.ACTIVE:
510 self.log.warn("onu discovery indication whereas onu is \
511 supposed to be active",
512 intf_id=intf_id, onu_id=onu_id,
513 state=onu_device.oper_status)
514 elif onu_device.oper_status == OperStatus.UNKNOWN:
515 self.log.info("onu in unknown state, recovering from olt \
516 reboot probably, activate onu", intf_id=intf_id,
517 onu_id=onu_id, serial_number=serial_number_str)
518
519 onu_device.oper_status = OperStatus.DISCOVERED
William Kurkianfefd4642019-02-07 15:30:03 -0500520 self.adapter_agent.device_update(onu_device)
William Kurkian6f436d02019-02-06 16:25:01 -0500521 try:
522 self.activate_onu(intf_id, onu_id, serial_number,
523 serial_number_str)
524 except Exception as e:
525 self.log.error('onu-activation-error',
526 serial_number=serial_number_str, error=e)
527 else:
528 self.log.warn('unexpected state', onu_id=onu_id,
529 onu_device_oper_state=onu_device.oper_status)
530
531 def onu_indication(self, onu_indication):
532 self.log.debug("onu indication", intf_id=onu_indication.intf_id,
533 onu_id=onu_indication.onu_id,
534 serial_number=onu_indication.serial_number,
535 oper_state=onu_indication.oper_state,
536 admin_state=onu_indication.admin_state)
537 try:
538 serial_number_str = self.stringify_serial_number(
539 onu_indication.serial_number)
540 except Exception as e:
541 serial_number_str = None
542
543 if serial_number_str is not None:
544 onu_device = self.adapter_agent.get_child_device(
545 self.device_id,
546 serial_number=serial_number_str)
547 else:
548 onu_device = self.adapter_agent.get_child_device(
549 self.device_id,
550 parent_port_no=self.platform.intf_id_to_port_no(
551 onu_indication.intf_id, Port.PON_OLT),
552 onu_id=onu_indication.onu_id)
553
554 if onu_device is None:
555 self.log.error('onu not found', intf_id=onu_indication.intf_id,
556 onu_id=onu_indication.onu_id)
557 return
558
559 if self.platform.intf_id_from_pon_port_no(onu_device.parent_port_no) \
560 != onu_indication.intf_id:
561 self.log.warn('ONU-is-on-a-different-intf-id-now',
562 previous_intf_id=self.platform.intf_id_from_pon_port_no(
563 onu_device.parent_port_no),
564 current_intf_id=onu_indication.intf_id)
565 # FIXME - handle intf_id mismatch (ONU move?)
566
567 if onu_device.proxy_address.onu_id != onu_indication.onu_id:
568 # FIXME - handle onu id mismatch
569 self.log.warn('ONU-id-mismatch, can happen if both voltha and '
570 'the olt rebooted',
571 expected_onu_id=onu_device.proxy_address.onu_id,
572 received_onu_id=onu_indication.onu_id)
573
574 # Admin state
575 if onu_indication.admin_state == 'down':
576 if onu_indication.oper_state != 'down':
577 self.log.error('ONU-admin-state-down-and-oper-status-not-down',
578 oper_state=onu_indication.oper_state)
579 # Forcing the oper state change code to execute
580 onu_indication.oper_state = 'down'
581
582 # Port and logical port update is taken care of by oper state block
583
584 elif onu_indication.admin_state == 'up':
585 pass
586
587 else:
588 self.log.warn('Invalid-or-not-implemented-admin-state',
589 received_admin_state=onu_indication.admin_state)
590
591 self.log.debug('admin-state-dealt-with')
592
593 onu_adapter_agent = \
594 registry('adapter_loader').get_agent(onu_device.adapter)
595 if onu_adapter_agent is None:
596 self.log.error('onu_adapter_agent-could-not-be-retrieved',
597 onu_device=onu_device)
598 return
599
600 # Operating state
601 if onu_indication.oper_state == 'down':
602
603 if onu_device.connect_status != ConnectStatus.UNREACHABLE:
604 onu_device.connect_status = ConnectStatus.UNREACHABLE
William Kurkianfefd4642019-02-07 15:30:03 -0500605 self.adapter_agent.device_update(onu_device)
William Kurkian6f436d02019-02-06 16:25:01 -0500606
607 # Move to discovered state
608 self.log.debug('onu-oper-state-is-down')
609
610 if onu_device.oper_status != OperStatus.DISCOVERED:
611 onu_device.oper_status = OperStatus.DISCOVERED
William Kurkianfefd4642019-02-07 15:30:03 -0500612 self.adapter_agent.device_update(onu_device)
William Kurkian6f436d02019-02-06 16:25:01 -0500613 # Set port oper state to Discovered
614 self.onu_ports_down(onu_device, OperStatus.DISCOVERED)
615
616 onu_adapter_agent.update_interface(onu_device,
617 {'oper_state': 'down'})
618
619 elif onu_indication.oper_state == 'up':
620
621 if onu_device.connect_status != ConnectStatus.REACHABLE:
622 onu_device.connect_status = ConnectStatus.REACHABLE
William Kurkianfefd4642019-02-07 15:30:03 -0500623 self.adapter_agent.device_update(onu_device)
William Kurkian6f436d02019-02-06 16:25:01 -0500624
625 if onu_device.oper_status != OperStatus.DISCOVERED:
626 self.log.debug("ignore onu indication",
627 intf_id=onu_indication.intf_id,
628 onu_id=onu_indication.onu_id,
629 state=onu_device.oper_status,
630 msg_oper_state=onu_indication.oper_state)
631 return
632
633 # Device was in Discovered state, setting it to active
634
635 # Prepare onu configuration
636
637 onu_adapter_agent.create_interface(onu_device, onu_indication)
638
639 else:
640 self.log.warn('Not-implemented-or-invalid-value-of-oper-state',
641 oper_state=onu_indication.oper_state)
642
643 def onu_ports_down(self, onu_device, oper_state):
644 # Set port oper state to Discovered
645 # add port will update port if it exists
646 # self.adapter_agent.add_port(
647 # self.device_id,
648 # Port(
649 # port_no=uni_no,
650 # label=uni_name,
651 # type=Port.ETHERNET_UNI,
652 # admin_state=onu_device.admin_state,
653 # oper_status=oper_state))
654 # TODO this should be downning ports in onu adatper
655
656 # Disable logical port
657 onu_ports = self.proxy.get('devices/{}/ports'.format(onu_device.id))
658 for onu_port in onu_ports:
659 self.log.debug('onu-ports-down', onu_port=onu_port)
660 onu_port_id = onu_port.label
661 try:
662 onu_logical_port = self.adapter_agent.get_logical_port(
663 logical_device_id=self.logical_device_id, port_id=onu_port_id)
664 onu_logical_port.ofp_port.state = OFPPS_LINK_DOWN
665 self.adapter_agent.update_logical_port(
666 logical_device_id=self.logical_device_id,
667 port=onu_logical_port)
668 self.log.debug('cascading-oper-state-to-port-and-logical-port')
669 except KeyError as e:
670 self.log.error('matching-onu-port-label-invalid',
671 onu_id=onu_device.id, olt_id=self.device_id,
672 onu_ports=onu_ports, onu_port_id=onu_port_id,
673 error=e)
674
675 def omci_indication(self, omci_indication):
676
677 self.log.debug("omci indication", intf_id=omci_indication.intf_id,
678 onu_id=omci_indication.onu_id)
679
680 onu_device = self.adapter_agent.get_child_device(
681 self.device_id, onu_id=omci_indication.onu_id,
682 parent_port_no=self.platform.intf_id_to_port_no(
683 omci_indication.intf_id, Port.PON_OLT), )
684
685 self.adapter_agent.receive_proxied_message(onu_device.proxy_address,
686 omci_indication.pkt)
687
688 def packet_indication(self, pkt_indication):
689
690 self.log.debug("packet indication",
691 intf_type=pkt_indication.intf_type,
692 intf_id=pkt_indication.intf_id,
693 port_no=pkt_indication.port_no,
694 cookie=pkt_indication.cookie,
695 gemport_id=pkt_indication.gemport_id,
696 flow_id=pkt_indication.flow_id)
697
698 if pkt_indication.intf_type == "pon":
699 if pkt_indication.port_no:
700 logical_port_num = pkt_indication.port_no
701 else: # TODO Remove this else block after openolt device has been fully rolled out with cookie protobuf change
702 try:
703 onu_id_uni_id = self.resource_mgr.get_onu_uni_from_ponport_gemport(pkt_indication.intf_id,
704 pkt_indication.gemport_id)
705 onu_id = int(onu_id_uni_id[0])
706 uni_id = int(onu_id_uni_id[1])
707 self.log.debug("packet indication-kv", onu_id=onu_id, uni_id=uni_id)
708 if onu_id is None:
709 raise Exception("onu-id-none")
710 if uni_id is None:
711 raise Exception("uni-id-none")
712 logical_port_num = self.platform.mk_uni_port_num(pkt_indication.intf_id, onu_id, uni_id)
713 except Exception as e:
714 self.log.error("no-onu-reference-for-gem",
715 gemport_id=pkt_indication.gemport_id, e=e)
716 return
717
718
719 elif pkt_indication.intf_type == "nni":
720 logical_port_num = self.platform.intf_id_to_port_no(
721 pkt_indication.intf_id,
722 Port.ETHERNET_NNI)
723
724 pkt = Ether(pkt_indication.pkt)
725
726 self.log.debug("packet indication",
727 logical_device_id=self.logical_device_id,
728 logical_port_no=logical_port_num)
729
730 self.adapter_agent.send_packet_in(
731 logical_device_id=self.logical_device_id,
732 logical_port_no=logical_port_num,
733 packet=str(pkt))
734
735 def packet_out(self, egress_port, msg):
736 pkt = Ether(msg)
737 self.log.debug('packet out', egress_port=egress_port,
738 device_id=self.device_id,
739 logical_device_id=self.logical_device_id,
740 packet=str(pkt).encode("HEX"))
741
742 # Find port type
743 egress_port_type = self.platform.intf_id_to_port_type_name(egress_port)
744 if egress_port_type == Port.ETHERNET_UNI:
745
746 if pkt.haslayer(Dot1Q):
747 outer_shim = pkt.getlayer(Dot1Q)
748 if isinstance(outer_shim.payload, Dot1Q):
749 # If double tag, remove the outer tag
750 payload = (
751 Ether(src=pkt.src, dst=pkt.dst, type=outer_shim.type) /
752 outer_shim.payload
753 )
754 else:
755 payload = pkt
756 else:
757 payload = pkt
758
759 send_pkt = binascii.unhexlify(str(payload).encode("HEX"))
760
761 self.log.debug(
762 'sending-packet-to-ONU', egress_port=egress_port,
763 intf_id=self.platform.intf_id_from_uni_port_num(egress_port),
764 onu_id=self.platform.onu_id_from_port_num(egress_port),
765 uni_id=self.platform.uni_id_from_port_num(egress_port),
766 port_no=egress_port,
767 packet=str(payload).encode("HEX"))
768
769 onu_pkt = openolt_pb2.OnuPacket(
770 intf_id=self.platform.intf_id_from_uni_port_num(egress_port),
771 onu_id=self.platform.onu_id_from_port_num(egress_port),
772 port_no=egress_port,
773 pkt=send_pkt)
774
775 self.stub.OnuPacketOut(onu_pkt)
776
777 elif egress_port_type == Port.ETHERNET_NNI:
778 self.log.debug('sending-packet-to-uplink', egress_port=egress_port,
779 packet=str(pkt).encode("HEX"))
780
781 send_pkt = binascii.unhexlify(str(pkt).encode("HEX"))
782
783 uplink_pkt = openolt_pb2.UplinkPacket(
784 intf_id=self.platform.intf_id_from_nni_port_num(egress_port),
785 pkt=send_pkt)
786
787 self.stub.UplinkPacketOut(uplink_pkt)
788
789 else:
790 self.log.warn('Packet-out-to-this-interface-type-not-implemented',
791 egress_port=egress_port,
792 port_type=egress_port_type)
793
794 def send_proxied_message(self, proxy_address, msg):
795 onu_device = self.adapter_agent.get_child_device(
796 self.device_id, onu_id=proxy_address.onu_id,
797 parent_port_no=self.platform.intf_id_to_port_no(
798 proxy_address.channel_id, Port.PON_OLT)
799 )
800 if onu_device.connect_status != ConnectStatus.REACHABLE:
801 self.log.debug('ONU is not reachable, cannot send OMCI',
802 serial_number=onu_device.serial_number,
803 intf_id=onu_device.proxy_address.channel_id,
804 onu_id=onu_device.proxy_address.onu_id)
805 return
806 omci = openolt_pb2.OmciMsg(intf_id=proxy_address.channel_id,
807 onu_id=proxy_address.onu_id, pkt=str(msg))
808 self.stub.OmciMsgOut(omci)
809
Matt Jeanneret6e315092019-02-20 10:42:57 -0500810 @inlineCallbacks
William Kurkian6f436d02019-02-06 16:25:01 -0500811 def add_onu_device(self, intf_id, port_no, onu_id, serial_number):
812 self.log.info("Adding ONU", port_no=port_no, onu_id=onu_id,
813 serial_number=serial_number)
814
815 # NOTE - channel_id of onu is set to intf_id
816 proxy_address = Device.ProxyAddress(device_id=self.device_id,
817 channel_id=intf_id, onu_id=onu_id,
818 onu_session_id=onu_id)
819
820 self.log.debug("Adding ONU", proxy_address=proxy_address)
821
822 serial_number_str = self.stringify_serial_number(serial_number)
823
Matt Jeanneret6e315092019-02-20 10:42:57 -0500824 yield self.adapter_agent.child_device_detected(
825 parent_device_id=self.device_id,
826 parent_port_no=port_no,
827 child_device_type='brcm_openomci_onu',
828 channel_id=onu_id,
William Kurkian6f436d02019-02-06 16:25:01 -0500829 )
830
831 def port_name(self, port_no, port_type, intf_id=None, serial_number=None):
832 if port_type is Port.ETHERNET_NNI:
833 return "nni-" + str(port_no)
834 elif port_type is Port.PON_OLT:
835 return "pon" + str(intf_id)
836 elif port_type is Port.ETHERNET_UNI:
837 assert False, 'local UNI management not supported'
838
839 def add_logical_port(self, port_no, intf_id, oper_state):
840 self.log.info('adding-logical-port', port_no=port_no)
841
842 label = self.port_name(port_no, Port.ETHERNET_NNI)
843
844 cap = OFPPF_1GB_FD | OFPPF_FIBER
845 curr_speed = OFPPF_1GB_FD
846 max_speed = OFPPF_1GB_FD
847
848 if oper_state == OperStatus.ACTIVE:
849 of_oper_state = OFPPS_LIVE
850 else:
851 of_oper_state = OFPPS_LINK_DOWN
852
853 ofp = ofp_port(
854 port_no=port_no,
855 hw_addr=mac_str_to_tuple(self._get_mac_form_port_no(port_no)),
856 name=label, config=0, state=of_oper_state, curr=cap,
857 advertised=cap, peer=cap, curr_speed=curr_speed,
858 max_speed=max_speed)
859
860 ofp_stats = ofp_port_stats(port_no=port_no)
861
862 logical_port = LogicalPort(
863 id=label, ofp_port=ofp, device_id=self.device_id,
864 device_port_no=port_no, root_port=True,
865 ofp_port_stats=ofp_stats)
866
867 self.adapter_agent.add_logical_port(self.logical_device_id,
868 logical_port)
869
870 def _get_mac_form_port_no(self, port_no):
871 mac = ''
872 for i in range(4):
873 mac = ':%02x' % ((port_no >> (i * 8)) & 0xff) + mac
874 return '00:00' + mac
875
William Kurkian92bd7122019-02-14 15:26:59 -0500876 @inlineCallbacks
William Kurkian6f436d02019-02-06 16:25:01 -0500877 def add_port(self, intf_id, port_type, oper_status):
878 port_no = self.platform.intf_id_to_port_no(intf_id, port_type)
879
880 label = self.port_name(port_no, port_type, intf_id)
881
882 self.log.debug('adding-port', port_no=port_no, label=label,
883 port_type=port_type)
884
885 port = Port(port_no=port_no, label=label, type=port_type,
886 admin_state=AdminState.ENABLED, oper_status=oper_status)
887
Matt Jeanneret9fd36df2019-02-14 19:14:36 -0500888 yield self.adapter_agent.port_created(self.device_id, port)
889 # self.adapter_agent.add_port(self.device_id, port)
William Kurkian6f436d02019-02-06 16:25:01 -0500890
William Kurkian92bd7122019-02-14 15:26:59 -0500891 returnValue(port_no, label)
William Kurkian6f436d02019-02-06 16:25:01 -0500892
893 def delete_logical_port(self, child_device):
894 logical_ports = self.proxy.get('/logical_devices/{}/ports'.format(
895 self.logical_device_id))
896 for logical_port in logical_ports:
897 if logical_port.device_id == child_device.id:
898 self.log.debug('delete-logical-port',
899 onu_device_id=child_device.id,
900 logical_port=logical_port)
901 self.flow_mgr.clear_flows_and_scheduler_for_logical_port(
902 child_device, logical_port)
903 self.adapter_agent.delete_logical_port(
904 self.logical_device_id, logical_port)
905 return
906
907 def delete_port(self, child_serial_number):
908 ports = self.proxy.get('/devices/{}/ports'.format(
909 self.device_id))
910 for port in ports:
911 if port.label == child_serial_number:
912 self.log.debug('delete-port',
913 onu_serial_number=child_serial_number,
914 port=port)
915 self.adapter_agent.delete_port(self.device_id, port)
916 return
917
918 def update_flow_table(self, flows):
919 self.log.debug('No updates here now, all is done in logical flows '
920 'update')
921
922 def update_logical_flows(self, flows_to_add, flows_to_remove,
923 device_rules_map):
924 if not self.is_state_up():
925 self.log.info('The OLT is not up, we cannot update flows',
926 flows_to_add=[f.id for f in flows_to_add],
927 flows_to_remove=[f.id for f in flows_to_remove])
928 return
929
930 try:
931 self.flow_mgr.update_children_flows(device_rules_map)
932 except Exception as e:
933 self.log.error('Error updating children flows', error=e)
934
935 self.log.debug('logical flows update', flows_to_add=flows_to_add,
936 flows_to_remove=flows_to_remove)
937
938 for flow in flows_to_add:
939
940 try:
941 self.flow_mgr.add_flow(flow)
942 except Exception as e:
943 self.log.error('failed to add flow', flow=flow, e=e)
944
945 for flow in flows_to_remove:
946
947 try:
948 self.flow_mgr.remove_flow(flow)
949 except Exception as e:
950 self.log.error('failed to remove flow', flow=flow, e=e)
951
952 self.flow_mgr.repush_all_different_flows()
953
954 # There has to be a better way to do this
955 def ip_hex(self, ip):
956 octets = ip.split(".")
957 hex_ip = []
958 for octet in octets:
959 octet_hex = hex(int(octet))
960 octet_hex = octet_hex.split('0x')[1]
961 octet_hex = octet_hex.rjust(2, '0')
962 hex_ip.append(octet_hex)
963 return ":".join(hex_ip)
964
965 def stringify_vendor_specific(self, vendor_specific):
966 return ''.join(str(i) for i in [
967 hex(ord(vendor_specific[0]) >> 4 & 0x0f)[2:],
968 hex(ord(vendor_specific[0]) & 0x0f)[2:],
969 hex(ord(vendor_specific[1]) >> 4 & 0x0f)[2:],
970 hex(ord(vendor_specific[1]) & 0x0f)[2:],
971 hex(ord(vendor_specific[2]) >> 4 & 0x0f)[2:],
972 hex(ord(vendor_specific[2]) & 0x0f)[2:],
973 hex(ord(vendor_specific[3]) >> 4 & 0x0f)[2:],
974 hex(ord(vendor_specific[3]) & 0x0f)[2:]])
975
976 def stringify_serial_number(self, serial_number):
977 return ''.join([serial_number.vendor_id,
978 self.stringify_vendor_specific(
979 serial_number.vendor_specific)])
980
981 def destringify_serial_number(self, serial_number_str):
982 serial_number = openolt_pb2.SerialNumber(
983 vendor_id=serial_number_str[:4].encode('utf-8'),
984 vendor_specific=binascii.unhexlify(serial_number_str[4:]))
985 return serial_number
986
987 def disable(self):
988 self.log.debug('sending-deactivate-olt-message',
989 device_id=self.device_id)
990
991 try:
992 # Send grpc call
993 self.stub.DisableOlt(openolt_pb2.Empty())
994 # The resulting indication will bring the OLT down
995 # self.go_state_down()
996 self.log.info('openolt device disabled')
997 except Exception as e:
998 self.log.error('Failure to disable openolt device', error=e)
999
1000 def delete(self):
1001 self.log.info('deleting-olt', device_id=self.device_id,
1002 logical_device_id=self.logical_device_id)
1003
1004 # Clears up the data from the resource manager KV store
1005 # for the device
1006 del self.resource_mgr
1007
1008 try:
1009 # Rebooting to reset the state
1010 self.reboot()
1011 # Removing logical device
1012 ld = self.adapter_agent.get_logical_device(self.logical_device_id)
1013 self.adapter_agent.delete_logical_device(ld)
1014 except Exception as e:
1015 self.log.error('Failure to delete openolt device', error=e)
1016 raise e
1017 else:
1018 self.log.info('successfully-deleted-olt', device_id=self.device_id)
1019
1020 def reenable(self):
1021 self.log.debug('reenabling-olt', device_id=self.device_id)
1022
1023 try:
1024 self.stub.ReenableOlt(openolt_pb2.Empty())
1025
William Kurkian6f436d02019-02-06 16:25:01 -05001026 except Exception as e:
1027 self.log.error('Failure to reenable openolt device', error=e)
1028 else:
1029 self.log.info('openolt device reenabled')
1030
1031 def activate_onu(self, intf_id, onu_id, serial_number,
1032 serial_number_str):
1033 pir = self.bw_mgr.pir(serial_number_str)
1034 self.log.debug("activating-onu", intf_id=intf_id, onu_id=onu_id,
1035 serial_number_str=serial_number_str,
1036 serial_number=serial_number, pir=pir)
1037 onu = openolt_pb2.Onu(intf_id=intf_id, onu_id=onu_id,
1038 serial_number=serial_number, pir=pir)
1039 self.stub.ActivateOnu(onu)
1040 self.log.info('onu-activated', serial_number=serial_number_str)
1041
1042 def delete_child_device(self, child_device):
1043 self.log.debug('sending-deactivate-onu',
1044 olt_device_id=self.device_id,
1045 onu_device=child_device,
1046 onu_serial_number=child_device.serial_number)
1047 try:
1048 self.adapter_agent.delete_child_device(self.device_id,
1049 child_device.id,
1050 child_device)
1051 except Exception as e:
1052 self.log.error('adapter_agent error', error=e)
1053 try:
1054 self.delete_logical_port(child_device)
1055 except Exception as e:
1056 self.log.error('logical_port delete error', error=e)
1057 try:
1058 self.delete_port(child_device.serial_number)
1059 except Exception as e:
1060 self.log.error('port delete error', error=e)
1061 serial_number = self.destringify_serial_number(
1062 child_device.serial_number)
1063 # TODO FIXME - For each uni.
1064 # TODO FIXME - Flows are not deleted
1065 uni_id = 0 # FIXME
1066 self.flow_mgr.delete_tech_profile_instance(
Matt Jeanneret7906d232019-02-14 14:57:38 -05001067 child_device.proxy_address.channel_id,
1068 child_device.proxy_address.onu_id,
1069 uni_id
William Kurkian6f436d02019-02-06 16:25:01 -05001070 )
1071 pon_intf_id_onu_id = (child_device.proxy_address.channel_id,
1072 child_device.proxy_address.onu_id,
1073 uni_id)
1074 # Free any PON resources that were reserved for the ONU
1075 self.resource_mgr.free_pon_resources_for_onu(pon_intf_id_onu_id)
1076
1077 onu = openolt_pb2.Onu(intf_id=child_device.proxy_address.channel_id,
1078 onu_id=child_device.proxy_address.onu_id,
1079 serial_number=serial_number)
1080 self.stub.DeleteOnu(onu)
1081
1082 def reboot(self):
1083 self.log.debug('rebooting openolt device', device_id=self.device_id)
1084 try:
1085 self.stub.Reboot(openolt_pb2.Empty())
1086 except Exception as e:
1087 self.log.error('something went wrong with the reboot', error=e)
1088 else:
1089 self.log.info('device rebooted')
1090
1091 def trigger_statistics_collection(self):
1092 try:
1093 self.stub.CollectStatistics(openolt_pb2.Empty())
1094 except Exception as e:
1095 self.log.error('Error while triggering statistics collection',
1096 error=e)
1097 else:
1098 self.log.info('statistics requested')
1099
1100 def simulate_alarm(self, alarm):
1101 self.alarm_mgr.simulate_alarm(alarm)