Total Complexity | 53 |
Total Lines | 372 |
Duplicated Lines | 12.9 % |
Coverage | 0% |
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 | import struct |
||
3 | |||
4 | from flask import jsonify, request |
||
5 | from pyof.foundation.basic_types import DPID, UBInt16, UBInt32 |
||
6 | from pyof.foundation.network_types import LLDP, VLAN, Ethernet, EtherType |
||
7 | from pyof.v0x01.common.action import ActionOutput as AO10 |
||
8 | from pyof.v0x01.common.phy_port import Port as Port10 |
||
9 | from pyof.v0x01.controller2switch.flow_mod import FlowMod as FM10 |
||
10 | from pyof.v0x01.controller2switch.flow_mod import FlowModCommand as FMC |
||
11 | from pyof.v0x01.controller2switch.packet_out import PacketOut as PO10 |
||
12 | from pyof.v0x04.common.action import ActionOutput as AO13 |
||
13 | from pyof.v0x04.common.flow_instructions import InstructionApplyAction |
||
14 | from pyof.v0x04.common.flow_match import OxmOfbMatchField, OxmTLV, VlanId |
||
15 | from pyof.v0x04.common.port import PortNo as Port13 |
||
16 | from pyof.v0x04.controller2switch.flow_mod import FlowMod as FM13 |
||
17 | from pyof.v0x04.controller2switch.packet_out import PacketOut as PO13 |
||
18 | |||
19 | from kytos.core import KytosEvent, KytosNApp, log, rest |
||
20 | from kytos.core.helpers import listen_to |
||
21 | from napps.kytos.of_lldp import constants, settings |
||
22 | |||
23 | |||
24 | class Main(KytosNApp): |
||
25 | """Main OF_LLDP NApp Class.""" |
||
26 | |||
27 | def setup(self): |
||
28 | """Make this NApp run in a loop.""" |
||
29 | self.vlan_id = None |
||
30 | if hasattr(settings, "FLOW_VLAN_VID"): |
||
31 | self.vlan_id = settings.FLOW_VLAN_VID |
||
32 | self.execute_as_loop(settings.POLLING_TIME) |
||
33 | |||
34 | def execute(self): |
||
35 | """Send LLDP Packets every 'POLLING_TIME' seconds to all switches.""" |
||
36 | switches = list(self.controller.switches.values()) |
||
37 | for switch in switches: |
||
38 | try: |
||
39 | of_version = switch.connection.protocol.version |
||
40 | except AttributeError: |
||
41 | of_version = None |
||
42 | |||
43 | if not switch.is_connected(): |
||
44 | continue |
||
45 | |||
46 | if of_version == 0x01: |
||
47 | port_type = UBInt16 |
||
48 | local_port = Port10.OFPP_LOCAL |
||
49 | elif of_version == 0x04: |
||
50 | port_type = UBInt32 |
||
51 | local_port = Port13.OFPP_LOCAL |
||
52 | else: |
||
53 | # skip the current switch with unsupported OF version |
||
54 | continue |
||
55 | |||
56 | interfaces = list(switch.interfaces.values()) |
||
57 | for interface in interfaces: |
||
58 | # Interface marked to receive lldp packet |
||
59 | if not interface.lldp or not interface.is_active(): |
||
60 | continue |
||
61 | # Avoid the interface that connects to the controller. |
||
62 | if interface.port_number == local_port: |
||
63 | continue |
||
64 | |||
65 | lldp = LLDP() |
||
66 | lldp.chassis_id.sub_value = DPID(switch.dpid) |
||
67 | lldp.port_id.sub_value = port_type(interface.port_number) |
||
68 | |||
69 | ethernet = Ethernet() |
||
70 | ethernet.ether_type = EtherType.LLDP |
||
71 | ethernet.source = interface.address |
||
72 | ethernet.destination = constants.LLDP_MULTICAST_MAC |
||
73 | ethernet.data = lldp.pack() |
||
74 | # self.vlan_id == None will result in a packet with no VLAN. |
||
75 | ethernet.vlans.append(VLAN(vid=self.vlan_id)) |
||
76 | |||
77 | packet_out = self._build_lldp_packet_out( |
||
78 | of_version, |
||
79 | interface.port_number, ethernet.pack()) |
||
80 | |||
81 | if packet_out is None: |
||
82 | continue |
||
83 | |||
84 | event_out = KytosEvent( |
||
85 | name='kytos/of_lldp.messages.out.ofpt_packet_out', |
||
86 | content={ |
||
87 | 'destination': switch.connection, |
||
88 | 'message': packet_out}) |
||
89 | self.controller.buffers.msg_out.put(event_out) |
||
90 | log.debug( |
||
91 | "Sending a LLDP PacketOut to the switch %s", |
||
92 | switch.dpid) |
||
93 | |||
94 | msg = '\n' |
||
95 | msg += 'Switch: %s (%s)\n' |
||
96 | msg += ' Interfaces: %s\n' |
||
97 | msg += ' -- LLDP PacketOut --\n' |
||
98 | msg += ' Ethernet: eth_type (%s) | src (%s) | dst (%s)' |
||
99 | msg += '\n' |
||
100 | msg += ' LLDP: Switch (%s) | port (%s)' |
||
101 | |||
102 | 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 | @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 | try: |
||
121 | of_version = event.content['switch'].connection.protocol.version |
||
122 | except AttributeError: |
||
123 | of_version = None |
||
124 | |||
125 | flow_mod = self._build_lldp_flow_mod(of_version) |
||
126 | |||
127 | if flow_mod: |
||
128 | name = 'kytos/of_lldp.messages.out.ofpt_flow_mod' |
||
129 | content = {'destination': event.content['switch'].connection, |
||
130 | 'message': flow_mod} |
||
131 | |||
132 | event_out = KytosEvent(name=name, content=content) |
||
133 | self.controller.buffers.msg_out.put(event_out) |
||
134 | |||
135 | @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 | ethernet = self._unpack_non_empty(Ethernet, event.message.data) |
||
145 | if ethernet.ether_type == EtherType.LLDP: |
||
146 | try: |
||
147 | lldp = self._unpack_non_empty(LLDP, ethernet.data) |
||
148 | 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 | switch_a = event.source.switch |
||
157 | port_a = event.message.in_port |
||
158 | switch_b = None |
||
159 | port_b = None |
||
160 | |||
161 | # in_port is currently a UBInt16 in v0x01 and an Int in v0x04. |
||
162 | if isinstance(port_a, int): |
||
163 | port_a = UBInt32(port_a) |
||
164 | |||
165 | try: |
||
166 | switch_b = self.controller.get_switch_by_dpid(dpid.value) |
||
167 | of_version = switch_b.connection.protocol.version |
||
168 | port_type = UBInt16 if of_version == 0x01 else UBInt32 |
||
169 | 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 | if not (switch_a and port_a and switch_b and port_b): |
||
176 | return |
||
177 | |||
178 | interface_a = switch_a.get_interface_by_port_no(port_a.value) |
||
179 | interface_b = switch_b.get_interface_by_port_no(port_b.value) |
||
180 | |||
181 | event_out = KytosEvent(name='kytos/of_lldp.interface.is.nni', |
||
182 | content={'interface_a': interface_a, |
||
183 | 'interface_b': interface_b}) |
||
184 | self.controller.buffers.app.put(event_out) |
||
185 | |||
186 | def shutdown(self): |
||
187 | """End of the application.""" |
||
188 | log.debug('Shutting down...') |
||
189 | |||
190 | @staticmethod |
||
191 | def _build_lldp_packet_out(version, port_number, data): |
||
192 | """Build a LLDP PacketOut message. |
||
193 | |||
194 | Args: |
||
195 | version (int): OpenFlow version |
||
196 | port_number (int): Switch port number where the packet must be |
||
197 | forwarded to. |
||
198 | data (bytes): Binary data to be sent through the port. |
||
199 | |||
200 | Returns: |
||
201 | PacketOut message for the specific given OpenFlow version, if it |
||
202 | is supported. |
||
203 | None if the OpenFlow version is not supported. |
||
204 | |||
205 | """ |
||
206 | if version == 0x01: |
||
207 | action_output_class = AO10 |
||
208 | packet_out_class = PO10 |
||
209 | elif version == 0x04: |
||
210 | action_output_class = AO13 |
||
211 | packet_out_class = PO13 |
||
212 | else: |
||
213 | log.info('Openflow version %s is not yet supported.', version) |
||
214 | return None |
||
215 | |||
216 | output_action = action_output_class() |
||
217 | output_action.port = port_number |
||
218 | |||
219 | packet_out = packet_out_class() |
||
220 | packet_out.data = data |
||
221 | packet_out.actions.append(output_action) |
||
222 | |||
223 | return packet_out |
||
224 | |||
225 | def _build_lldp_flow_mod(self, version): |
||
226 | """Build a FlodMod message to send LLDP to the controller. |
||
227 | |||
228 | Args: |
||
229 | version (int): OpenFlow version. |
||
230 | |||
231 | Returns: |
||
232 | FlowMod message for the specific given OpenFlow version, if it is |
||
233 | supported. |
||
234 | None if the OpenFlow version is not supported. |
||
235 | |||
236 | """ |
||
237 | if version == 0x01: |
||
238 | flow_mod = FM10() |
||
239 | flow_mod.command = FMC.OFPFC_ADD |
||
240 | flow_mod.priority = settings.FLOW_PRIORITY |
||
241 | flow_mod.match.dl_type = EtherType.LLDP |
||
242 | if self.vlan_id: |
||
243 | flow_mod.match.dl_vlan = self.vlan_id |
||
244 | flow_mod.actions.append(AO10(port=Port10.OFPP_CONTROLLER)) |
||
245 | |||
246 | elif version == 0x04: |
||
247 | flow_mod = FM13() |
||
248 | flow_mod.command = FMC.OFPFC_ADD |
||
249 | flow_mod.priority = settings.FLOW_PRIORITY |
||
250 | |||
251 | match_lldp = OxmTLV() |
||
252 | match_lldp.oxm_field = OxmOfbMatchField.OFPXMT_OFB_ETH_TYPE |
||
253 | match_lldp.oxm_value = EtherType.LLDP.to_bytes(2, 'big') |
||
254 | flow_mod.match.oxm_match_fields.append(match_lldp) |
||
255 | |||
256 | if self.vlan_id: |
||
257 | match_vlan = OxmTLV() |
||
258 | match_vlan.oxm_field = OxmOfbMatchField.OFPXMT_OFB_VLAN_VID |
||
259 | vlan_value = self.vlan_id | VlanId.OFPVID_PRESENT |
||
260 | match_vlan.oxm_value = vlan_value.to_bytes(2, 'big') |
||
261 | flow_mod.match.oxm_match_fields.append(match_vlan) |
||
262 | |||
263 | instruction = InstructionApplyAction() |
||
264 | instruction.actions.append(AO13(port=Port13.OFPP_CONTROLLER)) |
||
265 | flow_mod.instructions.append(instruction) |
||
266 | |||
267 | else: |
||
268 | flow_mod = None |
||
269 | |||
270 | return flow_mod |
||
271 | |||
272 | @staticmethod |
||
273 | def _unpack_non_empty(desired_class, data): |
||
274 | """Unpack data using an instance of desired_class. |
||
275 | |||
276 | Args: |
||
277 | desired_class (class): The class to be used to unpack data. |
||
278 | data (bytes): bytes to be unpacked. |
||
279 | |||
280 | Return: |
||
281 | An instance of desired_class class with data unpacked into it. |
||
282 | |||
283 | Raises: |
||
284 | UnpackException if the unpack could not be performed. |
||
285 | |||
286 | """ |
||
287 | obj = desired_class() |
||
288 | |||
289 | if hasattr(data, 'value'): |
||
290 | data = data.value |
||
291 | |||
292 | obj.unpack(data) |
||
293 | |||
294 | return obj |
||
295 | |||
296 | @staticmethod |
||
297 | def _get_data(req): |
||
298 | """Get request data.""" |
||
299 | data = req.get_json() # Valid format { "interfaces": [...] } |
||
300 | return data.get('interfaces', []) |
||
301 | |||
302 | def _get_interfaces(self): |
||
303 | """Get all interfaces.""" |
||
304 | interfaces = [] |
||
305 | for switch in list(self.controller.switches.values()): |
||
306 | interfaces += list(switch.interfaces.values()) |
||
307 | return interfaces |
||
308 | |||
309 | @staticmethod |
||
310 | def _get_interfaces_dict(interfaces): |
||
311 | """Return a dict of interfaces.""" |
||
312 | return {inter.id: inter for inter in interfaces} |
||
313 | |||
314 | def _get_lldp_interfaces(self): |
||
315 | """Get interfaces enabled to receive LLDP packets.""" |
||
316 | return [inter.id for inter in self._get_interfaces() if inter.lldp] |
||
317 | |||
318 | @rest('v1/interfaces', methods=['GET']) |
||
319 | def get_lldp_interfaces(self): |
||
320 | """Return all the interfaces that have LLDP traffic enabled.""" |
||
321 | return jsonify({"interfaces": self._get_lldp_interfaces()}), 200 |
||
322 | |||
323 | View Code Duplication | @rest('v1/interfaces/disable', methods=['POST']) |
|
|
|||
324 | def disable_lldp(self): |
||
325 | """Disables an interface to receive LLDP packets.""" |
||
326 | interface_ids = self._get_data(request) |
||
327 | error_list = [] # List of interfaces that were not activated. |
||
328 | interface_ids = filter(None, interface_ids) |
||
329 | interfaces = self._get_interfaces() |
||
330 | if not interfaces: |
||
331 | return jsonify("No interfaces were found."), 404 |
||
332 | interfaces = self._get_interfaces_dict(interfaces) |
||
333 | for id_ in interface_ids: |
||
334 | interface = interfaces.get(id_) |
||
335 | if interface: |
||
336 | interface.lldp = False |
||
337 | else: |
||
338 | error_list.append(id_) |
||
339 | if not error_list: |
||
340 | return jsonify( |
||
341 | "All the requested interfaces have been disabled."), 200 |
||
342 | |||
343 | # Return a list of interfaces that couldn't be disabled |
||
344 | msg_error = "Some interfaces couldn't be found and deactivated: " |
||
345 | return jsonify({msg_error: |
||
346 | error_list}), 400 |
||
347 | |||
348 | View Code Duplication | @rest('v1/interfaces/enable', methods=['POST']) |
|
349 | def enable_lldp(self): |
||
350 | """Enable an interface to receive LLDP packets.""" |
||
351 | interface_ids = self._get_data(request) |
||
352 | error_list = [] # List of interfaces that were not activated. |
||
353 | interface_ids = filter(None, interface_ids) |
||
354 | interfaces = self._get_interfaces() |
||
355 | if not interfaces: |
||
356 | return jsonify("No interfaces were found."), 404 |
||
357 | interfaces = self._get_interfaces_dict(interfaces) |
||
358 | for id_ in interface_ids: |
||
359 | interface = interfaces.get(id_) |
||
360 | if interface: |
||
361 | interface.lldp = True |
||
362 | else: |
||
363 | error_list.append(id_) |
||
364 | if not error_list: |
||
365 | return jsonify( |
||
366 | "All the requested interfaces have been enabled."), 200 |
||
367 | |||
368 | # Return a list of interfaces that couldn't be enabled |
||
369 | msg_error = "Some interfaces couldn't be found and activated: " |
||
370 | return jsonify({msg_error: |
||
371 | error_list}), 400 |
||
372 |