blob: f27c88655dddbb0f8550e65c30ba8b01a4467ec6 [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 Kurkian3a341a22019-02-13 18:23:44 -050024from twisted.internet.defer import inlineCallbacks
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
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
William Kurkian3a341a22019-02-13 18:23:44 -0500162 """
William Kurkian6f436d02019-02-06 16:25:01 -0500163 # 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,
William Kurkian3a341a22019-02-13 18:23:44 -0500181
182 nni_port = Port(
183 port_no=info.nni_port,
184 label='NNI facing Ethernet port',
185 type=Port.ETHERNET_NNI,
186 oper_status=OperStatus.ACTIVE
187 )
188 self.nni_port = nni_port
189 yield self.core_proxy.port_created(device.id, nni_port)
190 yield self.core_proxy.port_created(device.id, Port(
191 port_no=1,
192 label='PON port',
193 type=Port.PON_OLT,
194 oper_status=OperStatus.ACTIVE
195 )) dpid=dpid)
196 """
William Kurkian6f436d02019-02-06 16:25:01 -0500197 self.logical_device_id = ld_init.id
198
199 device = self.adapter_agent.get_device(self.device_id)
200 device.serial_number = serial_number
William Kurkianfefd4642019-02-07 15:30:03 -0500201 self.adapter_agent.device_update(device)
William Kurkian6f436d02019-02-06 16:25:01 -0500202
203 self.dpid = dpid
204 self.serial_number = serial_number
205
206 self.log.info('created-openolt-logical-device', logical_device_id=ld_init.id)
207
208 def stringToMacAddr(self, uri):
209 regex = re.compile('[^a-zA-Z]')
210 uri = regex.sub('', uri)
211
212 l = len(uri)
213 if l > 6:
214 uri = uri[0:6]
215 else:
216 uri = uri + uri[0:6 - l]
217
218 print uri
219
220 return ":".join([hex(ord(x))[-2:] for x in uri])
221
222 def do_state_init(self, event):
223 # Initialize gRPC
William Kurkianfefd4642019-02-07 15:30:03 -0500224 print ("Host And Port", self.host_and_port)
William Kurkian6f436d02019-02-06 16:25:01 -0500225 self.channel = grpc.insecure_channel(self.host_and_port)
226 self.channel_ready_future = grpc.channel_ready_future(self.channel)
227
228 self.log.info('openolt-device-created', device_id=self.device_id)
229
230 def post_init(self, event):
231 self.log.debug('post_init')
232
233 # We have reached init state, starting the indications thread
234
235 # Catch RuntimeError exception
236 try:
237 # Start indications thread
238 self.indications_thread_handle = threading.Thread(
239 target=self.indications_thread)
240 # Old getter/setter API for daemon; use it directly as a
241 # property instead. The Jinkins error will happon on the reason of
242 # Exception in thread Thread-1 (most likely raised # during
243 # interpreter shutdown)
William Kurkianfefd4642019-02-07 15:30:03 -0500244 self.log.debug('starting indications thread')
William Kurkian6f436d02019-02-06 16:25:01 -0500245 self.indications_thread_handle.setDaemon(True)
246 self.indications_thread_handle.start()
247 except Exception as e:
248 self.log.exception('post_init failed', e=e)
249
250 def do_state_connected(self, event):
251 self.log.debug("do_state_connected")
252
253 device = self.adapter_agent.get_device(self.device_id)
254
255 self.stub = openolt_pb2_grpc.OpenoltStub(self.channel)
256
William Kurkianfefd4642019-02-07 15:30:03 -0500257 delay = 1
258 while True:
259 try:
260 device_info = self.stub.GetDeviceInfo(openolt_pb2.Empty())
261 break
262 except Exception as e:
263 reraise = True
264 if delay > 120:
265 self.log.error("gRPC failure too many times")
266 else:
267 self.log.warn("gRPC failure, retry in %ds: %s"
268 % (delay, repr(e)))
269 time.sleep(delay)
270 delay += delay
271 reraise = False
272
273 if reraise:
274 raise
275
William Kurkian6f436d02019-02-06 16:25:01 -0500276 self.log.info('Device connected', device_info=device_info)
277
William Kurkian3a341a22019-02-13 18:23:44 -0500278 #self.create_logical_device(device_info)
279 self.logical_device_id = 0
William Kurkian6f436d02019-02-06 16:25:01 -0500280 device.serial_number = self.serial_number
William Kurkianfefd4642019-02-07 15:30:03 -0500281
William Kurkian6f436d02019-02-06 16:25:01 -0500282 self.resource_mgr = self.resource_mgr_class(self.device_id,
283 self.host_and_port,
284 self.extra_args,
285 device_info)
286 self.platform = self.platform_class(self.log, self.resource_mgr)
287 self.flow_mgr = self.flow_mgr_class(self.adapter_agent, self.log,
288 self.stub, self.device_id,
289 self.logical_device_id,
290 self.platform, self.resource_mgr)
291
292 self.alarm_mgr = self.alarm_mgr_class(self.log, self.adapter_agent,
293 self.device_id,
294 self.logical_device_id,
295 self.platform)
William Kurkianfefd4642019-02-07 15:30:03 -0500296 self.stats_mgr = self.stats_mgr_class(self, self.log, self.platform)
William Kurkian3a341a22019-02-13 18:23:44 -0500297 self.bw_mgr = self.bw_mgr_class(self.log, self.adapter_agent)
William Kurkianfefd4642019-02-07 15:30:03 -0500298
William Kurkian6f436d02019-02-06 16:25:01 -0500299 device.vendor = device_info.vendor
300 device.model = device_info.model
301 device.hardware_version = device_info.hardware_version
302 device.firmware_version = device_info.firmware_version
303
304 # TODO: check for uptime and reboot if too long (VOL-1192)
305
306 device.connect_status = ConnectStatus.REACHABLE
William Kurkianfefd4642019-02-07 15:30:03 -0500307 self.adapter_agent.device_update(device)
William Kurkian3a341a22019-02-13 18:23:44 -0500308
309 @inlineCallbacks
William Kurkian6f436d02019-02-06 16:25:01 -0500310 def do_state_up(self, event):
311 self.log.debug("do_state_up")
312
William Kurkian3a341a22019-02-13 18:23:44 -0500313 device = yield self.adapter_agent.get_device(self.device_id)
314 self.log.debug("do_state_up set device active", device=device)
William Kurkian6f436d02019-02-06 16:25:01 -0500315 # Update phys OF device
William Kurkian3a341a22019-02-13 18:23:44 -0500316 #device.parent_id = self.logical_device_id
William Kurkian6f436d02019-02-06 16:25:01 -0500317 device.oper_status = OperStatus.ACTIVE
William Kurkian3a341a22019-02-13 18:23:44 -0500318 self.log.debug("Updating to Active", device=device)
William Kurkianfefd4642019-02-07 15:30:03 -0500319 self.adapter_agent.device_update(device)
William Kurkian6f436d02019-02-06 16:25:01 -0500320
321 def do_state_down(self, event):
322 self.log.debug("do_state_down")
323 oper_state = OperStatus.UNKNOWN
324 connect_state = ConnectStatus.UNREACHABLE
325
326 # Propagating to the children
327
328 # Children ports
329 child_devices = self.adapter_agent.get_child_devices(self.device_id)
330 for onu_device in child_devices:
331 onu_adapter_agent = \
332 registry('adapter_loader').get_agent(onu_device.adapter)
333 onu_adapter_agent.update_interface(onu_device,
334 {'oper_state': 'down'})
335 self.onu_ports_down(onu_device, oper_state)
336
337 # Children devices
338 self.adapter_agent.update_child_devices_state(
339 self.device_id, oper_status=oper_state,
340 connect_status=connect_state)
341 # Device Ports
342 device_ports = self.adapter_agent.get_ports(self.device_id,
343 Port.ETHERNET_NNI)
344 logical_ports_ids = [port.label for port in device_ports]
345 device_ports += self.adapter_agent.get_ports(self.device_id,
346 Port.PON_OLT)
347
348 for port in device_ports:
349 port.oper_status = oper_state
350 self.adapter_agent.add_port(self.device_id, port)
351
352 # Device logical port
353 for logical_port_id in logical_ports_ids:
354 logical_port = self.adapter_agent.get_logical_port(
355 self.logical_device_id, logical_port_id)
356 logical_port.ofp_port.state = OFPPS_LINK_DOWN
357 self.adapter_agent.update_logical_port(self.logical_device_id,
358 logical_port)
359
360 # Device
361 device = self.adapter_agent.get_device(self.device_id)
362 device.oper_status = oper_state
363 device.connect_status = connect_state
364
William Kurkianfefd4642019-02-07 15:30:03 -0500365 reactor.callLater(2, self.adapter_agent.device_update, device)
William Kurkian6f436d02019-02-06 16:25:01 -0500366
367 # def post_up(self, event):
368 # self.log.debug('post-up')
369 # self.flow_mgr.reseed_flows()
370
371 def post_down(self, event):
372 self.log.debug('post_down')
373 self.flow_mgr.reset_flows()
374
375 def indications_thread(self):
376 self.log.debug('starting-indications-thread')
377 self.log.debug('connecting to olt', device_id=self.device_id)
378 self.channel_ready_future.result() # blocking call
379 self.log.info('connected to olt', device_id=self.device_id)
380 self.go_state_connected()
381
382 self.indications = self.stub.EnableIndication(openolt_pb2.Empty())
383
384 while True:
385 try:
386 # get the next indication from olt
387 ind = next(self.indications)
388 except Exception as e:
389 self.log.warn('gRPC connection lost', error=e)
390 reactor.callFromThread(self.go_state_down)
391 reactor.callFromThread(self.go_state_init)
392 break
393 else:
394 self.log.debug("rx indication", indication=ind)
395
396 # indication handlers run in the main event loop
397 if ind.HasField('olt_ind'):
398 reactor.callFromThread(self.olt_indication, ind.olt_ind)
399 elif ind.HasField('intf_ind'):
400 reactor.callFromThread(self.intf_indication, ind.intf_ind)
401 elif ind.HasField('intf_oper_ind'):
402 reactor.callFromThread(self.intf_oper_indication,
403 ind.intf_oper_ind)
404 elif ind.HasField('onu_disc_ind'):
405 reactor.callFromThread(self.onu_discovery_indication,
406 ind.onu_disc_ind)
407 elif ind.HasField('onu_ind'):
408 reactor.callFromThread(self.onu_indication, ind.onu_ind)
409 elif ind.HasField('omci_ind'):
410 reactor.callFromThread(self.omci_indication, ind.omci_ind)
411 elif ind.HasField('pkt_ind'):
412 reactor.callFromThread(self.packet_indication, ind.pkt_ind)
413 elif ind.HasField('port_stats'):
414 reactor.callFromThread(
415 self.stats_mgr.port_statistics_indication,
416 ind.port_stats)
417 elif ind.HasField('flow_stats'):
418 reactor.callFromThread(
419 self.stats_mgr.flow_statistics_indication,
420 ind.flow_stats)
421 elif ind.HasField('alarm_ind'):
422 reactor.callFromThread(self.alarm_mgr.process_alarms,
423 ind.alarm_ind)
424 else:
425 self.log.warn('unknown indication type')
426
427 def olt_indication(self, olt_indication):
428 if olt_indication.oper_state == "up":
429 self.go_state_up()
430 elif olt_indication.oper_state == "down":
431 self.go_state_down()
432
433 def intf_indication(self, intf_indication):
434 self.log.debug("intf indication", intf_id=intf_indication.intf_id,
435 oper_state=intf_indication.oper_state)
436
437 if intf_indication.oper_state == "up":
438 oper_status = OperStatus.ACTIVE
439 else:
440 oper_status = OperStatus.DISCOVERED
441
442 # add_port update the port if it exists
443 self.add_port(intf_indication.intf_id, Port.PON_OLT, oper_status)
444
445 def intf_oper_indication(self, intf_oper_indication):
446 self.log.debug("Received interface oper state change indication",
447 intf_id=intf_oper_indication.intf_id,
448 type=intf_oper_indication.type,
449 oper_state=intf_oper_indication.oper_state)
450
451 if intf_oper_indication.oper_state == "up":
452 oper_state = OperStatus.ACTIVE
453 else:
454 oper_state = OperStatus.DISCOVERED
455
456 if intf_oper_indication.type == "nni":
457
458 # add_(logical_)port update the port if it exists
459 port_no, label = self.add_port(intf_oper_indication.intf_id,
460 Port.ETHERNET_NNI, oper_state)
461 self.log.debug("int_oper_indication", port_no=port_no, label=label)
462 self.add_logical_port(port_no, intf_oper_indication.intf_id,
463 oper_state)
464
465 elif intf_oper_indication.type == "pon":
466 # FIXME - handle PON oper state change
467 pass
468
469 def onu_discovery_indication(self, onu_disc_indication):
470 intf_id = onu_disc_indication.intf_id
471 serial_number = onu_disc_indication.serial_number
472
473 serial_number_str = self.stringify_serial_number(serial_number)
474
475 self.log.debug("onu discovery indication", intf_id=intf_id,
476 serial_number=serial_number_str)
477
478 # Post ONU Discover alarm 20180809_0805
479 try:
480 OnuDiscoveryAlarm(self.alarm_mgr.alarms, pon_id=intf_id,
481 serial_number=serial_number_str).raise_alarm()
482 except Exception as disc_alarm_error:
483 self.log.exception("onu-discovery-alarm-error",
484 errmsg=disc_alarm_error.message)
485 # continue for now.
486
487 onu_device = self.adapter_agent.get_child_device(
488 self.device_id,
489 serial_number=serial_number_str)
490
491 if onu_device is None:
492 try:
493 onu_id = self.resource_mgr.get_onu_id(intf_id)
494 if onu_id is None:
495 raise Exception("onu-id-unavailable")
496
497 self.add_onu_device(
498 intf_id,
499 self.platform.intf_id_to_port_no(intf_id, Port.PON_OLT),
500 onu_id, serial_number)
501 self.activate_onu(intf_id, onu_id, serial_number,
502 serial_number_str)
503 except Exception as e:
504 self.log.exception('onu-activation-failed', e=e)
505
506 else:
507 if onu_device.connect_status != ConnectStatus.REACHABLE:
508 onu_device.connect_status = ConnectStatus.REACHABLE
William Kurkianfefd4642019-02-07 15:30:03 -0500509 self.adapter_agent.device_update(onu_device)
William Kurkian6f436d02019-02-06 16:25:01 -0500510
511 onu_id = onu_device.proxy_address.onu_id
512 if onu_device.oper_status == OperStatus.DISCOVERED \
513 or onu_device.oper_status == OperStatus.ACTIVATING:
514 self.log.debug("ignore onu discovery indication, \
515 the onu has been discovered and should be \
516 activating shorlty", intf_id=intf_id,
517 onu_id=onu_id, state=onu_device.oper_status)
518 elif onu_device.oper_status == OperStatus.ACTIVE:
519 self.log.warn("onu discovery indication whereas onu is \
520 supposed to be active",
521 intf_id=intf_id, onu_id=onu_id,
522 state=onu_device.oper_status)
523 elif onu_device.oper_status == OperStatus.UNKNOWN:
524 self.log.info("onu in unknown state, recovering from olt \
525 reboot probably, activate onu", intf_id=intf_id,
526 onu_id=onu_id, serial_number=serial_number_str)
527
528 onu_device.oper_status = OperStatus.DISCOVERED
William Kurkianfefd4642019-02-07 15:30:03 -0500529 self.adapter_agent.device_update(onu_device)
William Kurkian6f436d02019-02-06 16:25:01 -0500530 try:
531 self.activate_onu(intf_id, onu_id, serial_number,
532 serial_number_str)
533 except Exception as e:
534 self.log.error('onu-activation-error',
535 serial_number=serial_number_str, error=e)
536 else:
537 self.log.warn('unexpected state', onu_id=onu_id,
538 onu_device_oper_state=onu_device.oper_status)
539
540 def onu_indication(self, onu_indication):
541 self.log.debug("onu indication", intf_id=onu_indication.intf_id,
542 onu_id=onu_indication.onu_id,
543 serial_number=onu_indication.serial_number,
544 oper_state=onu_indication.oper_state,
545 admin_state=onu_indication.admin_state)
546 try:
547 serial_number_str = self.stringify_serial_number(
548 onu_indication.serial_number)
549 except Exception as e:
550 serial_number_str = None
551
552 if serial_number_str is not None:
553 onu_device = self.adapter_agent.get_child_device(
554 self.device_id,
555 serial_number=serial_number_str)
556 else:
557 onu_device = self.adapter_agent.get_child_device(
558 self.device_id,
559 parent_port_no=self.platform.intf_id_to_port_no(
560 onu_indication.intf_id, Port.PON_OLT),
561 onu_id=onu_indication.onu_id)
562
563 if onu_device is None:
564 self.log.error('onu not found', intf_id=onu_indication.intf_id,
565 onu_id=onu_indication.onu_id)
566 return
567
568 if self.platform.intf_id_from_pon_port_no(onu_device.parent_port_no) \
569 != onu_indication.intf_id:
570 self.log.warn('ONU-is-on-a-different-intf-id-now',
571 previous_intf_id=self.platform.intf_id_from_pon_port_no(
572 onu_device.parent_port_no),
573 current_intf_id=onu_indication.intf_id)
574 # FIXME - handle intf_id mismatch (ONU move?)
575
576 if onu_device.proxy_address.onu_id != onu_indication.onu_id:
577 # FIXME - handle onu id mismatch
578 self.log.warn('ONU-id-mismatch, can happen if both voltha and '
579 'the olt rebooted',
580 expected_onu_id=onu_device.proxy_address.onu_id,
581 received_onu_id=onu_indication.onu_id)
582
583 # Admin state
584 if onu_indication.admin_state == 'down':
585 if onu_indication.oper_state != 'down':
586 self.log.error('ONU-admin-state-down-and-oper-status-not-down',
587 oper_state=onu_indication.oper_state)
588 # Forcing the oper state change code to execute
589 onu_indication.oper_state = 'down'
590
591 # Port and logical port update is taken care of by oper state block
592
593 elif onu_indication.admin_state == 'up':
594 pass
595
596 else:
597 self.log.warn('Invalid-or-not-implemented-admin-state',
598 received_admin_state=onu_indication.admin_state)
599
600 self.log.debug('admin-state-dealt-with')
601
602 onu_adapter_agent = \
603 registry('adapter_loader').get_agent(onu_device.adapter)
604 if onu_adapter_agent is None:
605 self.log.error('onu_adapter_agent-could-not-be-retrieved',
606 onu_device=onu_device)
607 return
608
609 # Operating state
610 if onu_indication.oper_state == 'down':
611
612 if onu_device.connect_status != ConnectStatus.UNREACHABLE:
613 onu_device.connect_status = ConnectStatus.UNREACHABLE
William Kurkianfefd4642019-02-07 15:30:03 -0500614 self.adapter_agent.device_update(onu_device)
William Kurkian6f436d02019-02-06 16:25:01 -0500615
616 # Move to discovered state
617 self.log.debug('onu-oper-state-is-down')
618
619 if onu_device.oper_status != OperStatus.DISCOVERED:
620 onu_device.oper_status = OperStatus.DISCOVERED
William Kurkianfefd4642019-02-07 15:30:03 -0500621 self.adapter_agent.device_update(onu_device)
William Kurkian6f436d02019-02-06 16:25:01 -0500622 # Set port oper state to Discovered
623 self.onu_ports_down(onu_device, OperStatus.DISCOVERED)
624
625 onu_adapter_agent.update_interface(onu_device,
626 {'oper_state': 'down'})
627
628 elif onu_indication.oper_state == 'up':
629
630 if onu_device.connect_status != ConnectStatus.REACHABLE:
631 onu_device.connect_status = ConnectStatus.REACHABLE
William Kurkianfefd4642019-02-07 15:30:03 -0500632 self.adapter_agent.device_update(onu_device)
William Kurkian6f436d02019-02-06 16:25:01 -0500633
634 if onu_device.oper_status != OperStatus.DISCOVERED:
635 self.log.debug("ignore onu indication",
636 intf_id=onu_indication.intf_id,
637 onu_id=onu_indication.onu_id,
638 state=onu_device.oper_status,
639 msg_oper_state=onu_indication.oper_state)
640 return
641
642 # Device was in Discovered state, setting it to active
643
644 # Prepare onu configuration
645
646 onu_adapter_agent.create_interface(onu_device, onu_indication)
647
648 else:
649 self.log.warn('Not-implemented-or-invalid-value-of-oper-state',
650 oper_state=onu_indication.oper_state)
651
652 def onu_ports_down(self, onu_device, oper_state):
653 # Set port oper state to Discovered
654 # add port will update port if it exists
655 # self.adapter_agent.add_port(
656 # self.device_id,
657 # Port(
658 # port_no=uni_no,
659 # label=uni_name,
660 # type=Port.ETHERNET_UNI,
661 # admin_state=onu_device.admin_state,
662 # oper_status=oper_state))
663 # TODO this should be downning ports in onu adatper
664
665 # Disable logical port
666 onu_ports = self.proxy.get('devices/{}/ports'.format(onu_device.id))
667 for onu_port in onu_ports:
668 self.log.debug('onu-ports-down', onu_port=onu_port)
669 onu_port_id = onu_port.label
670 try:
671 onu_logical_port = self.adapter_agent.get_logical_port(
672 logical_device_id=self.logical_device_id, port_id=onu_port_id)
673 onu_logical_port.ofp_port.state = OFPPS_LINK_DOWN
674 self.adapter_agent.update_logical_port(
675 logical_device_id=self.logical_device_id,
676 port=onu_logical_port)
677 self.log.debug('cascading-oper-state-to-port-and-logical-port')
678 except KeyError as e:
679 self.log.error('matching-onu-port-label-invalid',
680 onu_id=onu_device.id, olt_id=self.device_id,
681 onu_ports=onu_ports, onu_port_id=onu_port_id,
682 error=e)
683
684 def omci_indication(self, omci_indication):
685
686 self.log.debug("omci indication", intf_id=omci_indication.intf_id,
687 onu_id=omci_indication.onu_id)
688
689 onu_device = self.adapter_agent.get_child_device(
690 self.device_id, onu_id=omci_indication.onu_id,
691 parent_port_no=self.platform.intf_id_to_port_no(
692 omci_indication.intf_id, Port.PON_OLT), )
693
694 self.adapter_agent.receive_proxied_message(onu_device.proxy_address,
695 omci_indication.pkt)
696
697 def packet_indication(self, pkt_indication):
698
699 self.log.debug("packet indication",
700 intf_type=pkt_indication.intf_type,
701 intf_id=pkt_indication.intf_id,
702 port_no=pkt_indication.port_no,
703 cookie=pkt_indication.cookie,
704 gemport_id=pkt_indication.gemport_id,
705 flow_id=pkt_indication.flow_id)
706
707 if pkt_indication.intf_type == "pon":
708 if pkt_indication.port_no:
709 logical_port_num = pkt_indication.port_no
710 else: # TODO Remove this else block after openolt device has been fully rolled out with cookie protobuf change
711 try:
712 onu_id_uni_id = self.resource_mgr.get_onu_uni_from_ponport_gemport(pkt_indication.intf_id,
713 pkt_indication.gemport_id)
714 onu_id = int(onu_id_uni_id[0])
715 uni_id = int(onu_id_uni_id[1])
716 self.log.debug("packet indication-kv", onu_id=onu_id, uni_id=uni_id)
717 if onu_id is None:
718 raise Exception("onu-id-none")
719 if uni_id is None:
720 raise Exception("uni-id-none")
721 logical_port_num = self.platform.mk_uni_port_num(pkt_indication.intf_id, onu_id, uni_id)
722 except Exception as e:
723 self.log.error("no-onu-reference-for-gem",
724 gemport_id=pkt_indication.gemport_id, e=e)
725 return
726
727
728 elif pkt_indication.intf_type == "nni":
729 logical_port_num = self.platform.intf_id_to_port_no(
730 pkt_indication.intf_id,
731 Port.ETHERNET_NNI)
732
733 pkt = Ether(pkt_indication.pkt)
734
735 self.log.debug("packet indication",
736 logical_device_id=self.logical_device_id,
737 logical_port_no=logical_port_num)
738
739 self.adapter_agent.send_packet_in(
740 logical_device_id=self.logical_device_id,
741 logical_port_no=logical_port_num,
742 packet=str(pkt))
743
744 def packet_out(self, egress_port, msg):
745 pkt = Ether(msg)
746 self.log.debug('packet out', egress_port=egress_port,
747 device_id=self.device_id,
748 logical_device_id=self.logical_device_id,
749 packet=str(pkt).encode("HEX"))
750
751 # Find port type
752 egress_port_type = self.platform.intf_id_to_port_type_name(egress_port)
753 if egress_port_type == Port.ETHERNET_UNI:
754
755 if pkt.haslayer(Dot1Q):
756 outer_shim = pkt.getlayer(Dot1Q)
757 if isinstance(outer_shim.payload, Dot1Q):
758 # If double tag, remove the outer tag
759 payload = (
760 Ether(src=pkt.src, dst=pkt.dst, type=outer_shim.type) /
761 outer_shim.payload
762 )
763 else:
764 payload = pkt
765 else:
766 payload = pkt
767
768 send_pkt = binascii.unhexlify(str(payload).encode("HEX"))
769
770 self.log.debug(
771 'sending-packet-to-ONU', egress_port=egress_port,
772 intf_id=self.platform.intf_id_from_uni_port_num(egress_port),
773 onu_id=self.platform.onu_id_from_port_num(egress_port),
774 uni_id=self.platform.uni_id_from_port_num(egress_port),
775 port_no=egress_port,
776 packet=str(payload).encode("HEX"))
777
778 onu_pkt = openolt_pb2.OnuPacket(
779 intf_id=self.platform.intf_id_from_uni_port_num(egress_port),
780 onu_id=self.platform.onu_id_from_port_num(egress_port),
781 port_no=egress_port,
782 pkt=send_pkt)
783
784 self.stub.OnuPacketOut(onu_pkt)
785
786 elif egress_port_type == Port.ETHERNET_NNI:
787 self.log.debug('sending-packet-to-uplink', egress_port=egress_port,
788 packet=str(pkt).encode("HEX"))
789
790 send_pkt = binascii.unhexlify(str(pkt).encode("HEX"))
791
792 uplink_pkt = openolt_pb2.UplinkPacket(
793 intf_id=self.platform.intf_id_from_nni_port_num(egress_port),
794 pkt=send_pkt)
795
796 self.stub.UplinkPacketOut(uplink_pkt)
797
798 else:
799 self.log.warn('Packet-out-to-this-interface-type-not-implemented',
800 egress_port=egress_port,
801 port_type=egress_port_type)
802
803 def send_proxied_message(self, proxy_address, msg):
804 onu_device = self.adapter_agent.get_child_device(
805 self.device_id, onu_id=proxy_address.onu_id,
806 parent_port_no=self.platform.intf_id_to_port_no(
807 proxy_address.channel_id, Port.PON_OLT)
808 )
809 if onu_device.connect_status != ConnectStatus.REACHABLE:
810 self.log.debug('ONU is not reachable, cannot send OMCI',
811 serial_number=onu_device.serial_number,
812 intf_id=onu_device.proxy_address.channel_id,
813 onu_id=onu_device.proxy_address.onu_id)
814 return
815 omci = openolt_pb2.OmciMsg(intf_id=proxy_address.channel_id,
816 onu_id=proxy_address.onu_id, pkt=str(msg))
817 self.stub.OmciMsgOut(omci)
818
819 def add_onu_device(self, intf_id, port_no, onu_id, serial_number):
820 self.log.info("Adding ONU", port_no=port_no, onu_id=onu_id,
821 serial_number=serial_number)
822
823 # NOTE - channel_id of onu is set to intf_id
824 proxy_address = Device.ProxyAddress(device_id=self.device_id,
825 channel_id=intf_id, onu_id=onu_id,
826 onu_session_id=onu_id)
827
828 self.log.debug("Adding ONU", proxy_address=proxy_address)
829
830 serial_number_str = self.stringify_serial_number(serial_number)
831
832 self.adapter_agent.add_onu_device(
833 parent_device_id=self.device_id, parent_port_no=port_no,
834 vendor_id=serial_number.vendor_id, proxy_address=proxy_address,
835 root=True, serial_number=serial_number_str,
836 admin_state=AdminState.ENABLED#, **{'vlan':4091} # magic still maps to brcm_openomci_onu.pon_port.BRDCM_DEFAULT_VLAN
837 )
838
839 def port_name(self, port_no, port_type, intf_id=None, serial_number=None):
840 if port_type is Port.ETHERNET_NNI:
841 return "nni-" + str(port_no)
842 elif port_type is Port.PON_OLT:
843 return "pon" + str(intf_id)
844 elif port_type is Port.ETHERNET_UNI:
845 assert False, 'local UNI management not supported'
846
847 def add_logical_port(self, port_no, intf_id, oper_state):
848 self.log.info('adding-logical-port', port_no=port_no)
849
850 label = self.port_name(port_no, Port.ETHERNET_NNI)
851
852 cap = OFPPF_1GB_FD | OFPPF_FIBER
853 curr_speed = OFPPF_1GB_FD
854 max_speed = OFPPF_1GB_FD
855
856 if oper_state == OperStatus.ACTIVE:
857 of_oper_state = OFPPS_LIVE
858 else:
859 of_oper_state = OFPPS_LINK_DOWN
860
861 ofp = ofp_port(
862 port_no=port_no,
863 hw_addr=mac_str_to_tuple(self._get_mac_form_port_no(port_no)),
864 name=label, config=0, state=of_oper_state, curr=cap,
865 advertised=cap, peer=cap, curr_speed=curr_speed,
866 max_speed=max_speed)
867
868 ofp_stats = ofp_port_stats(port_no=port_no)
869
870 logical_port = LogicalPort(
871 id=label, ofp_port=ofp, device_id=self.device_id,
872 device_port_no=port_no, root_port=True,
873 ofp_port_stats=ofp_stats)
874
875 self.adapter_agent.add_logical_port(self.logical_device_id,
876 logical_port)
877
878 def _get_mac_form_port_no(self, port_no):
879 mac = ''
880 for i in range(4):
881 mac = ':%02x' % ((port_no >> (i * 8)) & 0xff) + mac
882 return '00:00' + mac
883
884 def add_port(self, intf_id, port_type, oper_status):
885 port_no = self.platform.intf_id_to_port_no(intf_id, port_type)
886
887 label = self.port_name(port_no, port_type, intf_id)
888
889 self.log.debug('adding-port', port_no=port_no, label=label,
890 port_type=port_type)
891
892 port = Port(port_no=port_no, label=label, type=port_type,
893 admin_state=AdminState.ENABLED, oper_status=oper_status)
894
895 self.adapter_agent.add_port(self.device_id, port)
896
897 return port_no, label
898
899 def delete_logical_port(self, child_device):
900 logical_ports = self.proxy.get('/logical_devices/{}/ports'.format(
901 self.logical_device_id))
902 for logical_port in logical_ports:
903 if logical_port.device_id == child_device.id:
904 self.log.debug('delete-logical-port',
905 onu_device_id=child_device.id,
906 logical_port=logical_port)
907 self.flow_mgr.clear_flows_and_scheduler_for_logical_port(
908 child_device, logical_port)
909 self.adapter_agent.delete_logical_port(
910 self.logical_device_id, logical_port)
911 return
912
913 def delete_port(self, child_serial_number):
914 ports = self.proxy.get('/devices/{}/ports'.format(
915 self.device_id))
916 for port in ports:
917 if port.label == child_serial_number:
918 self.log.debug('delete-port',
919 onu_serial_number=child_serial_number,
920 port=port)
921 self.adapter_agent.delete_port(self.device_id, port)
922 return
923
924 def update_flow_table(self, flows):
925 self.log.debug('No updates here now, all is done in logical flows '
926 'update')
927
928 def update_logical_flows(self, flows_to_add, flows_to_remove,
929 device_rules_map):
930 if not self.is_state_up():
931 self.log.info('The OLT is not up, we cannot update flows',
932 flows_to_add=[f.id for f in flows_to_add],
933 flows_to_remove=[f.id for f in flows_to_remove])
934 return
935
936 try:
937 self.flow_mgr.update_children_flows(device_rules_map)
938 except Exception as e:
939 self.log.error('Error updating children flows', error=e)
940
941 self.log.debug('logical flows update', flows_to_add=flows_to_add,
942 flows_to_remove=flows_to_remove)
943
944 for flow in flows_to_add:
945
946 try:
947 self.flow_mgr.add_flow(flow)
948 except Exception as e:
949 self.log.error('failed to add flow', flow=flow, e=e)
950
951 for flow in flows_to_remove:
952
953 try:
954 self.flow_mgr.remove_flow(flow)
955 except Exception as e:
956 self.log.error('failed to remove flow', flow=flow, e=e)
957
958 self.flow_mgr.repush_all_different_flows()
959
960 # There has to be a better way to do this
961 def ip_hex(self, ip):
962 octets = ip.split(".")
963 hex_ip = []
964 for octet in octets:
965 octet_hex = hex(int(octet))
966 octet_hex = octet_hex.split('0x')[1]
967 octet_hex = octet_hex.rjust(2, '0')
968 hex_ip.append(octet_hex)
969 return ":".join(hex_ip)
970
971 def stringify_vendor_specific(self, vendor_specific):
972 return ''.join(str(i) for i in [
973 hex(ord(vendor_specific[0]) >> 4 & 0x0f)[2:],
974 hex(ord(vendor_specific[0]) & 0x0f)[2:],
975 hex(ord(vendor_specific[1]) >> 4 & 0x0f)[2:],
976 hex(ord(vendor_specific[1]) & 0x0f)[2:],
977 hex(ord(vendor_specific[2]) >> 4 & 0x0f)[2:],
978 hex(ord(vendor_specific[2]) & 0x0f)[2:],
979 hex(ord(vendor_specific[3]) >> 4 & 0x0f)[2:],
980 hex(ord(vendor_specific[3]) & 0x0f)[2:]])
981
982 def stringify_serial_number(self, serial_number):
983 return ''.join([serial_number.vendor_id,
984 self.stringify_vendor_specific(
985 serial_number.vendor_specific)])
986
987 def destringify_serial_number(self, serial_number_str):
988 serial_number = openolt_pb2.SerialNumber(
989 vendor_id=serial_number_str[:4].encode('utf-8'),
990 vendor_specific=binascii.unhexlify(serial_number_str[4:]))
991 return serial_number
992
993 def disable(self):
994 self.log.debug('sending-deactivate-olt-message',
995 device_id=self.device_id)
996
997 try:
998 # Send grpc call
999 self.stub.DisableOlt(openolt_pb2.Empty())
1000 # The resulting indication will bring the OLT down
1001 # self.go_state_down()
1002 self.log.info('openolt device disabled')
1003 except Exception as e:
1004 self.log.error('Failure to disable openolt device', error=e)
1005
1006 def delete(self):
1007 self.log.info('deleting-olt', device_id=self.device_id,
1008 logical_device_id=self.logical_device_id)
1009
1010 # Clears up the data from the resource manager KV store
1011 # for the device
1012 del self.resource_mgr
1013
1014 try:
1015 # Rebooting to reset the state
1016 self.reboot()
1017 # Removing logical device
1018 ld = self.adapter_agent.get_logical_device(self.logical_device_id)
1019 self.adapter_agent.delete_logical_device(ld)
1020 except Exception as e:
1021 self.log.error('Failure to delete openolt device', error=e)
1022 raise e
1023 else:
1024 self.log.info('successfully-deleted-olt', device_id=self.device_id)
1025
1026 def reenable(self):
1027 self.log.debug('reenabling-olt', device_id=self.device_id)
1028
1029 try:
1030 self.stub.ReenableOlt(openolt_pb2.Empty())
1031
William Kurkian6f436d02019-02-06 16:25:01 -05001032 except Exception as e:
1033 self.log.error('Failure to reenable openolt device', error=e)
1034 else:
1035 self.log.info('openolt device reenabled')
1036
1037 def activate_onu(self, intf_id, onu_id, serial_number,
1038 serial_number_str):
1039 pir = self.bw_mgr.pir(serial_number_str)
1040 self.log.debug("activating-onu", intf_id=intf_id, onu_id=onu_id,
1041 serial_number_str=serial_number_str,
1042 serial_number=serial_number, pir=pir)
1043 onu = openolt_pb2.Onu(intf_id=intf_id, onu_id=onu_id,
1044 serial_number=serial_number, pir=pir)
1045 self.stub.ActivateOnu(onu)
1046 self.log.info('onu-activated', serial_number=serial_number_str)
1047
1048 def delete_child_device(self, child_device):
1049 self.log.debug('sending-deactivate-onu',
1050 olt_device_id=self.device_id,
1051 onu_device=child_device,
1052 onu_serial_number=child_device.serial_number)
1053 try:
1054 self.adapter_agent.delete_child_device(self.device_id,
1055 child_device.id,
1056 child_device)
1057 except Exception as e:
1058 self.log.error('adapter_agent error', error=e)
1059 try:
1060 self.delete_logical_port(child_device)
1061 except Exception as e:
1062 self.log.error('logical_port delete error', error=e)
1063 try:
1064 self.delete_port(child_device.serial_number)
1065 except Exception as e:
1066 self.log.error('port delete error', error=e)
1067 serial_number = self.destringify_serial_number(
1068 child_device.serial_number)
1069 # TODO FIXME - For each uni.
1070 # TODO FIXME - Flows are not deleted
1071 uni_id = 0 # FIXME
1072 self.flow_mgr.delete_tech_profile_instance(
1073 child_device.proxy_address.channel_id,
1074 child_device.proxy_address.onu_id,
1075 uni_id
1076 )
1077 pon_intf_id_onu_id = (child_device.proxy_address.channel_id,
1078 child_device.proxy_address.onu_id,
1079 uni_id)
1080 # Free any PON resources that were reserved for the ONU
1081 self.resource_mgr.free_pon_resources_for_onu(pon_intf_id_onu_id)
1082
1083 onu = openolt_pb2.Onu(intf_id=child_device.proxy_address.channel_id,
1084 onu_id=child_device.proxy_address.onu_id,
1085 serial_number=serial_number)
1086 self.stub.DeleteOnu(onu)
1087
1088 def reboot(self):
1089 self.log.debug('rebooting openolt device', device_id=self.device_id)
1090 try:
1091 self.stub.Reboot(openolt_pb2.Empty())
1092 except Exception as e:
1093 self.log.error('something went wrong with the reboot', error=e)
1094 else:
1095 self.log.info('device rebooted')
1096
1097 def trigger_statistics_collection(self):
1098 try:
1099 self.stub.CollectStatistics(openolt_pb2.Empty())
1100 except Exception as e:
1101 self.log.error('Error while triggering statistics collection',
1102 error=e)
1103 else:
1104 self.log.info('statistics requested')
1105
1106 def simulate_alarm(self, alarm):
1107 self.alarm_mgr.simulate_alarm(alarm)