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