Passed
Pull Request — master (#29)
by Vinicius
03:02 queued 18s
created

build.main.Main.shutdown()   A

Complexity

Conditions 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1.125

Importance

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