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