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