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