Passed
Pull Request — master (#29)
by Vinicius
03:27
created

build.main   F

Complexity

Total Complexity 63

Size/Duplication

Total Lines 407
Duplicated Lines 13.76 %

Test Coverage

Coverage 92.38%

Importance

Changes 0
Metric Value
eloc 263
dl 56
loc 407
ccs 206
cts 223
cp 0.9238
rs 3.36
c 0
b 0
f 0
wmc 63

18 Methods

Rating   Name   Duplication   Size   Complexity  
A Main.setup() 0 7 2
D Main.execute() 0 74 12
B Main.disable_lldp() 28 28 6
A Main._unpack_non_empty() 0 23 2
A Main._get_interfaces_dict() 0 4 1
A Main.set_time() 0 19 3
A Main.get_time() 0 4 1
C Main.notify_uplink_detected() 0 50 10
A Main.shutdown() 0 3 1
A Main.notify_lldp_change() 0 8 1
A Main.get_lldp_interfaces() 0 4 1
A Main._get_lldp_interfaces() 0 3 1
A Main._build_lldp_packet_out() 0 34 3
B Main.enable_lldp() 28 28 6
A Main._get_data() 0 5 1
A Main._get_interfaces() 0 6 2
A Main._build_lldp_flow() 0 31 4
B Main.handle_lldp_flows() 0 35 6

How to fix   Duplicated Code    Complexity   

Duplicated Code

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:

Complexity

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

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
import requests
5 1
from flask import jsonify, request
6 1
from pyof.foundation.basic_types import DPID, UBInt16, UBInt32
7 1
from pyof.foundation.network_types import LLDP, VLAN, Ethernet, EtherType
8 1
from pyof.v0x01.common.action import ActionOutput as AO10
9 1
from pyof.v0x01.common.phy_port import Port as Port10
10 1
from pyof.v0x01.controller2switch.packet_out import PacketOut as PO10
11 1
from pyof.v0x04.common.action import ActionOutput as AO13
12 1
from pyof.v0x04.common.port import PortNo as Port13
13 1
from pyof.v0x04.controller2switch.packet_out import PacketOut as PO13
14
15 1
from kytos.core import KytosEvent, KytosNApp, log, rest
16 1
from kytos.core.helpers import listen_to
17 1
from napps.kytos.of_lldp import constants, settings
18
19
20 1
class Main(KytosNApp):
21
    """Main OF_LLDP NApp Class."""
22
23 1
    def setup(self):
24
        """Make this NApp run in a loop."""
25 1
        self.vlan_id = None
26 1
        self.polling_time = settings.POLLING_TIME
27 1
        if hasattr(settings, "FLOW_VLAN_VID"):
28 1
            self.vlan_id = settings.FLOW_VLAN_VID
29 1
        self.execute_as_loop(self.polling_time)
30
31 1
    def execute(self):
32
        """Send LLDP Packets every 'POLLING_TIME' seconds to all switches."""
33 1
        switches = list(self.controller.switches.values())
34 1
        for switch in switches:
35 1
            try:
36 1
                of_version = switch.connection.protocol.version
37
            except AttributeError:
38
                of_version = None
39
40 1
            if not switch.is_connected():
41
                continue
42
43 1
            if of_version == 0x01:
44 1
                port_type = UBInt16
45 1
                local_port = Port10.OFPP_LOCAL
46 1
            elif of_version == 0x04:
47 1
                port_type = UBInt32
48 1
                local_port = Port13.OFPP_LOCAL
49
            else:
50
                # skip the current switch with unsupported OF version
51
                continue
52
53 1
            interfaces = list(switch.interfaces.values())
54 1
            for interface in interfaces:
55
                # Interface marked to receive lldp packet
56
                # Only send LLDP packet to active interface
57 1
                if(not interface.lldp or not interface.is_active()
58
                   or not interface.is_enabled()):
59
                    continue
60
                # Avoid the interface that connects to the controller.
61 1
                if interface.port_number == local_port:
62
                    continue
63
64 1
                lldp = LLDP()
65 1
                lldp.chassis_id.sub_value = DPID(switch.dpid)
66 1
                lldp.port_id.sub_value = port_type(interface.port_number)
67
68 1
                ethernet = Ethernet()
69 1
                ethernet.ether_type = EtherType.LLDP
70 1
                ethernet.source = interface.address
71 1
                ethernet.destination = constants.LLDP_MULTICAST_MAC
72 1
                ethernet.data = lldp.pack()
73
                # self.vlan_id == None will result in a packet with no VLAN.
74 1
                ethernet.vlans.append(VLAN(vid=self.vlan_id))
75
76 1
                packet_out = self._build_lldp_packet_out(
77
                                    of_version,
78
                                    interface.port_number, ethernet.pack())
79
80 1
                if packet_out is None:
81
                    continue
82
83 1
                event_out = KytosEvent(
84
                    name='kytos/of_lldp.messages.out.ofpt_packet_out',
85
                    content={
86
                            'destination': switch.connection,
87
                            'message': packet_out})
88 1
                self.controller.buffers.msg_out.put(event_out)
89 1
                log.debug(
90
                    "Sending a LLDP PacketOut to the switch %s",
91
                    switch.dpid)
92
93 1
                msg = 'Switch: %s (%s)'
94 1
                msg += ' Interface: %s'
95 1
                msg += ' -- LLDP PacketOut --'
96 1
                msg += ' Ethernet: eth_type (%s) | src (%s) | dst (%s) /'
97 1
                msg += ' LLDP: Switch (%s) | portno (%s)'
98
99 1
                log.debug(
100
                    msg,
101
                    switch.connection, switch.dpid,
102
                    interface.id, ethernet.ether_type,
103
                    ethernet.source, ethernet.destination,
104
                    switch.dpid, interface.port_number)
105
106 1
    @listen_to('kytos/topology.switch.(enabled|disabled)')
107
    def handle_lldp_flows(self, event):
108
        """Install or remove flows in a switch.
109
110
        Install a flow to send LLDP packets to the controller. The proactive
111
        flow is installed whenever a switch is enabled. If the switch is
112
        disabled the flow is removed.
113
114
        Args:
115
            event (:class:`~kytos.core.events.KytosEvent`):
116
                Event with new switch information.
117
118
        """
119 1
        try:
120 1
            dpid = event.content['dpid']
121 1
            switch = self.controller.get_switch_by_dpid(dpid)
122 1
            of_version = switch.connection.protocol.version
123
124
        except AttributeError:
125
            of_version = None
126
127 1
        flow = self._build_lldp_flow(of_version)
128 1
        if flow:
129 1
            destination = switch.id
130 1
            endpoint = f'{settings.FLOW_MANAGER_URL}/flows/{destination}'
131 1
            data = {'force': True, 'flows': [flow]}
132 1
            if event.name == 'kytos/topology.switch.enabled':
133 1
                res = requests.post(endpoint, json=data)
134 1
                if res.status_code != 202:
135 1
                    log.error(f"Failed to push flows on {destination} error: "
136
                              f"{res.text}, status: {res.status_code}")
137
            else:
138 1
                res = requests.delete(endpoint, json=data)
139 1
                if res.status_code != 202:
140 1
                    log.error(f"Failed to delete flows on {destination} error:"
141
                              f" {res.text}, status: {res.status_code}")
142
143 1
    @listen_to('kytos/of_core.v0x0[14].messages.in.ofpt_packet_in')
144
    def notify_uplink_detected(self, event):
145
        """Dispatch two KytosEvents to notify identified NNI interfaces.
146
147
        Args:
148
            event (:class:`~kytos.core.events.KytosEvent`):
149
                Event with an LLDP packet as data.
150
151
        """
152 1
        ethernet = self._unpack_non_empty(Ethernet, event.message.data)
153 1
        if ethernet.ether_type == EtherType.LLDP:
154 1
            try:
155 1
                lldp = self._unpack_non_empty(LLDP, ethernet.data)
156 1
                dpid = self._unpack_non_empty(DPID, lldp.chassis_id.sub_value)
157
            except struct.error:
158
                #: If we have a LLDP packet but we cannot unpack it, or the
159
                #: unpacked packet does not contain the dpid attribute, then
160
                #: we are dealing with a LLDP generated by someone else. Thus
161
                #: this packet is not useful for us and we may just ignore it.
162
                return
163
164 1
            switch_a = event.source.switch
165 1
            port_a = event.message.in_port
166 1
            switch_b = None
167 1
            port_b = None
168
169
            # in_port is currently a UBInt16 in v0x01 and an Int in v0x04.
170 1
            if isinstance(port_a, int):
171 1
                port_a = UBInt32(port_a)
172
173 1
            try:
174 1
                switch_b = self.controller.get_switch_by_dpid(dpid.value)
175 1
                of_version = switch_b.connection.protocol.version
176 1
                port_type = UBInt16 if of_version == 0x01 else UBInt32
177 1
                port_b = self._unpack_non_empty(port_type,
178
                                                lldp.port_id.sub_value)
179
            except AttributeError:
180
                log.debug("Couldn't find datapath %s.", dpid.value)
181
182
            # Return if any of the needed information are not available
183 1
            if not (switch_a and port_a and switch_b and port_b):
184
                return
185
186 1
            interface_a = switch_a.get_interface_by_port_no(port_a.value)
187 1
            interface_b = switch_b.get_interface_by_port_no(port_b.value)
188
189 1
            event_out = KytosEvent(name='kytos/of_lldp.interface.is.nni',
190
                                   content={'interface_a': interface_a,
191
                                            'interface_b': interface_b})
192 1
            self.controller.buffers.app.put(event_out)
193
194 1
    def notify_lldp_change(self, state, interface_ids):
195
        """Dispatch a KytosEvent to notify changes to the LLDP status."""
196 1
        content = {'attribute': 'LLDP',
197
                   'state': state,
198
                   'interface_ids': interface_ids}
199 1
        event_out = KytosEvent(name='kytos/of_lldp.network_status.updated',
200
                               content=content)
201 1
        self.controller.buffers.app.put(event_out)
202
203 1
    def shutdown(self):
204
        """End of the application."""
205
        log.debug('Shutting down...')
206
207 1
    @staticmethod
208
    def _build_lldp_packet_out(version, port_number, data):
209
        """Build a LLDP PacketOut message.
210
211
        Args:
212
            version (int): OpenFlow version
213
            port_number (int): Switch port number where the packet must be
214
                forwarded to.
215
            data (bytes): Binary data to be sent through the port.
216
217
        Returns:
218
            PacketOut message for the specific given OpenFlow version, if it
219
                is supported.
220
            None if the OpenFlow version is not supported.
221
222
        """
223 1
        if version == 0x01:
224 1
            action_output_class = AO10
225 1
            packet_out_class = PO10
226 1
        elif version == 0x04:
227 1
            action_output_class = AO13
228 1
            packet_out_class = PO13
229
        else:
230 1
            log.info('Openflow version %s is not yet supported.', version)
231 1
            return None
232
233 1
        output_action = action_output_class()
234 1
        output_action.port = port_number
235
236 1
        packet_out = packet_out_class()
237 1
        packet_out.data = data
238 1
        packet_out.actions.append(output_action)
239
240 1
        return packet_out
241
242 1
    def _build_lldp_flow(self, version):
243
        """Build a Flow message to send LLDP to the controller.
244
245
        Args:
246
            version (int): OpenFlow version.
247
248
        Returns:
249
            Flow dictionary message for the specific given OpenFlow version,
250
            if it is supported.
251
            None if the OpenFlow version is not supported.
252
253
        """
254 1
        flow = {}
255 1
        match = {}
256 1
        flow['priority'] = settings.FLOW_PRIORITY
257 1
        flow['table_id'] = settings.TABLE_ID
258 1
        match['dl_type'] = EtherType.LLDP
259 1
        if self.vlan_id:
260 1
            match['dl_vlan'] = self.vlan_id
261 1
        flow['match'] = match
262
263 1
        if version == 0x01:
264 1
            flow['actions'] = [{'action_type': 'output',
265
                                'port': Port10.OFPP_CONTROLLER}]
266 1
        elif version == 0x04:
267 1
            flow['actions'] = [{'action_type': 'output',
268
                                'port': Port13.OFPP_CONTROLLER}]
269
        else:
270
            flow = None
271
272 1
        return flow
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'])
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
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
        changed_interfaces = []
331 1
        interface_ids = filter(None, interface_ids)
332 1
        interfaces = self._get_interfaces()
333 1
        if not interfaces:
334 1
            return jsonify("No interfaces were found."), 404
335 1
        interfaces = self._get_interfaces_dict(interfaces)
336 1
        for id_ in interface_ids:
337 1
            interface = interfaces.get(id_)
338 1
            if interface:
339 1
                interface.lldp = False
340 1
                changed_interfaces.append(id_)
341
            else:
342 1
                error_list.append(id_)
343 1
        if changed_interfaces:
344 1
            self.notify_lldp_change('disabled', changed_interfaces)
345 1
        if not error_list:
346 1
            return jsonify(
347
                "All the requested interfaces have been disabled."), 200
348
349
        # Return a list of interfaces that couldn't be disabled
350 1
        msg_error = "Some interfaces couldn't be found and deactivated: "
351 1
        return jsonify({msg_error:
352
                        error_list}), 400
353
354 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...
355
    def enable_lldp(self):
356
        """Enable an interface to receive LLDP packets."""
357 1
        interface_ids = self._get_data(request)
358 1
        error_list = []  # List of interfaces that were not activated.
359 1
        changed_interfaces = []
360 1
        interface_ids = filter(None, interface_ids)
361 1
        interfaces = self._get_interfaces()
362 1
        if not interfaces:
363 1
            return jsonify("No interfaces were found."), 404
364 1
        interfaces = self._get_interfaces_dict(interfaces)
365 1
        for id_ in interface_ids:
366 1
            interface = interfaces.get(id_)
367 1
            if interface:
368 1
                interface.lldp = True
369 1
                changed_interfaces.append(id_)
370
            else:
371 1
                error_list.append(id_)
372 1
        if changed_interfaces:
373 1
            self.notify_lldp_change('enabled', changed_interfaces)
374 1
        if not error_list:
375 1
            return jsonify(
376
                "All the requested interfaces have been enabled."), 200
377
378
        # Return a list of interfaces that couldn't be enabled
379 1
        msg_error = "Some interfaces couldn't be found and activated: "
380 1
        return jsonify({msg_error:
381
                        error_list}), 400
382
383 1
    @rest('v1/polling_time', methods=['GET'])
384
    def get_time(self):
385
        """Get LLDP polling time in seconds."""
386 1
        return jsonify({"polling_time": self.polling_time}), 200
387
388 1
    @rest('v1/polling_time', methods=['POST'])
389
    def set_time(self):
390
        """Set LLDP polling time."""
391
        # pylint: disable=attribute-defined-outside-init
392 1
        try:
393 1
            payload = request.get_json()
394 1
            polling_time = int(payload['polling_time'])
395 1
            if polling_time <= 0:
396
                raise ValueError(f"invalid polling_time {polling_time}, "
397
                                 "must be greater than zero")
398 1
            self.polling_time = polling_time
399 1
            self.execute_as_loop(self.polling_time)
400 1
            log.info("Polling time has been updated to %s"
401
                     " second(s), but this change will not be saved"
402
                     " permanently.", self.polling_time)
403 1
            return jsonify("Polling time has been updated."), 200
404 1
        except (ValueError, KeyError) as error:
405 1
            msg = f"This operation is not completed: {error}"
406
            return jsonify(msg), 400
407