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

build.main.Main.notify_lldp_change()   A

Complexity

Conditions 1

Size

Total Lines 8
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

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