Passed
Pull Request — master (#36)
by Vinicius
10:59 queued 07:52
created

build.main.Main.on_lldp_loop_disable_action()   A

Complexity

Conditions 1

Size

Total Lines 6
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1.4218

Importance

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