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