Passed
Pull Request — master (#52)
by Vinicius
12:20 queued 05:21
created

build.main.Main.on_switches_metadata_changed()   A

Complexity

Conditions 1

Size

Total Lines 5
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1.125

Importance

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