Total Complexity | 67 |
Total Lines | 419 |
Duplicated Lines | 13.37 % |
Coverage | 92.24% |
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 | |||
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 = 'Switch: %s (%s)' |
|
94 | 1 | msg += ' Interface: %s' |
|
95 | 1 | msg += ' -- LLDP PacketOut --' |
|
96 | 1 | msg += ' Ethernet: eth_type (%s) | src (%s) | dst (%s) /' |
|
97 | 1 | msg += ' LLDP: Switch (%s) | portno (%s)' |
|
98 | |||
99 | 1 | log.debug( |
|
100 | msg, |
||
101 | switch.connection, switch.dpid, |
||
102 | interface.id, ethernet.ether_type, |
||
103 | ethernet.source, ethernet.destination, |
||
104 | switch.dpid, interface.port_number) |
||
105 | |||
106 | 1 | @listen_to('kytos/topology.switch.(enabled|disabled)') |
|
107 | def handle_lldp_flows(self, event): |
||
108 | """Install or remove flows in a switch. |
||
109 | |||
110 | Install a flow to send LLDP packets to the controller. The proactive |
||
111 | flow is installed whenever a switch is enabled. If the switch is |
||
112 | disabled the flow is removed. |
||
113 | |||
114 | Args: |
||
115 | event (:class:`~kytos.core.events.KytosEvent`): |
||
116 | Event with new switch information. |
||
117 | |||
118 | """ |
||
119 | 1 | try: |
|
120 | 1 | dpid = event.content['dpid'] |
|
121 | 1 | switch = self.controller.get_switch_by_dpid(dpid) |
|
122 | 1 | of_version = switch.connection.protocol.version |
|
123 | |||
124 | except AttributeError: |
||
125 | of_version = None |
||
126 | |||
127 | 1 | flow = self._build_lldp_flow(of_version) |
|
128 | 1 | if flow: |
|
129 | 1 | destination = switch.id |
|
130 | 1 | endpoint = f'{settings.FLOW_MANAGER_URL}/flows/{destination}' |
|
131 | 1 | data = {'flows': [flow]} |
|
132 | 1 | if event.name == 'kytos/topology.switch.enabled': |
|
133 | 1 | res = requests.post(endpoint, json=data) |
|
134 | if res.status_code != 202: |
||
135 | 1 | log.error(f"Failed to push flows on {destination}," |
|
136 | f" error: {res.text}, " f"status: {res.status_code}") |
||
137 | 1 | if res.status_code == 424: |
|
138 | data["force"] = True |
||
139 | res = requests.post(endpoint, json=data) |
||
140 | if res.status_code != 202: |
||
141 | return |
||
142 | log.info(f"Successfully force pushed flows to {destination}") |
||
143 | else: |
||
144 | res = requests.delete(endpoint, json=data) |
||
145 | if res.status_code != 202: |
||
146 | 1 | log.error(f"Failed to delete flows on {destination}," |
|
147 | 1 | f" error: {res.text}, " f"status: {res.status_code}") |
|
148 | 1 | if res.status_code == 424: |
|
149 | 1 | data["force"] = True |
|
150 | 1 | res = requests.post(endpoint, json=data) |
|
151 | if res.status_code != 202: |
||
152 | return |
||
153 | log.info(f"Successfully force deleted flows to {destination}") |
||
154 | |||
155 | @listen_to('kytos/of_core.v0x0[14].messages.in.ofpt_packet_in') |
||
156 | def notify_uplink_detected(self, event): |
||
157 | """Dispatch two KytosEvents to notify identified NNI interfaces. |
||
158 | 1 | ||
159 | 1 | Args: |
|
160 | 1 | event (:class:`~kytos.core.events.KytosEvent`): |
|
161 | 1 | Event with an LLDP packet as data. |
|
162 | |||
163 | """ |
||
164 | 1 | ethernet = self._unpack_non_empty(Ethernet, event.message.data) |
|
165 | 1 | if ethernet.ether_type == EtherType.LLDP: |
|
166 | try: |
||
167 | 1 | lldp = self._unpack_non_empty(LLDP, ethernet.data) |
|
168 | 1 | dpid = self._unpack_non_empty(DPID, lldp.chassis_id.sub_value) |
|
169 | 1 | except struct.error: |
|
170 | 1 | #: If we have a LLDP packet but we cannot unpack it, or the |
|
171 | 1 | #: unpacked packet does not contain the dpid attribute, then |
|
172 | #: we are dealing with a LLDP generated by someone else. Thus |
||
173 | #: this packet is not useful for us and we may just ignore it. |
||
174 | return |
||
175 | |||
176 | switch_a = event.source.switch |
||
177 | 1 | port_a = event.message.in_port |
|
178 | switch_b = None |
||
179 | port_b = None |
||
180 | 1 | ||
181 | 1 | # in_port is currently a UBInt16 in v0x01 and an Int in v0x04. |
|
182 | if isinstance(port_a, int): |
||
183 | 1 | port_a = UBInt32(port_a) |
|
184 | |||
185 | try: |
||
186 | 1 | switch_b = self.controller.get_switch_by_dpid(dpid.value) |
|
187 | of_version = switch_b.connection.protocol.version |
||
188 | 1 | port_type = UBInt16 if of_version == 0x01 else UBInt32 |
|
189 | port_b = self._unpack_non_empty(port_type, |
||
190 | 1 | lldp.port_id.sub_value) |
|
191 | except AttributeError: |
||
192 | log.debug("Couldn't find datapath %s.", dpid.value) |
||
193 | 1 | ||
194 | # Return if any of the needed information are not available |
||
195 | 1 | if not (switch_a and port_a and switch_b and port_b): |
|
196 | return |
||
197 | 1 | ||
198 | interface_a = switch_a.get_interface_by_port_no(port_a.value) |
||
199 | interface_b = switch_b.get_interface_by_port_no(port_b.value) |
||
200 | |||
201 | 1 | event_out = KytosEvent(name='kytos/of_lldp.interface.is.nni', |
|
202 | content={'interface_a': interface_a, |
||
203 | 'interface_b': interface_b}) |
||
204 | self.controller.buffers.app.put(event_out) |
||
205 | |||
206 | def notify_lldp_change(self, state, interface_ids): |
||
207 | """Dispatch a KytosEvent to notify changes to the LLDP status.""" |
||
208 | content = {'attribute': 'LLDP', |
||
209 | 'state': state, |
||
210 | 'interface_ids': interface_ids} |
||
211 | event_out = KytosEvent(name='kytos/of_lldp.network_status.updated', |
||
212 | content=content) |
||
213 | self.controller.buffers.app.put(event_out) |
||
214 | |||
215 | def shutdown(self): |
||
216 | """End of the application.""" |
||
217 | 1 | log.debug('Shutting down...') |
|
218 | 1 | ||
219 | 1 | @staticmethod |
|
220 | 1 | def _build_lldp_packet_out(version, port_number, data): |
|
221 | 1 | """Build a LLDP PacketOut message. |
|
222 | 1 | ||
223 | Args: |
||
224 | 1 | version (int): OpenFlow version |
|
225 | 1 | port_number (int): Switch port number where the packet must be |
|
226 | forwarded to. |
||
227 | 1 | data (bytes): Binary data to be sent through the port. |
|
228 | 1 | ||
229 | Returns: |
||
230 | 1 | PacketOut message for the specific given OpenFlow version, if it |
|
231 | 1 | is supported. |
|
232 | 1 | None if the OpenFlow version is not supported. |
|
233 | |||
234 | 1 | """ |
|
235 | if version == 0x01: |
||
236 | 1 | action_output_class = AO10 |
|
237 | packet_out_class = PO10 |
||
238 | elif version == 0x04: |
||
239 | action_output_class = AO13 |
||
240 | packet_out_class = PO13 |
||
241 | else: |
||
242 | log.info('Openflow version %s is not yet supported.', version) |
||
243 | return None |
||
244 | |||
245 | output_action = action_output_class() |
||
246 | output_action.port = port_number |
||
247 | |||
248 | 1 | packet_out = packet_out_class() |
|
249 | 1 | packet_out.data = data |
|
250 | 1 | packet_out.actions.append(output_action) |
|
251 | 1 | ||
252 | 1 | return packet_out |
|
253 | 1 | ||
254 | 1 | def _build_lldp_flow(self, version): |
|
255 | 1 | """Build a Flow message to send LLDP to the controller. |
|
256 | |||
257 | 1 | Args: |
|
258 | 1 | version (int): OpenFlow version. |
|
259 | |||
260 | 1 | Returns: |
|
261 | 1 | Flow dictionary message for the specific given OpenFlow version, |
|
262 | if it is supported. |
||
263 | None if the OpenFlow version is not supported. |
||
264 | |||
265 | """ |
||
266 | 1 | flow = {} |
|
267 | match = {} |
||
268 | 1 | flow['priority'] = settings.FLOW_PRIORITY |
|
269 | flow['table_id'] = settings.TABLE_ID |
||
270 | match['dl_type'] = EtherType.LLDP |
||
271 | if self.vlan_id: |
||
272 | match['dl_vlan'] = self.vlan_id |
||
273 | flow['match'] = match |
||
274 | |||
275 | if version == 0x01: |
||
276 | flow['actions'] = [{'action_type': 'output', |
||
277 | 'port': Port10.OFPP_CONTROLLER}] |
||
278 | elif version == 0x04: |
||
279 | flow['actions'] = [{'action_type': 'output', |
||
280 | 'port': Port13.OFPP_CONTROLLER}] |
||
281 | else: |
||
282 | flow = None |
||
283 | 1 | ||
284 | return flow |
||
285 | 1 | ||
286 | 1 | @staticmethod |
|
287 | def _unpack_non_empty(desired_class, data): |
||
288 | 1 | """Unpack data using an instance of desired_class. |
|
289 | |||
290 | 1 | Args: |
|
291 | desired_class (class): The class to be used to unpack data. |
||
292 | 1 | data (bytes): bytes to be unpacked. |
|
293 | |||
294 | Return: |
||
295 | 1 | An instance of desired_class class with data unpacked into it. |
|
296 | 1 | ||
297 | Raises: |
||
298 | 1 | UnpackException if the unpack could not be performed. |
|
299 | |||
300 | 1 | """ |
|
301 | 1 | obj = desired_class() |
|
302 | 1 | ||
303 | 1 | if hasattr(data, 'value'): |
|
304 | data = data.value |
||
305 | 1 | ||
306 | obj.unpack(data) |
||
307 | |||
308 | 1 | return obj |
|
309 | |||
310 | 1 | @staticmethod |
|
311 | def _get_data(req): |
||
312 | 1 | """Get request data.""" |
|
313 | data = req.get_json() # Valid format { "interfaces": [...] } |
||
314 | 1 | return data.get('interfaces', []) |
|
315 | |||
316 | def _get_interfaces(self): |
||
317 | 1 | """Get all interfaces.""" |
|
318 | interfaces = [] |
||
319 | 1 | for switch in list(self.controller.switches.values()): |
|
320 | interfaces += list(switch.interfaces.values()) |
||
321 | return interfaces |
||
322 | 1 | ||
323 | 1 | @staticmethod |
|
324 | 1 | def _get_interfaces_dict(interfaces): |
|
325 | 1 | """Return a dict of interfaces.""" |
|
326 | 1 | return {inter.id: inter for inter in interfaces} |
|
327 | 1 | ||
328 | 1 | def _get_lldp_interfaces(self): |
|
329 | 1 | """Get interfaces enabled to receive LLDP packets.""" |
|
330 | 1 | return [inter.id for inter in self._get_interfaces() if inter.lldp] |
|
331 | 1 | ||
332 | 1 | @rest('v1/interfaces', methods=['GET']) |
|
333 | 1 | def get_lldp_interfaces(self): |
|
334 | 1 | """Return all the interfaces that have LLDP traffic enabled.""" |
|
335 | return jsonify({"interfaces": self._get_lldp_interfaces()}), 200 |
||
336 | 1 | ||
337 | 1 | View Code Duplication | @rest('v1/interfaces/disable', methods=['POST']) |
|
|||
338 | 1 | def disable_lldp(self): |
|
339 | 1 | """Disables an interface to receive LLDP packets.""" |
|
340 | 1 | interface_ids = self._get_data(request) |
|
341 | error_list = [] # List of interfaces that were not activated. |
||
342 | changed_interfaces = [] |
||
343 | interface_ids = filter(None, interface_ids) |
||
344 | 1 | interfaces = self._get_interfaces() |
|
345 | 1 | if not interfaces: |
|
346 | return jsonify("No interfaces were found."), 404 |
||
347 | interfaces = self._get_interfaces_dict(interfaces) |
||
348 | 1 | for id_ in interface_ids: |
|
349 | interface = interfaces.get(id_) |
||
350 | if interface: |
||
351 | 1 | interface.lldp = False |
|
352 | 1 | changed_interfaces.append(id_) |
|
353 | 1 | else: |
|
354 | 1 | error_list.append(id_) |
|
355 | 1 | if changed_interfaces: |
|
356 | 1 | self.notify_lldp_change('disabled', changed_interfaces) |
|
357 | 1 | if not error_list: |
|
358 | 1 | return jsonify( |
|
359 | 1 | "All the requested interfaces have been disabled."), 200 |
|
360 | 1 | ||
361 | 1 | # Return a list of interfaces that couldn't be disabled |
|
362 | 1 | msg_error = "Some interfaces couldn't be found and deactivated: " |
|
363 | 1 | return jsonify({msg_error: |
|
364 | error_list}), 400 |
||
365 | 1 | ||
366 | 1 | View Code Duplication | @rest('v1/interfaces/enable', methods=['POST']) |
367 | 1 | def enable_lldp(self): |
|
368 | 1 | """Enable an interface to receive LLDP packets.""" |
|
369 | 1 | interface_ids = self._get_data(request) |
|
370 | error_list = [] # List of interfaces that were not activated. |
||
371 | changed_interfaces = [] |
||
372 | interface_ids = filter(None, interface_ids) |
||
373 | 1 | interfaces = self._get_interfaces() |
|
374 | 1 | if not interfaces: |
|
375 | return jsonify("No interfaces were found."), 404 |
||
376 | interfaces = self._get_interfaces_dict(interfaces) |
||
377 | 1 | for id_ in interface_ids: |
|
378 | interface = interfaces.get(id_) |
||
379 | if interface: |
||
380 | 1 | interface.lldp = True |
|
381 | changed_interfaces.append(id_) |
||
382 | 1 | else: |
|
383 | error_list.append(id_) |
||
384 | if changed_interfaces: |
||
385 | self.notify_lldp_change('enabled', changed_interfaces) |
||
386 | 1 | if not error_list: |
|
387 | 1 | return jsonify( |
|
388 | 1 | "All the requested interfaces have been enabled."), 200 |
|
389 | 1 | ||
390 | # Return a list of interfaces that couldn't be enabled |
||
391 | msg_error = "Some interfaces couldn't be found and activated: " |
||
392 | 1 | return jsonify({msg_error: |
|
393 | 1 | error_list}), 400 |
|
394 | 1 | ||
395 | @rest('v1/polling_time', methods=['GET']) |
||
396 | def get_time(self): |
||
397 | 1 | """Get LLDP polling time in seconds.""" |
|
398 | 1 | return jsonify({"polling_time": self.polling_time}), 200 |
|
399 | 1 | ||
400 | 1 | @rest('v1/polling_time', methods=['POST']) |
|
401 | def set_time(self): |
||
402 | """Set LLDP polling time.""" |
||
403 | # pylint: disable=attribute-defined-outside-init |
||
404 | try: |
||
405 | payload = request.get_json() |
||
406 | polling_time = int(payload['polling_time']) |
||
407 | if polling_time <= 0: |
||
408 | raise ValueError(f"invalid polling_time {polling_time}, " |
||
409 | "must be greater than zero") |
||
410 | self.polling_time = polling_time |
||
411 | self.execute_as_loop(self.polling_time) |
||
412 | log.info("Polling time has been updated to %s" |
||
413 | " second(s), but this change will not be saved" |
||
414 | " permanently.", self.polling_time) |
||
415 | return jsonify("Polling time has been updated."), 200 |
||
416 | except (ValueError, KeyError) as error: |
||
417 | msg = f"This operation is not completed: {error}" |
||
418 | return jsonify(msg), 400 |
||
419 |