1
|
|
|
"""NApp responsible to discover new switches and hosts.""" |
2
|
1 |
|
import struct |
3
|
|
|
|
4
|
1 |
|
import requests |
5
|
1 |
|
from flask import jsonify, request |
6
|
1 |
|
from pyof.foundation.basic_types import DPID, UBInt16, UBInt32 |
7
|
1 |
|
from pyof.foundation.network_types import LLDP, VLAN, Ethernet, EtherType |
8
|
1 |
|
from pyof.v0x01.common.action import ActionOutput as AO10 |
9
|
1 |
|
from pyof.v0x01.common.phy_port import Port as Port10 |
10
|
1 |
|
from pyof.v0x01.controller2switch.packet_out import PacketOut as PO10 |
11
|
1 |
|
from pyof.v0x04.common.action import ActionOutput as AO13 |
12
|
1 |
|
from pyof.v0x04.common.port import PortNo as Port13 |
13
|
1 |
|
from pyof.v0x04.controller2switch.packet_out import PacketOut as PO13 |
14
|
|
|
|
15
|
1 |
|
from kytos.core import KytosEvent, KytosNApp, log, rest |
16
|
1 |
|
from kytos.core.helpers import listen_to |
17
|
1 |
|
from napps.kytos.of_lldp import constants, settings |
18
|
|
|
|
19
|
|
|
|
20
|
1 |
|
class Main(KytosNApp): |
21
|
|
|
"""Main OF_LLDP NApp Class.""" |
22
|
|
|
|
23
|
1 |
|
def setup(self): |
24
|
|
|
"""Make this NApp run in a loop.""" |
25
|
1 |
|
self.vlan_id = None |
26
|
1 |
|
self.polling_time = settings.POLLING_TIME |
27
|
1 |
|
if hasattr(settings, "FLOW_VLAN_VID"): |
28
|
1 |
|
self.vlan_id = settings.FLOW_VLAN_VID |
29
|
1 |
|
self.execute_as_loop(self.polling_time) |
30
|
|
|
|
31
|
1 |
|
def execute(self): |
32
|
|
|
"""Send LLDP Packets every 'POLLING_TIME' seconds to all switches.""" |
33
|
1 |
|
switches = list(self.controller.switches.values()) |
34
|
1 |
|
for switch in switches: |
35
|
1 |
|
try: |
36
|
1 |
|
of_version = switch.connection.protocol.version |
37
|
|
|
except AttributeError: |
38
|
|
|
of_version = None |
39
|
|
|
|
40
|
1 |
|
if not switch.is_connected(): |
41
|
|
|
continue |
42
|
|
|
|
43
|
1 |
|
if of_version == 0x01: |
44
|
1 |
|
port_type = UBInt16 |
45
|
1 |
|
local_port = Port10.OFPP_LOCAL |
46
|
1 |
|
elif of_version == 0x04: |
47
|
1 |
|
port_type = UBInt32 |
48
|
1 |
|
local_port = Port13.OFPP_LOCAL |
49
|
|
|
else: |
50
|
|
|
# skip the current switch with unsupported OF version |
51
|
|
|
continue |
52
|
|
|
|
53
|
1 |
|
interfaces = list(switch.interfaces.values()) |
54
|
1 |
|
for interface in interfaces: |
55
|
|
|
# Interface marked to receive lldp packet |
56
|
|
|
# Only send LLDP packet to active interface |
57
|
1 |
|
if(not interface.lldp or not interface.is_active() |
58
|
|
|
or not interface.is_enabled()): |
59
|
|
|
continue |
60
|
|
|
# Avoid the interface that connects to the controller. |
61
|
1 |
|
if interface.port_number == local_port: |
62
|
|
|
continue |
63
|
|
|
|
64
|
1 |
|
lldp = LLDP() |
65
|
1 |
|
lldp.chassis_id.sub_value = DPID(switch.dpid) |
66
|
1 |
|
lldp.port_id.sub_value = port_type(interface.port_number) |
67
|
|
|
|
68
|
1 |
|
ethernet = Ethernet() |
69
|
1 |
|
ethernet.ether_type = EtherType.LLDP |
70
|
1 |
|
ethernet.source = interface.address |
71
|
1 |
|
ethernet.destination = constants.LLDP_MULTICAST_MAC |
72
|
1 |
|
ethernet.data = lldp.pack() |
73
|
|
|
# self.vlan_id == None will result in a packet with no VLAN. |
74
|
1 |
|
ethernet.vlans.append(VLAN(vid=self.vlan_id)) |
75
|
|
|
|
76
|
1 |
|
packet_out = self._build_lldp_packet_out( |
77
|
|
|
of_version, |
78
|
|
|
interface.port_number, ethernet.pack()) |
79
|
|
|
|
80
|
1 |
|
if packet_out is None: |
81
|
|
|
continue |
82
|
|
|
|
83
|
1 |
|
event_out = KytosEvent( |
84
|
|
|
name='kytos/of_lldp.messages.out.ofpt_packet_out', |
85
|
|
|
content={ |
86
|
|
|
'destination': switch.connection, |
87
|
|
|
'message': packet_out}) |
88
|
1 |
|
self.controller.buffers.msg_out.put(event_out) |
89
|
1 |
|
log.debug( |
90
|
|
|
"Sending a LLDP PacketOut to the switch %s", |
91
|
|
|
switch.dpid) |
92
|
|
|
|
93
|
1 |
|
msg = '\n' |
94
|
1 |
|
msg += 'Switch: %s (%s)\n' |
95
|
1 |
|
msg += ' Interfaces: %s\n' |
96
|
1 |
|
msg += ' -- LLDP PacketOut --\n' |
97
|
1 |
|
msg += ' Ethernet: eth_type (%s) | src (%s) | dst (%s)' |
98
|
1 |
|
msg += '\n' |
99
|
1 |
|
msg += ' LLDP: Switch (%s) | port (%s)' |
100
|
|
|
|
101
|
1 |
|
log.debug( |
102
|
|
|
msg, |
103
|
|
|
switch.connection.address, switch.dpid, |
104
|
|
|
switch.interfaces, ethernet.ether_type, |
105
|
|
|
ethernet.source, ethernet.destination, |
106
|
|
|
switch.dpid, interface.port_number) |
107
|
|
|
|
108
|
1 |
|
@listen_to('kytos/topology.switch.(enabled|disabled)') |
109
|
|
|
def handle_lldp_flows(self, event): |
110
|
|
|
"""Install or remove flows in a switch. |
111
|
|
|
|
112
|
|
|
Install a flow to send LLDP packets to the controller. The proactive |
113
|
|
|
flow is installed whenever a switch is enabled. If the switch is |
114
|
|
|
disabled the flow is removed. |
115
|
|
|
|
116
|
|
|
Args: |
117
|
|
|
event (:class:`~kytos.core.events.KytosEvent`): |
118
|
|
|
Event with new switch information. |
119
|
|
|
|
120
|
|
|
""" |
121
|
1 |
|
try: |
122
|
1 |
|
dpid = event.content['dpid'] |
123
|
1 |
|
switch = self.controller.get_switch_by_dpid(dpid) |
124
|
1 |
|
of_version = switch.connection.protocol.version |
125
|
|
|
|
126
|
|
|
except AttributeError: |
127
|
|
|
of_version = None |
128
|
|
|
|
129
|
1 |
|
flow = self._build_lldp_flow(of_version) |
130
|
1 |
|
if flow: |
131
|
1 |
|
destination = switch.id |
132
|
1 |
|
endpoint = f'{settings.FLOW_MANAGER_URL}/flows/{destination}' |
133
|
1 |
|
data = {'flows': [flow]} |
134
|
1 |
|
if event.name == 'kytos/topology.switch.enabled': |
135
|
1 |
|
requests.post(endpoint, json=data) |
136
|
|
|
else: |
137
|
1 |
|
requests.delete(endpoint, json=data) |
138
|
|
|
|
139
|
1 |
|
@listen_to('kytos/of_core.v0x0[14].messages.in.ofpt_packet_in') |
140
|
|
|
def notify_uplink_detected(self, event): |
141
|
|
|
"""Dispatch two KytosEvents to notify identified NNI interfaces. |
142
|
|
|
|
143
|
|
|
Args: |
144
|
|
|
event (:class:`~kytos.core.events.KytosEvent`): |
145
|
|
|
Event with an LLDP packet as data. |
146
|
|
|
|
147
|
|
|
""" |
148
|
1 |
|
ethernet = self._unpack_non_empty(Ethernet, event.message.data) |
149
|
1 |
|
if ethernet.ether_type == EtherType.LLDP: |
150
|
1 |
|
try: |
151
|
1 |
|
lldp = self._unpack_non_empty(LLDP, ethernet.data) |
152
|
1 |
|
dpid = self._unpack_non_empty(DPID, lldp.chassis_id.sub_value) |
153
|
|
|
except struct.error: |
154
|
|
|
#: If we have a LLDP packet but we cannot unpack it, or the |
155
|
|
|
#: unpacked packet does not contain the dpid attribute, then |
156
|
|
|
#: we are dealing with a LLDP generated by someone else. Thus |
157
|
|
|
#: this packet is not useful for us and we may just ignore it. |
158
|
|
|
return |
159
|
|
|
|
160
|
1 |
|
switch_a = event.source.switch |
161
|
1 |
|
port_a = event.message.in_port |
162
|
1 |
|
switch_b = None |
163
|
1 |
|
port_b = None |
164
|
|
|
|
165
|
|
|
# in_port is currently a UBInt16 in v0x01 and an Int in v0x04. |
166
|
1 |
|
if isinstance(port_a, int): |
167
|
1 |
|
port_a = UBInt32(port_a) |
168
|
|
|
|
169
|
1 |
|
try: |
170
|
1 |
|
switch_b = self.controller.get_switch_by_dpid(dpid.value) |
171
|
1 |
|
of_version = switch_b.connection.protocol.version |
172
|
1 |
|
port_type = UBInt16 if of_version == 0x01 else UBInt32 |
173
|
1 |
|
port_b = self._unpack_non_empty(port_type, |
174
|
|
|
lldp.port_id.sub_value) |
175
|
|
|
except AttributeError: |
176
|
|
|
log.debug("Couldn't find datapath %s.", dpid.value) |
177
|
|
|
|
178
|
|
|
# Return if any of the needed information are not available |
179
|
1 |
|
if not (switch_a and port_a and switch_b and port_b): |
180
|
|
|
return |
181
|
|
|
|
182
|
1 |
|
interface_a = switch_a.get_interface_by_port_no(port_a.value) |
183
|
1 |
|
interface_b = switch_b.get_interface_by_port_no(port_b.value) |
184
|
|
|
|
185
|
1 |
|
event_out = KytosEvent(name='kytos/of_lldp.interface.is.nni', |
186
|
|
|
content={'interface_a': interface_a, |
187
|
|
|
'interface_b': interface_b}) |
188
|
1 |
|
self.controller.buffers.app.put(event_out) |
189
|
|
|
|
190
|
1 |
|
def notify_lldp_change(self, state, interface_ids): |
191
|
|
|
"""Dispatch a KytosEvent to notify changes to the LLDP status.""" |
192
|
1 |
|
content = {'attribute': 'LLDP', |
193
|
|
|
'state': state, |
194
|
|
|
'interface_ids': interface_ids} |
195
|
1 |
|
event_out = KytosEvent(name='kytos/of_lldp.network_status.updated', |
196
|
|
|
content=content) |
197
|
1 |
|
self.controller.buffers.app.put(event_out) |
198
|
|
|
|
199
|
1 |
|
def shutdown(self): |
200
|
|
|
"""End of the application.""" |
201
|
|
|
log.debug('Shutting down...') |
202
|
|
|
|
203
|
1 |
|
@staticmethod |
204
|
|
|
def _build_lldp_packet_out(version, port_number, data): |
205
|
|
|
"""Build a LLDP PacketOut message. |
206
|
|
|
|
207
|
|
|
Args: |
208
|
|
|
version (int): OpenFlow version |
209
|
|
|
port_number (int): Switch port number where the packet must be |
210
|
|
|
forwarded to. |
211
|
|
|
data (bytes): Binary data to be sent through the port. |
212
|
|
|
|
213
|
|
|
Returns: |
214
|
|
|
PacketOut message for the specific given OpenFlow version, if it |
215
|
|
|
is supported. |
216
|
|
|
None if the OpenFlow version is not supported. |
217
|
|
|
|
218
|
|
|
""" |
219
|
1 |
|
if version == 0x01: |
220
|
1 |
|
action_output_class = AO10 |
221
|
1 |
|
packet_out_class = PO10 |
222
|
1 |
|
elif version == 0x04: |
223
|
1 |
|
action_output_class = AO13 |
224
|
1 |
|
packet_out_class = PO13 |
225
|
|
|
else: |
226
|
1 |
|
log.info('Openflow version %s is not yet supported.', version) |
227
|
1 |
|
return None |
228
|
|
|
|
229
|
1 |
|
output_action = action_output_class() |
230
|
1 |
|
output_action.port = port_number |
231
|
|
|
|
232
|
1 |
|
packet_out = packet_out_class() |
233
|
1 |
|
packet_out.data = data |
234
|
1 |
|
packet_out.actions.append(output_action) |
235
|
|
|
|
236
|
1 |
|
return packet_out |
237
|
|
|
|
238
|
1 |
|
def _build_lldp_flow(self, version): |
239
|
|
|
"""Build a Flow message to send LLDP to the controller. |
240
|
|
|
|
241
|
|
|
Args: |
242
|
|
|
version (int): OpenFlow version. |
243
|
|
|
|
244
|
|
|
Returns: |
245
|
|
|
Flow dictionary message for the specific given OpenFlow version, |
246
|
|
|
if it is supported. |
247
|
|
|
None if the OpenFlow version is not supported. |
248
|
|
|
|
249
|
|
|
""" |
250
|
1 |
|
flow = {} |
251
|
1 |
|
match = {} |
252
|
1 |
|
flow['priority'] = settings.FLOW_PRIORITY |
253
|
1 |
|
flow['table_id'] = settings.TABLE_ID |
254
|
1 |
|
match['dl_type'] = EtherType.LLDP |
255
|
1 |
|
if self.vlan_id: |
256
|
1 |
|
match['dl_vlan'] = self.vlan_id |
257
|
1 |
|
flow['match'] = match |
258
|
|
|
|
259
|
1 |
|
if version == 0x01: |
260
|
1 |
|
flow['actions'] = [{'action_type': 'output', |
261
|
|
|
'port': Port10.OFPP_CONTROLLER}] |
262
|
1 |
|
elif version == 0x04: |
263
|
1 |
|
flow['actions'] = [{'action_type': 'output', |
264
|
|
|
'port': Port13.OFPP_CONTROLLER}] |
265
|
|
|
else: |
266
|
|
|
flow = None |
267
|
|
|
|
268
|
1 |
|
return flow |
269
|
|
|
|
270
|
1 |
|
@staticmethod |
271
|
|
|
def _unpack_non_empty(desired_class, data): |
272
|
|
|
"""Unpack data using an instance of desired_class. |
273
|
|
|
|
274
|
|
|
Args: |
275
|
|
|
desired_class (class): The class to be used to unpack data. |
276
|
|
|
data (bytes): bytes to be unpacked. |
277
|
|
|
|
278
|
|
|
Return: |
279
|
|
|
An instance of desired_class class with data unpacked into it. |
280
|
|
|
|
281
|
|
|
Raises: |
282
|
|
|
UnpackException if the unpack could not be performed. |
283
|
|
|
|
284
|
|
|
""" |
285
|
1 |
|
obj = desired_class() |
286
|
|
|
|
287
|
1 |
|
if hasattr(data, 'value'): |
288
|
1 |
|
data = data.value |
289
|
|
|
|
290
|
1 |
|
obj.unpack(data) |
291
|
|
|
|
292
|
1 |
|
return obj |
293
|
|
|
|
294
|
1 |
|
@staticmethod |
295
|
|
|
def _get_data(req): |
296
|
|
|
"""Get request data.""" |
297
|
1 |
|
data = req.get_json() # Valid format { "interfaces": [...] } |
298
|
1 |
|
return data.get('interfaces', []) |
299
|
|
|
|
300
|
1 |
|
def _get_interfaces(self): |
301
|
|
|
"""Get all interfaces.""" |
302
|
1 |
|
interfaces = [] |
303
|
1 |
|
for switch in list(self.controller.switches.values()): |
304
|
1 |
|
interfaces += list(switch.interfaces.values()) |
305
|
1 |
|
return interfaces |
306
|
|
|
|
307
|
1 |
|
@staticmethod |
308
|
|
|
def _get_interfaces_dict(interfaces): |
309
|
|
|
"""Return a dict of interfaces.""" |
310
|
1 |
|
return {inter.id: inter for inter in interfaces} |
311
|
|
|
|
312
|
1 |
|
def _get_lldp_interfaces(self): |
313
|
|
|
"""Get interfaces enabled to receive LLDP packets.""" |
314
|
1 |
|
return [inter.id for inter in self._get_interfaces() if inter.lldp] |
315
|
|
|
|
316
|
1 |
|
@rest('v1/interfaces', methods=['GET']) |
317
|
|
|
def get_lldp_interfaces(self): |
318
|
|
|
"""Return all the interfaces that have LLDP traffic enabled.""" |
319
|
1 |
|
return jsonify({"interfaces": self._get_lldp_interfaces()}), 200 |
320
|
|
|
|
321
|
1 |
View Code Duplication |
@rest('v1/interfaces/disable', methods=['POST']) |
|
|
|
|
322
|
|
|
def disable_lldp(self): |
323
|
|
|
"""Disables an interface to receive LLDP packets.""" |
324
|
1 |
|
interface_ids = self._get_data(request) |
325
|
1 |
|
error_list = [] # List of interfaces that were not activated. |
326
|
1 |
|
changed_interfaces = [] |
327
|
1 |
|
interface_ids = filter(None, interface_ids) |
328
|
1 |
|
interfaces = self._get_interfaces() |
329
|
1 |
|
if not interfaces: |
330
|
1 |
|
return jsonify("No interfaces were found."), 404 |
331
|
1 |
|
interfaces = self._get_interfaces_dict(interfaces) |
332
|
1 |
|
for id_ in interface_ids: |
333
|
1 |
|
interface = interfaces.get(id_) |
334
|
1 |
|
if interface: |
335
|
1 |
|
interface.lldp = False |
336
|
1 |
|
changed_interfaces.append(id_) |
337
|
|
|
else: |
338
|
1 |
|
error_list.append(id_) |
339
|
1 |
|
if changed_interfaces: |
340
|
1 |
|
self.notify_lldp_change('disabled', changed_interfaces) |
341
|
1 |
|
if not error_list: |
342
|
1 |
|
return jsonify( |
343
|
|
|
"All the requested interfaces have been disabled."), 200 |
344
|
|
|
|
345
|
|
|
# Return a list of interfaces that couldn't be disabled |
346
|
1 |
|
msg_error = "Some interfaces couldn't be found and deactivated: " |
347
|
1 |
|
return jsonify({msg_error: |
348
|
|
|
error_list}), 400 |
349
|
|
|
|
350
|
1 |
View Code Duplication |
@rest('v1/interfaces/enable', methods=['POST']) |
|
|
|
|
351
|
|
|
def enable_lldp(self): |
352
|
|
|
"""Enable an interface to receive LLDP packets.""" |
353
|
1 |
|
interface_ids = self._get_data(request) |
354
|
1 |
|
error_list = [] # List of interfaces that were not activated. |
355
|
1 |
|
changed_interfaces = [] |
356
|
1 |
|
interface_ids = filter(None, interface_ids) |
357
|
1 |
|
interfaces = self._get_interfaces() |
358
|
1 |
|
if not interfaces: |
359
|
1 |
|
return jsonify("No interfaces were found."), 404 |
360
|
1 |
|
interfaces = self._get_interfaces_dict(interfaces) |
361
|
1 |
|
for id_ in interface_ids: |
362
|
1 |
|
interface = interfaces.get(id_) |
363
|
1 |
|
if interface: |
364
|
1 |
|
interface.lldp = True |
365
|
1 |
|
changed_interfaces.append(id_) |
366
|
|
|
else: |
367
|
1 |
|
error_list.append(id_) |
368
|
1 |
|
if changed_interfaces: |
369
|
1 |
|
self.notify_lldp_change('enabled', changed_interfaces) |
370
|
1 |
|
if not error_list: |
371
|
1 |
|
return jsonify( |
372
|
|
|
"All the requested interfaces have been enabled."), 200 |
373
|
|
|
|
374
|
|
|
# Return a list of interfaces that couldn't be enabled |
375
|
1 |
|
msg_error = "Some interfaces couldn't be found and activated: " |
376
|
1 |
|
return jsonify({msg_error: |
377
|
|
|
error_list}), 400 |
378
|
|
|
|
379
|
1 |
|
@rest('v1/polling_time', methods=['GET']) |
380
|
|
|
def get_time(self): |
381
|
|
|
"""Get LLDP polling time in seconds.""" |
382
|
1 |
|
return jsonify({"polling_time": self.polling_time}), 200 |
383
|
|
|
|
384
|
1 |
|
@rest('v1/polling_time', methods=['POST']) |
385
|
|
|
def set_time(self): |
386
|
|
|
"""Set LLDP polling time.""" |
387
|
|
|
# pylint: disable=attribute-defined-outside-init |
388
|
1 |
|
try: |
389
|
1 |
|
payload = request.get_json() |
390
|
1 |
|
polling_time = int(payload['polling_time']) |
391
|
1 |
|
if polling_time <= 0: |
392
|
|
|
raise ValueError(f"invalid polling_time {polling_time}, " |
393
|
|
|
"must be greater than zero") |
394
|
1 |
|
self.polling_time = polling_time |
395
|
1 |
|
self.execute_as_loop(self.polling_time) |
396
|
1 |
|
log.info("Polling time has been updated to %s" |
397
|
|
|
" second(s), but this change will not be saved" |
398
|
|
|
" permanently.", self.polling_time) |
399
|
1 |
|
return jsonify("Polling time has been updated."), 200 |
400
|
1 |
|
except (ValueError, KeyError) as error: |
401
|
1 |
|
msg = f"This operation is not completed: {error}" |
402
|
|
|
return jsonify(msg), 400 |
403
|
|
|
|