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