| Total Complexity | 63 |
| Total Lines | 420 |
| Duplicated Lines | 14.76 % |
| 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 package |
||
| 59 | if not interface.lldp: |
||
| 60 | # print(f"Disabled LLDP package {interface.id}") |
||
| 61 | continue |
||
| 62 | # Avoid the interface that connects to the controller. |
||
| 63 | if interface.port_number == local_port: |
||
| 64 | continue |
||
| 65 | |||
| 66 | lldp = LLDP() |
||
| 67 | lldp.chassis_id.sub_value = DPID(switch.dpid) |
||
| 68 | lldp.port_id.sub_value = port_type(interface.port_number) |
||
| 69 | |||
| 70 | ethernet = Ethernet() |
||
| 71 | ethernet.ether_type = EtherType.LLDP |
||
| 72 | ethernet.source = interface.address |
||
| 73 | ethernet.destination = constants.LLDP_MULTICAST_MAC |
||
| 74 | ethernet.data = lldp.pack() |
||
| 75 | # self.vlan_id == None will result in a pack with no VLAN. |
||
| 76 | ethernet.vlans.append(VLAN(vid=self.vlan_id)) |
||
| 77 | |||
| 78 | packet_out = self._build_lldp_packet_out( |
||
| 79 | of_version, |
||
| 80 | interface.port_number, ethernet.pack()) |
||
| 81 | |||
| 82 | if packet_out is None: |
||
| 83 | continue |
||
| 84 | |||
| 85 | event_out = KytosEvent( |
||
| 86 | name='kytos/of_lldp.messages.out.ofpt_packet_out', |
||
| 87 | content={ |
||
| 88 | 'destination': switch.connection, |
||
| 89 | 'message': packet_out}) |
||
| 90 | self.controller.buffers.msg_out.put(event_out) |
||
| 91 | # print(f"Sending package to interface {interface.id}") |
||
| 92 | log.debug( |
||
| 93 | "Sending a LLDP PacketOut to the switch %s", |
||
| 94 | switch.dpid) |
||
| 95 | |||
| 96 | msg = '\n' |
||
| 97 | msg += 'Switch: %s (%s)\n' |
||
| 98 | msg += ' Interfaces: %s\n' |
||
| 99 | msg += ' -- LLDP PacketOut --\n' |
||
| 100 | msg += ' Ethernet: eth_type (%s) | src (%s) | dst (%s)' |
||
| 101 | msg += '\n' |
||
| 102 | msg += ' LLDP: Switch (%s) | port (%s)' |
||
| 103 | |||
| 104 | 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 | @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 | try: |
||
| 123 | of_version = event.content['switch'].connection.protocol.version |
||
| 124 | except AttributeError: |
||
| 125 | of_version = None |
||
| 126 | |||
| 127 | flow_mod = self._build_lldp_flow_mod(of_version) |
||
| 128 | |||
| 129 | if flow_mod: |
||
| 130 | name = 'kytos/of_lldp.messages.out.ofpt_flow_mod' |
||
| 131 | content = {'destination': event.content['switch'].connection, |
||
| 132 | 'message': flow_mod} |
||
| 133 | |||
| 134 | event_out = KytosEvent(name=name, content=content) |
||
| 135 | self.controller.buffers.msg_out.put(event_out) |
||
| 136 | |||
| 137 | @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 | ethernet = self._unpack_non_empty(Ethernet, event.message.data) |
||
| 147 | if ethernet.ether_type == EtherType.LLDP: |
||
| 148 | try: |
||
| 149 | lldp = self._unpack_non_empty(LLDP, ethernet.data) |
||
| 150 | 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 | switch_a = event.source.switch |
||
| 159 | port_a = event.message.in_port |
||
| 160 | switch_b = None |
||
| 161 | port_b = None |
||
| 162 | |||
| 163 | # in_port is currently a UBInt16 in v0x01 and an Int in v0x04. |
||
| 164 | if isinstance(port_a, int): |
||
| 165 | port_a = UBInt32(port_a) |
||
| 166 | |||
| 167 | try: |
||
| 168 | switch_b = self.controller.get_switch_by_dpid(dpid.value) |
||
| 169 | of_version = switch_b.connection.protocol.version |
||
| 170 | port_type = UBInt16 if of_version == 0x01 else UBInt32 |
||
| 171 | 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 | if not (switch_a and port_a and switch_b and port_b): |
||
| 178 | return |
||
| 179 | |||
| 180 | interface_a = switch_a.get_interface_by_port_no(port_a.value) |
||
| 181 | interface_b = switch_b.get_interface_by_port_no(port_b.value) |
||
| 182 | |||
| 183 | event_out = KytosEvent(name='kytos/of_lldp.interface.is.nni', |
||
| 184 | content={'interface_a': interface_a, |
||
| 185 | 'interface_b': interface_b}) |
||
| 186 | self.controller.buffers.app.put(event_out) |
||
| 187 | |||
| 188 | def shutdown(self): |
||
| 189 | """End of the application.""" |
||
| 190 | log.debug('Shutting down...') |
||
| 191 | |||
| 192 | @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 | if version == 0x01: |
||
| 209 | action_output_class = AO10 |
||
| 210 | packet_out_class = PO10 |
||
| 211 | elif version == 0x04: |
||
| 212 | action_output_class = AO13 |
||
| 213 | packet_out_class = PO13 |
||
| 214 | else: |
||
| 215 | log.info('Openflow version %s is not yet supported.', version) |
||
| 216 | return None |
||
| 217 | |||
| 218 | output_action = action_output_class() |
||
| 219 | output_action.port = port_number |
||
| 220 | |||
| 221 | packet_out = packet_out_class() |
||
| 222 | packet_out.data = data |
||
| 223 | packet_out.actions.append(output_action) |
||
| 224 | |||
| 225 | return packet_out |
||
| 226 | |||
| 227 | 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 | if version == 0x01: |
||
| 240 | flow_mod = FM10() |
||
| 241 | flow_mod.command = FMC.OFPFC_ADD |
||
| 242 | flow_mod.priority = settings.FLOW_PRIORITY |
||
| 243 | flow_mod.match.dl_type = EtherType.LLDP |
||
| 244 | if self.vlan_id: |
||
| 245 | flow_mod.match.dl_vlan = self.vlan_id |
||
| 246 | flow_mod.actions.append(AO10(port=Port10.OFPP_CONTROLLER)) |
||
| 247 | |||
| 248 | elif version == 0x04: |
||
| 249 | flow_mod = FM13() |
||
| 250 | flow_mod.command = FMC.OFPFC_ADD |
||
| 251 | flow_mod.priority = settings.FLOW_PRIORITY |
||
| 252 | |||
| 253 | match_lldp = OxmTLV() |
||
| 254 | match_lldp.oxm_field = OxmOfbMatchField.OFPXMT_OFB_ETH_TYPE |
||
| 255 | match_lldp.oxm_value = EtherType.LLDP.to_bytes(2, 'big') |
||
| 256 | flow_mod.match.oxm_match_fields.append(match_lldp) |
||
| 257 | |||
| 258 | if self.vlan_id: |
||
| 259 | match_vlan = OxmTLV() |
||
| 260 | match_vlan.oxm_field = OxmOfbMatchField.OFPXMT_OFB_VLAN_VID |
||
| 261 | vlan_value = self.vlan_id | VlanId.OFPVID_PRESENT |
||
| 262 | match_vlan.oxm_value = vlan_value.to_bytes(2, 'big') |
||
| 263 | flow_mod.match.oxm_match_fields.append(match_vlan) |
||
| 264 | |||
| 265 | instruction = InstructionApplyAction() |
||
| 266 | instruction.actions.append(AO13(port=Port13.OFPP_CONTROLLER)) |
||
| 267 | flow_mod.instructions.append(instruction) |
||
| 268 | |||
| 269 | else: |
||
| 270 | flow_mod = None |
||
| 271 | |||
| 272 | return flow_mod |
||
| 273 | |||
| 274 | @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 | obj = desired_class() |
||
| 290 | |||
| 291 | if hasattr(data, 'value'): |
||
| 292 | data = data.value |
||
| 293 | |||
| 294 | obj.unpack(data) |
||
| 295 | |||
| 296 | return obj |
||
| 297 | |||
| 298 | def _get_data(self, req): |
||
| 299 | """Get request data.""" |
||
| 300 | data = req.get_json() |
||
| 301 | interface_list = [] |
||
| 302 | if data: |
||
| 303 | interface_list = data.get('interfaces') |
||
| 304 | return interface_list |
||
| 305 | |||
| 306 | def _get_interfaces(self): |
||
| 307 | """Get all interfaces.""" |
||
| 308 | interfaces = [] |
||
| 309 | switches = list(self.controller.switches.values()) |
||
| 310 | for switch in switches: |
||
| 311 | interface_list = list(switch.interfaces.values()) |
||
| 312 | interfaces = interfaces + interface_list |
||
| 313 | return interfaces |
||
| 314 | |||
| 315 | @staticmethod |
||
| 316 | def _get_interfaces_dict(interfaces): |
||
| 317 | """Return a dict of interfaces.""" |
||
| 318 | interfaces_dic = {} |
||
| 319 | interfaces_dic = {interface.id: interface for interface in interfaces} |
||
| 320 | return interfaces_dic |
||
| 321 | |||
| 322 | def _get_lldp_interfaces(self): |
||
| 323 | """Get interfaces enabled to receive the LLDP package.""" |
||
| 324 | enabled_lldp = [] |
||
| 325 | interfaces = self._get_interfaces() |
||
| 326 | enabled_lldp = [inter.id for inter in interfaces if inter.lldp] |
||
| 327 | return enabled_lldp |
||
| 328 | |||
| 329 | @rest('v1/interfaces', methods=['GET']) |
||
| 330 | def get_lldp_interfaces(self): |
||
| 331 | """Return of the interfaces available to receive the LLDP package.""" |
||
| 332 | result = {"interfaces": self._get_lldp_interfaces()} |
||
| 333 | return jsonify(result), 200 |
||
| 334 | |||
| 335 | View Code Duplication | @rest('v1/interfaces/disable', methods=['POST']) |
|
|
|
|||
| 336 | def disable_lldp(self): |
||
| 337 | """Disables an interface to receive an LLDP package.""" |
||
| 338 | interfaces_id = self._get_data(request) |
||
| 339 | error_list = [] |
||
| 340 | if interfaces_id is None: |
||
| 341 | return jsonify("Bad format."), 401 |
||
| 342 | interfaces = self._get_interfaces() |
||
| 343 | |||
| 344 | if not interfaces: |
||
| 345 | return jsonify("No interfaces were found"), 404 |
||
| 346 | |||
| 347 | interfaces = self._get_interfaces_dict(interfaces) |
||
| 348 | for interface_id in interfaces_id: |
||
| 349 | if not interface_id: |
||
| 350 | continue |
||
| 351 | if interfaces.get(interface_id): |
||
| 352 | interface = interfaces[interface_id] |
||
| 353 | interface.lldp = False |
||
| 354 | else: |
||
| 355 | # List of interfaces that were not activated. |
||
| 356 | error_list.append(interface_id) |
||
| 357 | if not error_list: |
||
| 358 | return jsonify("All interface passed has been disabled."), 200 |
||
| 359 | |||
| 360 | # Return a list of interfaces has not disabled. |
||
| 361 | # Other interfaces passed has enabled. |
||
| 362 | msg_partial_enabled = "" |
||
| 363 | msg_partial_enabled += "Some interfaces have not been disabled. " |
||
| 364 | msg_partial_enabled += "Interface list not disabled:" |
||
| 365 | return jsonify({msg_partial_enabled: |
||
| 366 | error_list}), 400 |
||
| 367 | |||
| 368 | View Code Duplication | @rest('v1/interfaces/enable', methods=['POST']) |
|
| 369 | def enable_lldp(self): |
||
| 370 | """Enable an interface to receive an LLDP package.""" |
||
| 371 | interfaces_id = self._get_data(request) |
||
| 372 | error_list = [] |
||
| 373 | if interfaces_id is None: |
||
| 374 | return jsonify("Bad format."), 401 |
||
| 375 | interfaces = self._get_interfaces() |
||
| 376 | if not interfaces: |
||
| 377 | return jsonify("No interfaces were found"), 404 |
||
| 378 | interfaces = self._get_interfaces_dict(interfaces) |
||
| 379 | for interface_id in interfaces_id: |
||
| 380 | if not interface_id: |
||
| 381 | continue |
||
| 382 | if interfaces.get(interface_id): |
||
| 383 | interface = interfaces[interface_id] |
||
| 384 | interface.lldp = True |
||
| 385 | else: |
||
| 386 | # List of interfaces that were not activated. |
||
| 387 | error_list.append(interface_id) |
||
| 388 | if not error_list: |
||
| 389 | return jsonify("All interface passed has been enabled."), 200 |
||
| 390 | |||
| 391 | # Return a list of interfaces has not enabled. |
||
| 392 | # The other interfaces have been activated. |
||
| 393 | msg_partial_enabled = "" |
||
| 394 | msg_partial_enabled += "Some interfaces have not been enabled. " |
||
| 395 | msg_partial_enabled += "Interface list not enabled:" |
||
| 396 | return jsonify({msg_partial_enabled: |
||
| 397 | error_list}), 400 |
||
| 398 | |||
| 399 | @rest('v1/interfaces/disable/all', methods=['POST']) |
||
| 400 | def disable_lldp_all(self): |
||
| 401 | """Disable LLDP on all interfaces.""" |
||
| 402 | interfaces = self._get_interfaces() |
||
| 403 | if not interfaces: |
||
| 404 | return jsonify("No interfaces were found"), 404 |
||
| 405 | for interface in interfaces: |
||
| 406 | interface.lldp = False |
||
| 407 | |||
| 408 | return jsonify("All interfaces has been disabled"), 200 |
||
| 409 | |||
| 410 | @rest('v1/interfaces/enable/all', methods=['POST']) |
||
| 411 | def enable_all_lldp(self): |
||
| 412 | """Enable LLLDP on all interfaces.""" |
||
| 413 | interfaces = self._get_interfaces() |
||
| 414 | if not interfaces: |
||
| 415 | return jsonify("No interfaces were found."), 404 |
||
| 416 | for interface in interfaces: |
||
| 417 | interface.lldp = True |
||
| 418 | |||
| 419 | return jsonify("All interfaces has been enabled."), 200 |
||
| 420 |