Passed
Pull Request — master (#36)
by Vinicius
16:52 queued 13:33
created

build.main.Main.execute()   D

Complexity

Conditions 12

Size

Total Lines 76
Code Lines 58

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 37
CRAP Score 12.5799

Importance

Changes 0
Metric Value
cc 12
eloc 58
nop 1
dl 0
loc 76
ccs 37
cts 44
cp 0.8409
crap 12.5799
rs 4.7345
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.execute() 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 1
import time
4
5 1
import requests
6 1
from flask import jsonify, request
7 1
from pyof.foundation.basic_types import DPID, UBInt16, UBInt32
8 1
from pyof.foundation.network_types import LLDP, VLAN, Ethernet, EtherType
9 1
from pyof.v0x01.common.action import ActionOutput as AO10
10 1
from pyof.v0x01.common.phy_port import Port as Port10
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.port import PortNo as Port13
14 1
from pyof.v0x04.controller2switch.packet_out import PacketOut as PO13
15
16 1
from kytos.core import KytosEvent, KytosNApp, log, rest
17 1
from kytos.core.helpers import listen_to
18 1
from napps.kytos.of_lldp import constants, settings
19 1
from napps.kytos.of_lldp.loop_manager import LoopManager, LoopState
20 1
from napps.kytos.of_lldp.utils import get_cookie
21
22
23 1
class Main(KytosNApp):
24
    """Main OF_LLDP NApp Class."""
25
26 1
    def setup(self):
27
        """Make this NApp run in a loop."""
28 1
        self.vlan_id = None
29 1
        self.polling_time = settings.POLLING_TIME
30 1
        if hasattr(settings, "FLOW_VLAN_VID"):
31 1
            self.vlan_id = settings.FLOW_VLAN_VID
32 1
        self.execute_as_loop(self.polling_time)
33 1
        self.loop_manager = LoopManager(self.controller)
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 = 'Switch: %s (%s)'
98 1
                msg += ' Interface: %s'
99 1
                msg += ' -- LLDP PacketOut --'
100 1
                msg += ' Ethernet: eth_type (%s) | src (%s) | dst (%s) /'
101 1
                msg += ' LLDP: Switch (%s) | portno (%s)'
102
103 1
                log.debug(
104
                    msg,
105
                    switch.connection, switch.dpid,
106
                    interface.id, ethernet.ether_type,
107
                    ethernet.source, ethernet.destination,
108
                    switch.dpid, interface.port_number)
109
110 1
        self.try_to_publish_stopped_loops()
111
112 1
    def try_to_publish_stopped_loops(self):
113
        """Try to publish current stopped loops."""
114
        for dpid, port_pairs in self.loop_manager.get_stopped_loops().items():
115
            try:
116
                switch = self.controller.get_switch_by_dpid(dpid)
117
                for port_pair in port_pairs:
118
                    interface_a = switch.interfaces[port_pair[0]]
119
                    interface_b = switch.interfaces[port_pair[1]]
120
                    self.loop_manager.publish_loop_state(
121
                        interface_a, interface_b, LoopState.stopped.value
122
                    )
123
            except (KeyError, AttributeError) as exc:
124
                items = self.loop_manager.get_stopped_loops()
125
                log.error(f"try_to_publish_stopped_loops failed with: {items} "
126
                          f"{str(exc)}")
127
                return None
128
129 1
    @listen_to('kytos/topology.switch.(enabled|disabled)')
130
    def handle_lldp_flows(self, event):
131
        """Install or remove flows in a switch.
132
133
        Install a flow to send LLDP packets to the controller. The proactive
134
        flow is installed whenever a switch is enabled. If the switch is
135
        disabled the flow is removed.
136
137
        Args:
138
            event (:class:`~kytos.core.events.KytosEvent`):
139
                Event with new switch information.
140
141
        """
142 1
        self._handle_lldp_flows(event)
143
144 1
    @listen_to("kytos/of_lldp.loop.action.log")
145
    def on_lldp_loop_log_action(self, event):
146
        """Handle LLDP loop log action."""
147
        interface_a = event.content["interface_a"]
148
        interface_b = event.content["interface_b"]
149
        self.loop_manager.handle_log_action(interface_a, interface_b)
150
151 1
    @listen_to("kytos/of_lldp.loop.action.disable")
152
    def on_lldp_loop_disable_action(self, event):
153
        """Handle LLDP loop disable action."""
154
        interface_a = event.content["interface_a"]
155
        interface_b = event.content["interface_b"]
156
        self.loop_manager.handle_disable_action(interface_a, interface_b)
157
158 1
    @listen_to("kytos/of_lldp.loop.detected")
159
    def on_lldp_loop_detected(self, event):
160
        """Handle LLDP loop detected."""
161
        interface_id = event.content["interface_id"]
162
        dpid = event.content["dpid"]
163
        port_pair = event.content["port_numbers"]
164
        self.loop_manager.handle_loop_detected(interface_id, dpid, port_pair)
165
166 1
    @listen_to("kytos/of_lldp.loop.stopped")
167
    def on_lldp_loop_stopped(self, event):
168
        """Handle LLDP loop stopped."""
169
        dpid = event.content["dpid"]
170
        port_pair = event.content["port_numbers"]
171
        try:
172
            switch = self.controller.get_switch_by_dpid(dpid)
173
            interface_a = switch.interfaces[port_pair[0]]
174
            interface_b = switch.interfaces[port_pair[1]]
175
            self.loop_manager.handle_loop_stopped(interface_a, interface_b)
176
        except (KeyError, AttributeError) as exc:
177
            log.error("on_lldp_loop_stopped failed with: "
178
                      f"{event.content} {str(exc)}")
179
180 1
    @listen_to("kytos/topology.topology_loaded")
181
    def on_topology_loaded(self, event):
182
        """Handle on topology loaded."""
183
        topology = event.content["topology"]
184
        self.loop_manager.handle_topology_loaded(topology)
185
186 1
    @listen_to("kytos/topology.switches.metadata.(added|removed)")
187
    def on_switches_metadata_changed(self, event):
188
        """Handle on switches metadata changed."""
189
        switch = event.content["switch"]
190
        self.loop_manager.handle_switch_metadata_changed(switch)
191
192 1
    def _handle_lldp_flows(self, event):
193
        """Install or remove flows in a switch.
194
195
        Install a flow to send LLDP packets to the controller. The proactive
196
        flow is installed whenever a switch is enabled. If the switch is
197
        disabled the flow is removed.
198
        """
199 1
        try:
200 1
            dpid = event.content['dpid']
201 1
            switch = self.controller.get_switch_by_dpid(dpid)
202 1
            of_version = switch.connection.protocol.version
203
204
        except AttributeError:
205
            of_version = None
206
207 1
        def _retry_if_status_code(response, endpoint, data, status_codes,
208
                                  retries=3, wait=2):
209
            """Retry if the response is in the status_codes."""
210 1
            if response.status_code not in status_codes:
211 1
                return
212 1
            if retries - 1 <= 0:
213 1
                return
214 1
            data = dict(data)
215 1
            data["force"] = True
216 1
            res = requests.post(endpoint, json=data)
217 1
            method = res.request.method
218 1
            if res.status_code != 202:
219 1
                log.error(f"Failed to retry on {endpoint}, error: {res.text},"
220
                          f" status: {res.status_code}, method: {method},"
221
                          f" data: {data}")
222 1
                time.sleep(wait)
223 1
                return _retry_if_status_code(response, endpoint, data,
224
                                             status_codes, retries - 1, wait)
225
            log.info(f"Successfully forced {method} flows to {endpoint}")
226
227 1
        flow = self._build_lldp_flow(of_version, get_cookie(switch.dpid))
228 1
        if flow:
229 1
            destination = switch.id
230 1
            endpoint = f'{settings.FLOW_MANAGER_URL}/flows/{destination}'
231 1
            data = {'flows': [flow]}
232 1
            if event.name == 'kytos/topology.switch.enabled':
233 1
                flow.pop("cookie_mask")
234 1
                res = requests.post(endpoint, json=data)
235 1
                if res.status_code != 202:
236 1
                    log.error(f"Failed to push flows on {destination},"
237
                              f" error: {res.text}, status: {res.status_code},"
238
                              f" data: {data}")
239 1
                _retry_if_status_code(res, endpoint, data, [424, 500])
240
            else:
241 1
                res = requests.delete(endpoint, json=data)
242 1
                if res.status_code != 202:
243 1
                    log.error(f"Failed to delete flows on {destination},"
244
                              f" error: {res.text}, status: {res.status_code}",
245
                              f" data: {data}")
246
                _retry_if_status_code(res, endpoint, data, [424, 500])
247
248 1
    @listen_to('kytos/of_core.v0x0[14].messages.in.ofpt_packet_in')
249
    def on_ofpt_packet_in(self, event):
250
        """Dispatch two KytosEvents to notify identified NNI interfaces.
251
252
        Args:
253
            event (:class:`~kytos.core.events.KytosEvent`):
254
                Event with an LLDP packet as data.
255
256
        """
257
        self.notify_uplink_detected(event)
258
259 1
    def notify_uplink_detected(self, event):
260
        """Dispatch two KytosEvents to notify identified NNI interfaces.
261
262
        Args:
263
            event (:class:`~kytos.core.events.KytosEvent`):
264
                Event with an LLDP packet as data.
265
266
        """
267 1
        ethernet = self._unpack_non_empty(Ethernet, event.message.data)
268 1
        if ethernet.ether_type == EtherType.LLDP:
269 1
            try:
270 1
                lldp = self._unpack_non_empty(LLDP, ethernet.data)
271 1
                dpid = self._unpack_non_empty(DPID, lldp.chassis_id.sub_value)
272
            except struct.error:
273
                #: If we have a LLDP packet but we cannot unpack it, or the
274
                #: unpacked packet does not contain the dpid attribute, then
275
                #: we are dealing with a LLDP generated by someone else. Thus
276
                #: this packet is not useful for us and we may just ignore it.
277
                return
278
279 1
            switch_a = event.source.switch
280 1
            port_a = event.message.in_port
281 1
            switch_b = None
282 1
            port_b = None
283
284
            # in_port is currently a UBInt16 in v0x01 and an Int in v0x04.
285 1
            if isinstance(port_a, int):
286 1
                port_a = UBInt32(port_a)
287
288 1
            try:
289 1
                switch_b = self.controller.get_switch_by_dpid(dpid.value)
290 1
                of_version = switch_b.connection.protocol.version
291 1
                port_type = UBInt16 if of_version == 0x01 else UBInt32
292 1
                port_b = self._unpack_non_empty(port_type,
293
                                                lldp.port_id.sub_value)
294
            except AttributeError:
295
                log.debug("Couldn't find datapath %s.", dpid.value)
296
297
            # Return if any of the needed information are not available
298 1
            if not (switch_a and port_a and switch_b and port_b):
299
                return
300
301 1
            interface_a = switch_a.get_interface_by_port_no(port_a.value)
302 1
            interface_b = switch_b.get_interface_by_port_no(port_b.value)
303
304 1
            self.loop_manager.process_if_looped(interface_a, interface_b)
305 1
            event_out = KytosEvent(name='kytos/of_lldp.interface.is.nni',
306
                                   content={'interface_a': interface_a,
307
                                            'interface_b': interface_b})
308 1
            self.controller.buffers.app.put(event_out)
309
310 1
    def notify_lldp_change(self, state, interface_ids):
311
        """Dispatch a KytosEvent to notify changes to the LLDP status."""
312 1
        content = {'attribute': 'LLDP',
313
                   'state': state,
314
                   'interface_ids': interface_ids}
315 1
        event_out = KytosEvent(name='kytos/of_lldp.network_status.updated',
316
                               content=content)
317 1
        self.controller.buffers.app.put(event_out)
318
319 1
    def shutdown(self):
320
        """End of the application."""
321
        log.debug('Shutting down...')
322
323 1
    @staticmethod
324
    def _build_lldp_packet_out(version, port_number, data):
325
        """Build a LLDP PacketOut message.
326
327
        Args:
328
            version (int): OpenFlow version
329
            port_number (int): Switch port number where the packet must be
330
                forwarded to.
331
            data (bytes): Binary data to be sent through the port.
332
333
        Returns:
334
            PacketOut message for the specific given OpenFlow version, if it
335
                is supported.
336
            None if the OpenFlow version is not supported.
337
338
        """
339 1
        if version == 0x01:
340 1
            action_output_class = AO10
341 1
            packet_out_class = PO10
342 1
        elif version == 0x04:
343 1
            action_output_class = AO13
344 1
            packet_out_class = PO13
345
        else:
346 1
            log.info('Openflow version %s is not yet supported.', version)
347 1
            return None
348
349 1
        output_action = action_output_class()
350 1
        output_action.port = port_number
351
352 1
        packet_out = packet_out_class()
353 1
        packet_out.data = data
354 1
        packet_out.actions.append(output_action)
355
356 1
        return packet_out
357
358 1
    def _build_lldp_flow(self, version, cookie,
359
                         cookie_mask=0xffffffffffffffff):
360
        """Build a Flow message to send LLDP to the controller.
361
362
        Args:
363
            version (int): OpenFlow version.
364
365
        Returns:
366
            Flow dictionary message for the specific given OpenFlow version,
367
            if it is supported.
368
            None if the OpenFlow version is not supported.
369
370
        """
371 1
        flow = {}
372 1
        match = {}
373 1
        flow['priority'] = settings.FLOW_PRIORITY
374 1
        flow['table_id'] = settings.TABLE_ID
375 1
        flow['cookie'] = cookie
376 1
        flow['cookie_mask'] = cookie_mask
377 1
        match['dl_type'] = EtherType.LLDP
378 1
        if self.vlan_id:
379 1
            match['dl_vlan'] = self.vlan_id
380 1
        flow['match'] = match
381
382 1
        if version == 0x01:
383 1
            flow['actions'] = [{'action_type': 'output',
384
                                'port': Port10.OFPP_CONTROLLER}]
385 1
        elif version == 0x04:
386 1
            flow['actions'] = [{'action_type': 'output',
387
                                'port': Port13.OFPP_CONTROLLER}]
388
        else:
389
            flow = None
390
391 1
        return flow
392
393 1
    @staticmethod
394
    def _unpack_non_empty(desired_class, data):
395
        """Unpack data using an instance of desired_class.
396
397
        Args:
398
            desired_class (class): The class to be used to unpack data.
399
            data (bytes): bytes to be unpacked.
400
401
        Return:
402
            An instance of desired_class class with data unpacked into it.
403
404
        Raises:
405
            UnpackException if the unpack could not be performed.
406
407
        """
408 1
        obj = desired_class()
409
410 1
        if hasattr(data, 'value'):
411 1
            data = data.value
412
413 1
        obj.unpack(data)
414
415 1
        return obj
416
417 1
    @staticmethod
418
    def _get_data(req):
419
        """Get request data."""
420 1
        data = req.get_json()  # Valid format { "interfaces": [...] }
421 1
        return data.get('interfaces', [])
422
423 1
    def _get_interfaces(self):
424
        """Get all interfaces."""
425 1
        interfaces = []
426 1
        for switch in list(self.controller.switches.values()):
427 1
            interfaces += list(switch.interfaces.values())
428 1
        return interfaces
429
430 1
    @staticmethod
431
    def _get_interfaces_dict(interfaces):
432
        """Return a dict of interfaces."""
433 1
        return {inter.id: inter for inter in interfaces}
434
435 1
    def _get_lldp_interfaces(self):
436
        """Get interfaces enabled to receive LLDP packets."""
437 1
        return [inter.id for inter in self._get_interfaces() if inter.lldp]
438
439 1
    @rest('v1/interfaces', methods=['GET'])
440
    def get_lldp_interfaces(self):
441
        """Return all the interfaces that have LLDP traffic enabled."""
442 1
        return jsonify({"interfaces": self._get_lldp_interfaces()}), 200
443
444 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...
445
    def disable_lldp(self):
446
        """Disables an interface to receive LLDP packets."""
447 1
        interface_ids = self._get_data(request)
448 1
        error_list = []  # List of interfaces that were not activated.
449 1
        changed_interfaces = []
450 1
        interface_ids = filter(None, interface_ids)
451 1
        interfaces = self._get_interfaces()
452 1
        if not interfaces:
453 1
            return jsonify("No interfaces were found."), 404
454 1
        interfaces = self._get_interfaces_dict(interfaces)
455 1
        for id_ in interface_ids:
456 1
            interface = interfaces.get(id_)
457 1
            if interface:
458 1
                interface.lldp = False
459 1
                changed_interfaces.append(id_)
460
            else:
461 1
                error_list.append(id_)
462 1
        if changed_interfaces:
463 1
            self.notify_lldp_change('disabled', changed_interfaces)
464 1
        if not error_list:
465 1
            return jsonify(
466
                "All the requested interfaces have been disabled."), 200
467
468
        # Return a list of interfaces that couldn't be disabled
469 1
        msg_error = "Some interfaces couldn't be found and deactivated: "
470 1
        return jsonify({msg_error:
471
                        error_list}), 400
472
473 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...
474
    def enable_lldp(self):
475
        """Enable an interface to receive LLDP packets."""
476 1
        interface_ids = self._get_data(request)
477 1
        error_list = []  # List of interfaces that were not activated.
478 1
        changed_interfaces = []
479 1
        interface_ids = filter(None, interface_ids)
480 1
        interfaces = self._get_interfaces()
481 1
        if not interfaces:
482 1
            return jsonify("No interfaces were found."), 404
483 1
        interfaces = self._get_interfaces_dict(interfaces)
484 1
        for id_ in interface_ids:
485 1
            interface = interfaces.get(id_)
486 1
            if interface:
487 1
                interface.lldp = True
488 1
                changed_interfaces.append(id_)
489
            else:
490 1
                error_list.append(id_)
491 1
        if changed_interfaces:
492 1
            self.notify_lldp_change('enabled', changed_interfaces)
493 1
        if not error_list:
494 1
            return jsonify(
495
                "All the requested interfaces have been enabled."), 200
496
497
        # Return a list of interfaces that couldn't be enabled
498 1
        msg_error = "Some interfaces couldn't be found and activated: "
499 1
        return jsonify({msg_error:
500
                        error_list}), 400
501
502 1
    @rest('v1/polling_time', methods=['GET'])
503
    def get_time(self):
504
        """Get LLDP polling time in seconds."""
505 1
        return jsonify({"polling_time": self.polling_time}), 200
506
507 1
    @rest('v1/polling_time', methods=['POST'])
508
    def set_time(self):
509
        """Set LLDP polling time."""
510
        # pylint: disable=attribute-defined-outside-init
511 1
        try:
512 1
            payload = request.get_json()
513 1
            polling_time = int(payload['polling_time'])
514 1
            if polling_time <= 0:
515
                raise ValueError(f"invalid polling_time {polling_time}, "
516
                                 "must be greater than zero")
517 1
            self.polling_time = polling_time
518 1
            self.execute_as_loop(self.polling_time)
519 1
            log.info("Polling time has been updated to %s"
520
                     " second(s), but this change will not be saved"
521
                     " permanently.", self.polling_time)
522 1
            return jsonify("Polling time has been updated."), 200
523 1
        except (ValueError, KeyError) as error:
524 1
            msg = f"This operation is not completed: {error}"
525
            return jsonify(msg), 400
526