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