Passed
Pull Request — master (#53)
by Gleyberson
02:33
created

build.main.Main.notify_uplink_detected()   D

Complexity

Conditions 12

Size

Total Lines 54
Code Lines 33

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 23
CRAP Score 13.2753

Importance

Changes 0
Metric Value
cc 12
eloc 33
nop 2
dl 0
loc 54
ccs 23
cts 29
cp 0.7931
crap 13.2753
rs 4.8
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

Complexity

Complex classes like build.main.Main.notify_uplink_detected() 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
            # Return if any interface does not exist
185 1
            if not (interface_a and interface_b):
186
                return
187
188 1
            event_out = KytosEvent(name='kytos/of_lldp.interface.is.nni',
189
                                   content={'interface_a': interface_a,
190
                                            'interface_b': interface_b})
191 1
            self.controller.buffers.app.put(event_out)
192
193 1
    def notify_lldp_change(self, state, interface_ids):
194
        """Dispatch a KytosEvent to notify changes to the LLDP status."""
195 1
        content = {'attribute': 'LLDP',
196
                   'state': state,
197
                   'interface_ids': interface_ids}
198 1
        event_out = KytosEvent(name='kytos/of_lldp.network_status.updated',
199
                               content=content)
200 1
        self.controller.buffers.app.put(event_out)
201
202 1
    def shutdown(self):
203
        """End of the application."""
204
        log.debug('Shutting down...')
205
206 1
    @staticmethod
207
    def _build_lldp_packet_out(version, port_number, data):
208
        """Build a LLDP PacketOut message.
209
210
        Args:
211
            version (int): OpenFlow version
212
            port_number (int): Switch port number where the packet must be
213
                forwarded to.
214
            data (bytes): Binary data to be sent through the port.
215
216
        Returns:
217
            PacketOut message for the specific given OpenFlow version, if it
218
                is supported.
219
            None if the OpenFlow version is not supported.
220
221
        """
222 1
        if version == 0x01:
223 1
            action_output_class = AO10
224 1
            packet_out_class = PO10
225 1
        elif version == 0x04:
226 1
            action_output_class = AO13
227 1
            packet_out_class = PO13
228
        else:
229 1
            log.info('Openflow version %s is not yet supported.', version)
230 1
            return None
231
232 1
        output_action = action_output_class()
233 1
        output_action.port = port_number
234
235 1
        packet_out = packet_out_class()
236 1
        packet_out.data = data
237 1
        packet_out.actions.append(output_action)
238
239 1
        return packet_out
240
241 1
    def _build_lldp_flow_mod(self, version):
242
        """Build a FlodMod message to send LLDP to the controller.
243
244
        Args:
245
            version (int): OpenFlow version.
246
247
        Returns:
248
            FlowMod message for the specific given OpenFlow version, if it is
249
                supported.
250
            None if the OpenFlow version is not supported.
251
252
        """
253 1
        if version == 0x01:
254 1
            flow_mod = FM10()
255 1
            flow_mod.command = FMC.OFPFC_ADD
256 1
            flow_mod.priority = settings.FLOW_PRIORITY
257 1
            flow_mod.match.dl_type = EtherType.LLDP
258 1
            if self.vlan_id:
259 1
                flow_mod.match.dl_vlan = self.vlan_id
260 1
            flow_mod.actions.append(AO10(port=Port10.OFPP_CONTROLLER))
261
262 1
        elif version == 0x04:
263 1
            flow_mod = FM13()
264 1
            flow_mod.command = FMC.OFPFC_ADD
265 1
            flow_mod.priority = settings.FLOW_PRIORITY
266
267 1
            match_lldp = OxmTLV()
268 1
            match_lldp.oxm_field = OxmOfbMatchField.OFPXMT_OFB_ETH_TYPE
269 1
            match_lldp.oxm_value = EtherType.LLDP.to_bytes(2, 'big')
270 1
            flow_mod.match.oxm_match_fields.append(match_lldp)
271
272 1
            if self.vlan_id:
273 1
                match_vlan = OxmTLV()
274 1
                match_vlan.oxm_field = OxmOfbMatchField.OFPXMT_OFB_VLAN_VID
275 1
                vlan_value = self.vlan_id | VlanId.OFPVID_PRESENT
276 1
                match_vlan.oxm_value = vlan_value.to_bytes(2, 'big')
277 1
                flow_mod.match.oxm_match_fields.append(match_vlan)
278
279 1
            instruction = InstructionApplyAction()
280 1
            instruction.actions.append(AO13(port=Port13.OFPP_CONTROLLER))
281 1
            flow_mod.instructions.append(instruction)
282
283
        else:
284 1
            flow_mod = None
285
286 1
        return flow_mod
287
288 1
    @staticmethod
289
    def _unpack_non_empty(desired_class, data):
290
        """Unpack data using an instance of desired_class.
291
292
        Args:
293
            desired_class (class): The class to be used to unpack data.
294
            data (bytes): bytes to be unpacked.
295
296
        Return:
297
            An instance of desired_class class with data unpacked into it.
298
299
        Raises:
300
            UnpackException if the unpack could not be performed.
301
302
        """
303 1
        obj = desired_class()
304
305 1
        if hasattr(data, 'value'):
306 1
            data = data.value
307
308 1
        obj.unpack(data)
309
310 1
        return obj
311
312 1
    @staticmethod
313
    def _get_data(req):
314
        """Get request data."""
315 1
        data = req.get_json()  # Valid format { "interfaces": [...] }
316 1
        return data.get('interfaces', [])
317
318 1
    def _get_interfaces(self):
319
        """Get all interfaces."""
320 1
        interfaces = []
321 1
        for switch in list(self.controller.switches.values()):
322 1
            interfaces += list(switch.interfaces.values())
323 1
        return interfaces
324
325 1
    @staticmethod
326
    def _get_interfaces_dict(interfaces):
327
        """Return a dict of interfaces."""
328 1
        return {inter.id: inter for inter in interfaces}
329
330 1
    def _get_lldp_interfaces(self):
331
        """Get interfaces enabled to receive LLDP packets."""
332 1
        return [inter.id for inter in self._get_interfaces() if inter.lldp]
333
334 1
    @rest('v1/interfaces', methods=['GET'])
335
    def get_lldp_interfaces(self):
336
        """Return all the interfaces that have LLDP traffic enabled."""
337 1
        return jsonify({"interfaces": self._get_lldp_interfaces()}), 200
338
339 1 View Code Duplication
    @rest('v1/interfaces/disable', methods=['POST'])
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
340
    def disable_lldp(self):
341
        """Disables an interface to receive LLDP packets."""
342 1
        interface_ids = self._get_data(request)
343 1
        error_list = []  # List of interfaces that were not activated.
344 1
        changed_interfaces = []
345 1
        interface_ids = filter(None, interface_ids)
346 1
        interfaces = self._get_interfaces()
347 1
        if not interfaces:
348 1
            return jsonify("No interfaces were found."), 404
349 1
        interfaces = self._get_interfaces_dict(interfaces)
350 1
        for id_ in interface_ids:
351 1
            interface = interfaces.get(id_)
352 1
            if interface:
353 1
                interface.lldp = False
354 1
                changed_interfaces.append(id_)
355
            else:
356 1
                error_list.append(id_)
357 1
        if changed_interfaces:
358 1
            self.notify_lldp_change('disabled', changed_interfaces)
359 1
        if not error_list:
360 1
            return jsonify(
361
                "All the requested interfaces have been disabled."), 200
362
363
        # Return a list of interfaces that couldn't be disabled
364 1
        msg_error = "Some interfaces couldn't be found and deactivated: "
365 1
        return jsonify({msg_error:
366
                        error_list}), 400
367
368 1 View Code Duplication
    @rest('v1/interfaces/enable', methods=['POST'])
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
369
    def enable_lldp(self):
370
        """Enable an interface to receive LLDP packets."""
371 1
        interface_ids = self._get_data(request)
372 1
        error_list = []  # List of interfaces that were not activated.
373 1
        changed_interfaces = []
374 1
        interface_ids = filter(None, interface_ids)
375 1
        interfaces = self._get_interfaces()
376 1
        if not interfaces:
377 1
            return jsonify("No interfaces were found."), 404
378 1
        interfaces = self._get_interfaces_dict(interfaces)
379 1
        for id_ in interface_ids:
380 1
            interface = interfaces.get(id_)
381 1
            if interface:
382 1
                interface.lldp = True
383 1
                changed_interfaces.append(id_)
384
            else:
385 1
                error_list.append(id_)
386 1
        if changed_interfaces:
387 1
            self.notify_lldp_change('enabled', changed_interfaces)
388 1
        if not error_list:
389 1
            return jsonify(
390
                "All the requested interfaces have been enabled."), 200
391
392
        # Return a list of interfaces that couldn't be enabled
393 1
        msg_error = "Some interfaces couldn't be found and activated: "
394 1
        return jsonify({msg_error:
395
                        error_list}), 400
396
397 1
    @rest('v1/polling_time', methods=['GET'])
398
    def get_time(self):
399
        """Get LLDP polling time in seconds."""
400 1
        return jsonify({"polling_time": self.polling_time}), 200
401
402 1
    @rest('v1/polling_time', methods=['POST'])
403
    def set_time(self):
404
        """Set LLDP polling time."""
405
        # pylint: disable=attribute-defined-outside-init
406 1
        try:
407 1
            payload = request.get_json()
408 1
            polling_time = int(payload['polling_time'])
409 1
            if polling_time <= 0:
410
                raise ValueError(f"invalid polling_time {polling_time}, "
411
                                 "must be greater than zero")
412 1
            self.polling_time = polling_time
413 1
            self.execute_as_loop(self.polling_time)
414 1
            log.info("Polling time has been updated to %s"
415
                     " second(s), but this change will not be saved"
416
                     " permanently.", self.polling_time)
417 1
            return jsonify("Polling time has been updated."), 200
418 1
        except (ValueError, KeyError) as error:
419 1
            msg = f"This operation is not completed: {error}"
420
            return jsonify(msg), 400
421