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