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