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