1
|
|
|
"""NApp responsible to discover new switches and hosts.""" |
2
|
1 |
|
import struct |
3
|
1 |
|
import time |
4
|
|
|
|
5
|
1 |
|
import requests |
6
|
1 |
|
from flask import jsonify, request |
7
|
1 |
|
from pyof.foundation.basic_types import DPID, UBInt16, UBInt32 |
8
|
1 |
|
from pyof.foundation.network_types import LLDP, VLAN, Ethernet, EtherType |
9
|
1 |
|
from pyof.v0x01.common.action import ActionOutput as AO10 |
10
|
1 |
|
from pyof.v0x01.common.phy_port import Port as Port10 |
11
|
1 |
|
from pyof.v0x01.controller2switch.packet_out import PacketOut as PO10 |
12
|
1 |
|
from pyof.v0x04.common.action import ActionOutput as AO13 |
13
|
1 |
|
from pyof.v0x04.common.port import PortNo as Port13 |
14
|
1 |
|
from pyof.v0x04.controller2switch.packet_out import PacketOut as PO13 |
15
|
|
|
|
16
|
1 |
|
from kytos.core import KytosEvent, KytosNApp, log, rest |
17
|
1 |
|
from kytos.core.helpers import alisten_to, listen_to |
18
|
1 |
|
from kytos.core.link import Link |
19
|
1 |
|
from napps.kytos.of_core.msg_prios import of_msg_prio |
20
|
1 |
|
from napps.kytos.of_lldp import constants, settings |
21
|
1 |
|
from napps.kytos.of_lldp.loop_manager import LoopManager, LoopState |
22
|
1 |
|
from napps.kytos.of_lldp.managers import LivenessManager |
23
|
1 |
|
from napps.kytos.of_lldp.utils import get_cookie |
24
|
|
|
|
25
|
1 |
|
from .controllers import LivenessController |
26
|
|
|
|
27
|
|
|
|
28
|
1 |
|
class Main(KytosNApp): |
29
|
|
|
"""Main OF_LLDP NApp Class.""" |
30
|
|
|
|
31
|
1 |
|
def setup(self): |
32
|
|
|
"""Make this NApp run in a loop.""" |
33
|
1 |
|
self.vlan_id = None |
34
|
1 |
|
self.polling_time = settings.POLLING_TIME |
35
|
1 |
|
if hasattr(settings, "FLOW_VLAN_VID"): |
36
|
1 |
|
self.vlan_id = settings.FLOW_VLAN_VID |
37
|
1 |
|
self.liveness_dead_multipler = settings.LIVENESS_DEAD_MULTIPLIER |
38
|
1 |
|
self.execute_as_loop(self.polling_time) |
39
|
1 |
|
self.loop_manager = LoopManager(self.controller) |
40
|
1 |
|
self.dead_interval = self.polling_time * self.liveness_dead_multipler |
41
|
1 |
|
self.liveness_controller = self.get_liveness_controller() |
42
|
1 |
|
self.liveness_controller.bootstrap_indexes() |
43
|
1 |
|
self.liveness_manager = LivenessManager(self.controller) |
44
|
1 |
|
Link.register_status_func(f"{self.napp_id}_liveness", |
45
|
|
|
LivenessManager.link_status_hook_liveness) |
46
|
|
|
|
47
|
1 |
|
@staticmethod |
48
|
1 |
|
def get_liveness_controller() -> LivenessController: |
49
|
|
|
"""Get LivenessController.""" |
50
|
|
|
return LivenessController() |
51
|
|
|
|
52
|
1 |
|
def execute(self): |
53
|
|
|
"""Send LLDP Packets every 'POLLING_TIME' seconds to all switches.""" |
54
|
1 |
|
switches = list(self.controller.switches.values()) |
55
|
1 |
|
for switch in switches: |
56
|
1 |
|
try: |
57
|
1 |
|
of_version = switch.connection.protocol.version |
58
|
|
|
except AttributeError: |
59
|
|
|
of_version = None |
60
|
|
|
|
61
|
1 |
|
if not switch.is_connected(): |
62
|
|
|
continue |
63
|
|
|
|
64
|
1 |
|
if of_version == 0x01: |
65
|
1 |
|
port_type = UBInt16 |
66
|
1 |
|
local_port = Port10.OFPP_LOCAL |
67
|
1 |
|
elif of_version == 0x04: |
68
|
1 |
|
port_type = UBInt32 |
69
|
1 |
|
local_port = Port13.OFPP_LOCAL |
70
|
|
|
else: |
71
|
|
|
# skip the current switch with unsupported OF version |
72
|
|
|
continue |
73
|
|
|
|
74
|
1 |
|
interfaces = list(switch.interfaces.values()) |
75
|
1 |
|
for interface in interfaces: |
76
|
|
|
# Interface marked to receive lldp packet |
77
|
|
|
# Only send LLDP packet to active interface |
78
|
1 |
|
if(not interface.lldp or not interface.is_active() |
79
|
|
|
or not interface.is_enabled()): |
80
|
|
|
continue |
81
|
|
|
# Avoid the interface that connects to the controller. |
82
|
1 |
|
if interface.port_number == local_port: |
83
|
|
|
continue |
84
|
|
|
|
85
|
1 |
|
lldp = LLDP() |
86
|
1 |
|
lldp.chassis_id.sub_value = DPID(switch.dpid) |
87
|
1 |
|
lldp.port_id.sub_value = port_type(interface.port_number) |
88
|
|
|
|
89
|
1 |
|
ethernet = Ethernet() |
90
|
1 |
|
ethernet.ether_type = EtherType.LLDP |
91
|
1 |
|
ethernet.source = interface.address |
92
|
1 |
|
ethernet.destination = constants.LLDP_MULTICAST_MAC |
93
|
1 |
|
ethernet.data = lldp.pack() |
94
|
|
|
# self.vlan_id == None will result in a packet with no VLAN. |
95
|
1 |
|
ethernet.vlans.append(VLAN(vid=self.vlan_id)) |
96
|
|
|
|
97
|
1 |
|
packet_out = self._build_lldp_packet_out( |
98
|
|
|
of_version, |
99
|
|
|
interface.port_number, ethernet.pack()) |
100
|
|
|
|
101
|
1 |
|
if packet_out is None: |
102
|
|
|
continue |
103
|
|
|
|
104
|
1 |
|
event_out = KytosEvent( |
105
|
|
|
name='kytos/of_lldp.messages.out.ofpt_packet_out', |
106
|
|
|
priority=of_msg_prio(packet_out.header.message_type.value), |
107
|
|
|
content={ |
108
|
|
|
'destination': switch.connection, |
109
|
|
|
'message': packet_out}) |
110
|
|
|
|
111
|
1 |
|
self.controller.buffers.msg_out.put(event_out) |
112
|
1 |
|
log.debug( |
113
|
|
|
"Sending a LLDP PacketOut to the switch %s", |
114
|
|
|
switch.dpid) |
115
|
|
|
|
116
|
1 |
|
msg = 'Switch: %s (%s)' |
117
|
1 |
|
msg += ' Interface: %s' |
118
|
1 |
|
msg += ' -- LLDP PacketOut --' |
119
|
1 |
|
msg += ' Ethernet: eth_type (%s) | src (%s) | dst (%s) /' |
120
|
1 |
|
msg += ' LLDP: Switch (%s) | portno (%s)' |
121
|
|
|
|
122
|
1 |
|
log.debug( |
123
|
|
|
msg, |
124
|
|
|
switch.connection, switch.dpid, |
125
|
|
|
interface.id, ethernet.ether_type, |
126
|
|
|
ethernet.source, ethernet.destination, |
127
|
|
|
switch.dpid, interface.port_number) |
128
|
|
|
|
129
|
1 |
|
self.try_to_publish_stopped_loops() |
130
|
1 |
|
self.liveness_manager.reaper(self.dead_interval) |
131
|
|
|
|
132
|
1 |
|
def load_liveness(self) -> None: |
133
|
|
|
"""Load liveness.""" |
134
|
1 |
|
interfaces = {intf.id: intf for intf in self._get_interfaces()} |
135
|
1 |
|
intfs = self.liveness_controller.get_enabled_interfaces() |
136
|
1 |
|
intfs_to_enable = [interfaces[intf["id"]] for intf in intfs] |
137
|
1 |
|
self.liveness_manager.enable(*intfs_to_enable) |
138
|
|
|
|
139
|
1 |
|
def try_to_publish_stopped_loops(self): |
140
|
|
|
"""Try to publish current stopped loops.""" |
141
|
|
|
for dpid, port_pairs in self.loop_manager.get_stopped_loops().items(): |
142
|
|
|
try: |
143
|
|
|
switch = self.controller.get_switch_by_dpid(dpid) |
144
|
|
|
for port_pair in port_pairs: |
145
|
|
|
interface_a = switch.interfaces[port_pair[0]] |
146
|
|
|
interface_b = switch.interfaces[port_pair[1]] |
147
|
|
|
self.loop_manager.publish_loop_state( |
148
|
|
|
interface_a, interface_b, LoopState.stopped.value |
149
|
|
|
) |
150
|
|
|
except (KeyError, AttributeError) as exc: |
151
|
|
|
log.error("try_to_publish_stopped_loops failed with switch:" |
152
|
|
|
f"{dpid}, port_pair: {port_pair}. {str(exc)}") |
153
|
|
|
|
154
|
1 |
|
@listen_to('kytos/topology.switch.(enabled|disabled)') |
155
|
1 |
|
def handle_lldp_flows(self, event): |
156
|
|
|
"""Install or remove flows in a switch. |
157
|
|
|
|
158
|
|
|
Install a flow to send LLDP packets to the controller. The proactive |
159
|
|
|
flow is installed whenever a switch is enabled. If the switch is |
160
|
|
|
disabled the flow is removed. |
161
|
|
|
|
162
|
|
|
Args: |
163
|
|
|
event (:class:`~kytos.core.events.KytosEvent`): |
164
|
|
|
Event with new switch information. |
165
|
|
|
|
166
|
|
|
""" |
167
|
|
|
self._handle_lldp_flows(event) |
168
|
|
|
|
169
|
1 |
|
@listen_to("kytos/of_lldp.loop.action.log") |
170
|
1 |
|
def on_lldp_loop_log_action(self, event): |
171
|
|
|
"""Handle LLDP loop log action.""" |
172
|
|
|
interface_a = event.content["interface_a"] |
173
|
|
|
interface_b = event.content["interface_b"] |
174
|
|
|
self.loop_manager.handle_log_action(interface_a, interface_b) |
175
|
|
|
|
176
|
1 |
|
@listen_to("kytos/of_lldp.loop.action.disable") |
177
|
1 |
|
def on_lldp_loop_disable_action(self, event): |
178
|
|
|
"""Handle LLDP loop disable action.""" |
179
|
|
|
interface_a = event.content["interface_a"] |
180
|
|
|
interface_b = event.content["interface_b"] |
181
|
|
|
self.loop_manager.handle_disable_action(interface_a, interface_b) |
182
|
|
|
|
183
|
1 |
|
@listen_to("kytos/of_lldp.loop.detected") |
184
|
1 |
|
def on_lldp_loop_detected(self, event): |
185
|
|
|
"""Handle LLDP loop detected.""" |
186
|
|
|
interface_id = event.content["interface_id"] |
187
|
|
|
dpid = event.content["dpid"] |
188
|
|
|
port_pair = event.content["port_numbers"] |
189
|
|
|
self.loop_manager.handle_loop_detected(interface_id, dpid, port_pair) |
190
|
|
|
|
191
|
1 |
|
@listen_to("kytos/of_lldp.loop.stopped") |
192
|
1 |
|
def on_lldp_loop_stopped(self, event): |
193
|
|
|
"""Handle LLDP loop stopped.""" |
194
|
|
|
dpid = event.content["dpid"] |
195
|
|
|
port_pair = event.content["port_numbers"] |
196
|
|
|
try: |
197
|
|
|
switch = self.controller.get_switch_by_dpid(dpid) |
198
|
|
|
interface_a = switch.interfaces[port_pair[0]] |
199
|
|
|
interface_b = switch.interfaces[port_pair[1]] |
200
|
|
|
self.loop_manager.handle_loop_stopped(interface_a, interface_b) |
201
|
|
|
except (KeyError, AttributeError) as exc: |
202
|
|
|
log.error("on_lldp_loop_stopped failed with: " |
203
|
|
|
f"{event.content} {str(exc)}") |
204
|
|
|
|
205
|
1 |
|
@listen_to("kytos/topology.topology_loaded") |
206
|
1 |
|
def on_topology_loaded(self, event): |
207
|
|
|
"""Handle on topology loaded.""" |
208
|
|
|
self.handle_topology_loaded(event) |
209
|
|
|
|
210
|
1 |
|
def handle_topology_loaded(self, event) -> None: |
211
|
|
|
"""Handle on topology loaded.""" |
212
|
1 |
|
topology = event.content["topology"] |
213
|
1 |
|
self.loop_manager.handle_topology_loaded(topology) |
214
|
1 |
|
self.load_liveness() |
215
|
|
|
|
216
|
1 |
|
@listen_to("kytos/topology.switches.metadata.(added|removed)") |
217
|
1 |
|
def on_switches_metadata_changed(self, event): |
218
|
|
|
"""Handle on switches metadata changed.""" |
219
|
|
|
switch = event.content["switch"] |
220
|
|
|
self.loop_manager.handle_switch_metadata_changed(switch) |
221
|
|
|
|
222
|
1 |
|
def _handle_lldp_flows(self, event): |
223
|
|
|
"""Install or remove flows in a switch. |
224
|
|
|
|
225
|
|
|
Install a flow to send LLDP packets to the controller. The proactive |
226
|
|
|
flow is installed whenever a switch is enabled. If the switch is |
227
|
|
|
disabled the flow is removed. |
228
|
|
|
""" |
229
|
1 |
|
try: |
230
|
1 |
|
dpid = event.content['dpid'] |
231
|
1 |
|
switch = self.controller.get_switch_by_dpid(dpid) |
232
|
1 |
|
of_version = switch.connection.protocol.version |
233
|
|
|
|
234
|
|
|
except AttributeError: |
235
|
|
|
of_version = None |
236
|
|
|
|
237
|
1 |
|
def _retry_if_status_code(response, endpoint, data, status_codes, |
238
|
|
|
retries=3, wait=2): |
239
|
|
|
"""Retry if the response is in the status_codes.""" |
240
|
1 |
|
if response.status_code not in status_codes: |
241
|
1 |
|
return |
242
|
1 |
|
if retries - 1 <= 0: |
243
|
1 |
|
return |
244
|
1 |
|
data = dict(data) |
245
|
1 |
|
data["force"] = True |
246
|
1 |
|
res = requests.post(endpoint, json=data) |
247
|
1 |
|
method = res.request.method |
248
|
1 |
|
if res.status_code != 202: |
249
|
1 |
|
log.error(f"Failed to retry on {endpoint}, error: {res.text}," |
250
|
|
|
f" status: {res.status_code}, method: {method}," |
251
|
|
|
f" data: {data}") |
252
|
1 |
|
time.sleep(wait) |
253
|
1 |
|
return _retry_if_status_code(response, endpoint, data, |
254
|
|
|
status_codes, retries - 1, wait) |
255
|
|
|
log.info(f"Successfully forced {method} flows to {endpoint}") |
256
|
|
|
|
257
|
1 |
|
flow = self._build_lldp_flow(of_version, get_cookie(switch.dpid)) |
258
|
1 |
|
if flow: |
259
|
1 |
|
destination = switch.id |
260
|
1 |
|
endpoint = f'{settings.FLOW_MANAGER_URL}/flows/{destination}' |
261
|
1 |
|
data = {'flows': [flow]} |
262
|
1 |
|
if event.name == 'kytos/topology.switch.enabled': |
263
|
1 |
|
flow.pop("cookie_mask") |
264
|
1 |
|
res = requests.post(endpoint, json=data) |
265
|
1 |
|
if res.status_code != 202: |
266
|
1 |
|
log.error(f"Failed to push flows on {destination}," |
267
|
|
|
f" error: {res.text}, status: {res.status_code}," |
268
|
|
|
f" data: {data}") |
269
|
1 |
|
_retry_if_status_code(res, endpoint, data, [424, 500]) |
270
|
|
|
else: |
271
|
1 |
|
res = requests.delete(endpoint, json=data) |
272
|
1 |
|
if res.status_code != 202: |
273
|
|
|
log.error(f"Failed to delete flows on {destination}," |
274
|
|
|
f" error: {res.text}, status: {res.status_code}," |
275
|
|
|
f" data: {data}") |
276
|
1 |
|
_retry_if_status_code(res, endpoint, data, [424, 500]) |
277
|
|
|
|
278
|
1 |
|
@alisten_to('kytos/of_core.v0x0[14].messages.in.ofpt_packet_in') |
279
|
1 |
|
async def on_ofpt_packet_in(self, event): |
280
|
|
|
"""Dispatch two KytosEvents to notify identified NNI interfaces. |
281
|
|
|
|
282
|
|
|
Args: |
283
|
|
|
event (:class:`~kytos.core.events.KytosEvent`): |
284
|
|
|
Event with an LLDP packet as data. |
285
|
|
|
|
286
|
|
|
""" |
287
|
1 |
|
ethernet = self._unpack_non_empty(Ethernet, event.message.data) |
288
|
1 |
|
if ethernet.ether_type == EtherType.LLDP: |
289
|
1 |
|
try: |
290
|
1 |
|
lldp = self._unpack_non_empty(LLDP, ethernet.data) |
291
|
1 |
|
dpid = self._unpack_non_empty(DPID, lldp.chassis_id.sub_value) |
292
|
|
|
except struct.error: |
293
|
|
|
#: If we have a LLDP packet but we cannot unpack it, or the |
294
|
|
|
#: unpacked packet does not contain the dpid attribute, then |
295
|
|
|
#: we are dealing with a LLDP generated by someone else. Thus |
296
|
|
|
#: this packet is not useful for us and we may just ignore it. |
297
|
|
|
return |
298
|
|
|
|
299
|
1 |
|
switch_a = event.source.switch |
300
|
1 |
|
port_a = event.message.in_port |
301
|
1 |
|
switch_b = None |
302
|
1 |
|
port_b = None |
303
|
|
|
|
304
|
|
|
# in_port is currently a UBInt16 in v0x01 and an Int in v0x04. |
305
|
1 |
|
if isinstance(port_a, int): |
306
|
1 |
|
port_a = UBInt32(port_a) |
307
|
|
|
|
308
|
1 |
|
try: |
309
|
1 |
|
switch_b = self.controller.get_switch_by_dpid(dpid.value) |
310
|
1 |
|
of_version = switch_b.connection.protocol.version |
311
|
1 |
|
port_type = UBInt16 if of_version == 0x01 else UBInt32 |
312
|
1 |
|
port_b = self._unpack_non_empty(port_type, |
313
|
|
|
lldp.port_id.sub_value) |
314
|
|
|
except AttributeError: |
315
|
|
|
log.debug("Couldn't find datapath %s.", dpid.value) |
316
|
|
|
|
317
|
|
|
# Return if any of the needed information are not available |
318
|
1 |
|
if not (switch_a and port_a and switch_b and port_b): |
319
|
|
|
return |
320
|
|
|
|
321
|
1 |
|
interface_a = switch_a.get_interface_by_port_no(port_a.value) |
322
|
1 |
|
interface_b = switch_b.get_interface_by_port_no(port_b.value) |
323
|
|
|
|
324
|
1 |
|
await self.loop_manager.process_if_looped(interface_a, interface_b) |
325
|
1 |
|
await self.liveness_manager.consume_hello_if_enabled(interface_a, |
326
|
|
|
interface_b) |
327
|
1 |
|
event_out = KytosEvent(name='kytos/of_lldp.interface.is.nni', |
328
|
|
|
content={'interface_a': interface_a, |
329
|
|
|
'interface_b': interface_b}) |
330
|
1 |
|
await self.controller.buffers.app.aput(event_out) |
331
|
|
|
|
332
|
1 |
|
def notify_lldp_change(self, state, interface_ids): |
333
|
|
|
"""Dispatch a KytosEvent to notify changes to the LLDP status.""" |
334
|
1 |
|
content = {'attribute': 'LLDP', |
335
|
|
|
'state': state, |
336
|
|
|
'interface_ids': interface_ids} |
337
|
1 |
|
event_out = KytosEvent(name='kytos/of_lldp.network_status.updated', |
338
|
|
|
content=content) |
339
|
1 |
|
self.controller.buffers.app.put(event_out) |
340
|
|
|
|
341
|
1 |
|
def publish_liveness_status(self, event_suffix, interfaces): |
342
|
|
|
"""Dispatch a KytosEvent to publish liveness admin status.""" |
343
|
1 |
|
content = {"interfaces": interfaces} |
344
|
1 |
|
name = f"kytos/of_lldp.liveness.{event_suffix}" |
345
|
1 |
|
event_out = KytosEvent(name=name, content=content) |
346
|
1 |
|
self.controller.buffers.app.put(event_out) |
347
|
|
|
|
348
|
1 |
|
def shutdown(self): |
349
|
|
|
"""End of the application.""" |
350
|
|
|
log.debug('Shutting down...') |
351
|
|
|
|
352
|
1 |
|
@staticmethod |
353
|
1 |
|
def _build_lldp_packet_out(version, port_number, data): |
354
|
|
|
"""Build a LLDP PacketOut message. |
355
|
|
|
|
356
|
|
|
Args: |
357
|
|
|
version (int): OpenFlow version |
358
|
|
|
port_number (int): Switch port number where the packet must be |
359
|
|
|
forwarded to. |
360
|
|
|
data (bytes): Binary data to be sent through the port. |
361
|
|
|
|
362
|
|
|
Returns: |
363
|
|
|
PacketOut message for the specific given OpenFlow version, if it |
364
|
|
|
is supported. |
365
|
|
|
None if the OpenFlow version is not supported. |
366
|
|
|
|
367
|
|
|
""" |
368
|
1 |
|
if version == 0x01: |
369
|
1 |
|
action_output_class = AO10 |
370
|
1 |
|
packet_out_class = PO10 |
371
|
1 |
|
elif version == 0x04: |
372
|
1 |
|
action_output_class = AO13 |
373
|
1 |
|
packet_out_class = PO13 |
374
|
|
|
else: |
375
|
1 |
|
log.info('Openflow version %s is not yet supported.', version) |
376
|
1 |
|
return None |
377
|
|
|
|
378
|
1 |
|
output_action = action_output_class() |
379
|
1 |
|
output_action.port = port_number |
380
|
|
|
|
381
|
1 |
|
packet_out = packet_out_class() |
382
|
1 |
|
packet_out.data = data |
383
|
1 |
|
packet_out.actions.append(output_action) |
384
|
|
|
|
385
|
1 |
|
return packet_out |
386
|
|
|
|
387
|
1 |
|
def _build_lldp_flow(self, version, cookie, |
388
|
|
|
cookie_mask=0xffffffffffffffff): |
389
|
|
|
"""Build a Flow message to send LLDP to the controller. |
390
|
|
|
|
391
|
|
|
Args: |
392
|
|
|
version (int): OpenFlow version. |
393
|
|
|
|
394
|
|
|
Returns: |
395
|
|
|
Flow dictionary message for the specific given OpenFlow version, |
396
|
|
|
if it is supported. |
397
|
|
|
None if the OpenFlow version is not supported. |
398
|
|
|
|
399
|
|
|
""" |
400
|
1 |
|
flow = {} |
401
|
1 |
|
match = {} |
402
|
1 |
|
flow['priority'] = settings.FLOW_PRIORITY |
403
|
1 |
|
flow['table_id'] = settings.TABLE_ID |
404
|
1 |
|
flow['cookie'] = cookie |
405
|
1 |
|
flow['cookie_mask'] = cookie_mask |
406
|
1 |
|
match['dl_type'] = EtherType.LLDP |
407
|
1 |
|
if self.vlan_id: |
408
|
1 |
|
match['dl_vlan'] = self.vlan_id |
409
|
1 |
|
flow['match'] = match |
410
|
|
|
|
411
|
1 |
|
if version == 0x01: |
412
|
1 |
|
flow['actions'] = [{'action_type': 'output', |
413
|
|
|
'port': Port10.OFPP_CONTROLLER}] |
414
|
1 |
|
elif version == 0x04: |
415
|
1 |
|
flow['actions'] = [{'action_type': 'output', |
416
|
|
|
'port': Port13.OFPP_CONTROLLER}] |
417
|
|
|
else: |
418
|
|
|
flow = None |
419
|
|
|
|
420
|
1 |
|
return flow |
421
|
|
|
|
422
|
1 |
|
@staticmethod |
423
|
1 |
|
def _unpack_non_empty(desired_class, data): |
424
|
|
|
"""Unpack data using an instance of desired_class. |
425
|
|
|
|
426
|
|
|
Args: |
427
|
|
|
desired_class (class): The class to be used to unpack data. |
428
|
|
|
data (bytes): bytes to be unpacked. |
429
|
|
|
|
430
|
|
|
Return: |
431
|
|
|
An instance of desired_class class with data unpacked into it. |
432
|
|
|
|
433
|
|
|
Raises: |
434
|
|
|
UnpackException if the unpack could not be performed. |
435
|
|
|
|
436
|
|
|
""" |
437
|
1 |
|
obj = desired_class() |
438
|
|
|
|
439
|
1 |
|
if hasattr(data, 'value'): |
440
|
1 |
|
data = data.value |
441
|
|
|
|
442
|
1 |
|
obj.unpack(data) |
443
|
|
|
|
444
|
1 |
|
return obj |
445
|
|
|
|
446
|
1 |
|
@staticmethod |
447
|
1 |
|
def _get_data(req): |
448
|
|
|
"""Get request data.""" |
449
|
1 |
|
data = req.get_json() # Valid format { "interfaces": [...] } |
450
|
1 |
|
return data.get('interfaces', []) |
451
|
|
|
|
452
|
1 |
|
def _get_interfaces(self): |
453
|
|
|
"""Get all interfaces.""" |
454
|
1 |
|
interfaces = [] |
455
|
1 |
|
for switch in list(self.controller.switches.values()): |
456
|
1 |
|
interfaces += list(switch.interfaces.values()) |
457
|
1 |
|
return interfaces |
458
|
|
|
|
459
|
1 |
|
@staticmethod |
460
|
1 |
|
def _get_interfaces_dict(interfaces): |
461
|
|
|
"""Return a dict of interfaces.""" |
462
|
1 |
|
return {inter.id: inter for inter in interfaces} |
463
|
|
|
|
464
|
1 |
|
def _get_lldp_interfaces(self): |
465
|
|
|
"""Get interfaces enabled to receive LLDP packets.""" |
466
|
1 |
|
return [inter.id for inter in self._get_interfaces() if inter.lldp] |
467
|
|
|
|
468
|
1 |
|
@rest('v1/interfaces', methods=['GET']) |
469
|
1 |
|
def get_lldp_interfaces(self): |
470
|
|
|
"""Return all the interfaces that have LLDP traffic enabled.""" |
471
|
1 |
|
return jsonify({"interfaces": self._get_lldp_interfaces()}), 200 |
472
|
|
|
|
473
|
1 |
|
@rest('v1/interfaces/disable', methods=['POST']) |
474
|
1 |
|
def disable_lldp(self): |
475
|
|
|
"""Disables an interface to receive LLDP packets.""" |
476
|
1 |
|
interface_ids = self._get_data(request) |
477
|
1 |
|
error_list = [] # List of interfaces that were not activated. |
478
|
1 |
|
changed_interfaces = [] |
479
|
1 |
|
interface_ids = filter(None, interface_ids) |
480
|
1 |
|
interfaces = self._get_interfaces() |
481
|
1 |
|
intfs = [] |
482
|
1 |
|
if not interfaces: |
483
|
1 |
|
return jsonify("No interfaces were found."), 404 |
484
|
1 |
|
interfaces = self._get_interfaces_dict(interfaces) |
485
|
1 |
|
for id_ in interface_ids: |
486
|
1 |
|
interface = interfaces.get(id_) |
487
|
1 |
|
if interface: |
488
|
1 |
|
interface.lldp = False |
489
|
1 |
|
changed_interfaces.append(id_) |
490
|
1 |
|
intfs.append(interface) |
491
|
|
|
else: |
492
|
1 |
|
error_list.append(id_) |
493
|
1 |
|
if changed_interfaces: |
494
|
1 |
|
self.notify_lldp_change('disabled', changed_interfaces) |
495
|
1 |
|
intf_ids = [intf.id for intf in intfs] |
496
|
1 |
|
self.liveness_controller.disable_interfaces(intf_ids) |
497
|
1 |
|
self.liveness_manager.disable(*intfs) |
498
|
1 |
|
self.publish_liveness_status("disabled", intfs) |
499
|
1 |
|
if not error_list: |
500
|
1 |
|
return jsonify( |
501
|
|
|
"All the requested interfaces have been disabled."), 200 |
502
|
|
|
|
503
|
|
|
# Return a list of interfaces that couldn't be disabled |
504
|
1 |
|
msg_error = "Some interfaces couldn't be found and deactivated: " |
505
|
1 |
|
return jsonify({msg_error: |
506
|
|
|
error_list}), 400 |
507
|
|
|
|
508
|
1 |
|
@rest('v1/interfaces/enable', methods=['POST']) |
509
|
1 |
|
def enable_lldp(self): |
510
|
|
|
"""Enable an interface to receive LLDP packets.""" |
511
|
1 |
|
interface_ids = self._get_data(request) |
512
|
1 |
|
error_list = [] # List of interfaces that were not activated. |
513
|
1 |
|
changed_interfaces = [] |
514
|
1 |
|
interface_ids = filter(None, interface_ids) |
515
|
1 |
|
interfaces = self._get_interfaces() |
516
|
1 |
|
if not interfaces: |
517
|
1 |
|
return jsonify("No interfaces were found."), 404 |
518
|
1 |
|
interfaces = self._get_interfaces_dict(interfaces) |
519
|
1 |
|
for id_ in interface_ids: |
520
|
1 |
|
interface = interfaces.get(id_) |
521
|
1 |
|
if interface: |
522
|
1 |
|
interface.lldp = True |
523
|
1 |
|
changed_interfaces.append(id_) |
524
|
|
|
else: |
525
|
1 |
|
error_list.append(id_) |
526
|
1 |
|
if changed_interfaces: |
527
|
1 |
|
self.notify_lldp_change('enabled', changed_interfaces) |
528
|
1 |
|
if not error_list: |
529
|
1 |
|
return jsonify( |
530
|
|
|
"All the requested interfaces have been enabled."), 200 |
531
|
|
|
|
532
|
|
|
# Return a list of interfaces that couldn't be enabled |
533
|
1 |
|
msg_error = "Some interfaces couldn't be found and activated: " |
534
|
1 |
|
return jsonify({msg_error: |
535
|
|
|
error_list}), 400 |
536
|
|
|
|
537
|
1 |
|
@rest("v1/liveness/enable", methods=["POST"]) |
538
|
1 |
|
def enable_liveness(self): |
539
|
|
|
"""Enable liveness link detection on interfaces.""" |
540
|
1 |
|
intf_ids = self._get_data(request) |
541
|
1 |
|
if not intf_ids: |
542
|
|
|
return jsonify("Interfaces payload is empty"), 400 |
543
|
1 |
|
interfaces = {intf.id: intf for intf in self._get_interfaces()} |
544
|
1 |
|
diff = set(intf_ids) - set(interfaces.keys()) |
545
|
1 |
|
if diff: |
546
|
|
|
return jsonify(f"Interface IDs {diff} not found"), 404 |
547
|
|
|
|
548
|
1 |
|
intfs = [interfaces[_id] for _id in intf_ids] |
549
|
1 |
|
non_lldp = [intf.id for intf in intfs if not intf.lldp] |
550
|
1 |
|
if non_lldp: |
551
|
|
|
msg = f"Interface IDs {non_lldp} don't have LLDP enabled" |
552
|
|
|
return jsonify(msg), 400 |
553
|
1 |
|
self.liveness_controller.enable_interfaces(intf_ids) |
554
|
1 |
|
self.liveness_manager.enable(*intfs) |
555
|
1 |
|
self.publish_liveness_status("enabled", intfs) |
556
|
1 |
|
return jsonify(), 200 |
557
|
|
|
|
558
|
1 |
|
@rest("v1/liveness/disable", methods=["POST"]) |
559
|
1 |
|
def disable_liveness(self): |
560
|
|
|
"""Disable liveness link detection on interfaces.""" |
561
|
1 |
|
intf_ids = self._get_data(request) |
562
|
1 |
|
if not intf_ids: |
563
|
|
|
return jsonify("Interfaces payload is empty"), 400 |
564
|
|
|
|
565
|
1 |
|
interfaces = {intf.id: intf for intf in self._get_interfaces()} |
566
|
1 |
|
diff = set(intf_ids) - set(interfaces.keys()) |
567
|
1 |
|
if diff: |
568
|
|
|
return jsonify(f"Interface IDs {diff} not found"), 404 |
569
|
|
|
|
570
|
1 |
|
intfs = [interfaces[_id] for _id in intf_ids if _id in interfaces] |
571
|
1 |
|
self.liveness_controller.disable_interfaces(intf_ids) |
572
|
1 |
|
self.liveness_manager.disable(*intfs) |
573
|
1 |
|
self.publish_liveness_status("disabled", intfs) |
574
|
1 |
|
return jsonify(), 200 |
575
|
|
|
|
576
|
1 |
|
@rest("v1/liveness/", methods=["GET"]) |
577
|
1 |
|
def get_liveness_interfaces(self): |
578
|
|
|
"""Get liveness interfaces.""" |
579
|
1 |
|
args = request.args |
580
|
1 |
|
interface_id = args.get("interface_id") |
581
|
1 |
|
if interface_id: |
582
|
|
|
status, last_hello_at = self.liveness_manager.get_interface_status( |
583
|
|
|
interface_id |
584
|
|
|
) |
585
|
|
|
if not status: |
586
|
|
|
return {"interfaces": []}, 200 |
587
|
|
|
body = { |
588
|
|
|
"interfaces": [ |
589
|
|
|
{ |
590
|
|
|
"id": interface_id, |
591
|
|
|
"status": status, |
592
|
|
|
"last_hello_at": last_hello_at, |
593
|
|
|
} |
594
|
|
|
] |
595
|
|
|
} |
596
|
|
|
return jsonify(body), 200 |
597
|
1 |
|
interfaces = [] |
598
|
1 |
|
for interface_id in list(self.liveness_manager.interfaces.keys()): |
599
|
|
|
status, last_hello_at = self.liveness_manager.get_interface_status( |
600
|
|
|
interface_id |
601
|
|
|
) |
602
|
|
|
interfaces.append({"id": interface_id, "status": status, |
603
|
|
|
"last_hello_at": last_hello_at}) |
604
|
1 |
|
return jsonify({"interfaces": interfaces}), 200 |
605
|
|
|
|
606
|
1 |
|
@rest("v1/liveness/pair", methods=["GET"]) |
607
|
1 |
|
def get_liveness_interface_pairs(self): |
608
|
|
|
"""Get liveness interface pairs.""" |
609
|
1 |
|
pairs = [] |
610
|
1 |
|
for entry in list(self.liveness_manager.liveness.values()): |
611
|
|
|
lsm = entry["lsm"] |
612
|
|
|
pair = { |
613
|
|
|
"interface_a": { |
614
|
|
|
"id": entry["interface_a"].id, |
615
|
|
|
"status": lsm.ilsm_a.state, |
616
|
|
|
"last_hello_at": lsm.ilsm_a.last_hello_at, |
617
|
|
|
}, |
618
|
|
|
"interface_b": { |
619
|
|
|
"id": entry["interface_b"].id, |
620
|
|
|
"status": lsm.ilsm_b.state, |
621
|
|
|
"last_hello_at": lsm.ilsm_b.last_hello_at, |
622
|
|
|
}, |
623
|
|
|
"status": lsm.state |
624
|
|
|
} |
625
|
|
|
pairs.append(pair) |
626
|
1 |
|
return jsonify({"pairs": pairs}) |
627
|
|
|
|
628
|
1 |
|
@rest('v1/polling_time', methods=['GET']) |
629
|
1 |
|
def get_time(self): |
630
|
|
|
"""Get LLDP polling time in seconds.""" |
631
|
1 |
|
return jsonify({"polling_time": self.polling_time}), 200 |
632
|
|
|
|
633
|
1 |
|
@rest('v1/polling_time', methods=['POST']) |
634
|
1 |
|
def set_time(self): |
635
|
|
|
"""Set LLDP polling time.""" |
636
|
|
|
# pylint: disable=attribute-defined-outside-init |
637
|
1 |
|
try: |
638
|
1 |
|
payload = request.get_json() |
639
|
1 |
|
polling_time = int(payload['polling_time']) |
640
|
1 |
|
if polling_time <= 0: |
641
|
|
|
raise ValueError(f"invalid polling_time {polling_time}, " |
642
|
|
|
"must be greater than zero") |
643
|
1 |
|
self.polling_time = polling_time |
644
|
1 |
|
self.execute_as_loop(self.polling_time) |
645
|
1 |
|
log.info("Polling time has been updated to %s" |
646
|
|
|
" second(s), but this change will not be saved" |
647
|
|
|
" permanently.", self.polling_time) |
648
|
1 |
|
return jsonify("Polling time has been updated."), 200 |
649
|
1 |
|
except (ValueError, KeyError) as error: |
650
|
1 |
|
msg = f"This operation is not completed: {error}" |
651
|
|
|
return jsonify(msg), 400 |
652
|
|
|
|