Passed
Pull Request — master (#50)
by
unknown
01:55
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
4 1
from flask import jsonify, request
5 1
from pyof.foundation.basic_types import DPID, UBInt16, UBInt32
6 1
from pyof.foundation.network_types import LLDP, VLAN, Ethernet, EtherType
7 1
from pyof.v0x01.common.action import ActionOutput as AO10
8 1
from pyof.v0x01.common.phy_port import Port as Port10
9 1
from pyof.v0x01.controller2switch.flow_mod import FlowMod as FM10
10 1
from pyof.v0x01.controller2switch.flow_mod import FlowModCommand as FMC
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.flow_instructions import InstructionApplyAction
14 1
from pyof.v0x04.common.flow_match import OxmOfbMatchField, OxmTLV, VlanId
15 1
from pyof.v0x04.common.port import PortNo as Port13
16 1
from pyof.v0x04.controller2switch.flow_mod import FlowMod as FM13
17 1
from pyof.v0x04.controller2switch.packet_out import PacketOut as PO13
18
19 1
from kytos.core import KytosEvent, KytosNApp, log, rest
20 1
from kytos.core.helpers import listen_to
21 1
from napps.kytos.of_lldp import constants, settings
22
23
24 1
class Main(KytosNApp):
25
    """Main OF_LLDP NApp Class."""
26
27 1
    def setup(self):
28
        """Make this NApp run in a loop."""
29 1
        self.vlan_id = None
30 1
        if hasattr(settings, "FLOW_VLAN_VID"):
31 1
            self.vlan_id = settings.FLOW_VLAN_VID
32 1
        self.execute_as_loop(settings.POLLING_TIME)
33
34 1
    def execute(self):
35
        """Send LLDP Packets every 'POLLING_TIME' seconds to all switches."""
36 1
        switches = list(self.controller.switches.values())
37 1
        for switch in switches:
38 1
            try:
39 1
                of_version = switch.connection.protocol.version
40
            except AttributeError:
41
                of_version = None
42
43 1
            if not switch.is_connected():
44
                continue
45
46 1
            if of_version == 0x01:
47 1
                port_type = UBInt16
48 1
                local_port = Port10.OFPP_LOCAL
49 1
            elif of_version == 0x04:
50 1
                port_type = UBInt32
51 1
                local_port = Port13.OFPP_LOCAL
52
            else:
53
                # skip the current switch with unsupported OF version
54
                continue
55
56 1
            interfaces = list(switch.interfaces.values())
57 1
            for interface in interfaces:
58
                # Interface marked to receive lldp packet
59
                # Only send LLDP packet to active interface
60 1
                if(not interface.lldp or not interface.is_active()
61
                   or not interface.is_enabled()):
62
                    continue
63
                # Avoid the interface that connects to the controller.
64 1
                if interface.port_number == local_port:
65
                    continue
66
67 1
                lldp = LLDP()
68 1
                lldp.chassis_id.sub_value = DPID(switch.dpid)
69 1
                lldp.port_id.sub_value = port_type(interface.port_number)
70
71 1
                ethernet = Ethernet()
72 1
                ethernet.ether_type = EtherType.LLDP
73 1
                ethernet.source = interface.address
74 1
                ethernet.destination = constants.LLDP_MULTICAST_MAC
75 1
                ethernet.data = lldp.pack()
76
                # self.vlan_id == None will result in a packet with no VLAN.
77 1
                ethernet.vlans.append(VLAN(vid=self.vlan_id))
78
79 1
                packet_out = self._build_lldp_packet_out(
80
                                    of_version,
81
                                    interface.port_number, ethernet.pack())
82
83 1
                if packet_out is None:
84
                    continue
85
86 1
                event_out = KytosEvent(
87
                    name='kytos/of_lldp.messages.out.ofpt_packet_out',
88
                    content={
89
                            'destination': switch.connection,
90
                            'message': packet_out})
91 1
                self.controller.buffers.msg_out.put(event_out)
92 1
                log.debug(
93
                    "Sending a LLDP PacketOut to the switch %s",
94
                    switch.dpid)
95
96 1
                msg = '\n'
97 1
                msg += 'Switch: %s (%s)\n'
98 1
                msg += ' Interfaces: %s\n'
99 1
                msg += ' -- LLDP PacketOut --\n'
100 1
                msg += ' Ethernet: eth_type (%s) | src (%s) | dst (%s)'
101 1
                msg += '\n'
102 1
                msg += ' LLDP: Switch (%s) | port (%s)'
103
104 1
                log.debug(
105
                    msg,
106
                    switch.connection.address, switch.dpid,
107
                    switch.interfaces, ethernet.ether_type,
108
                    ethernet.source, ethernet.destination,
109
                    switch.dpid, interface.port_number)
110
111 1
    @listen_to('kytos/of_core.handshake.completed')
112
    def install_lldp_flow(self, event):
113
        """Install a flow to send LLDP packets to the controller.
114
115
        The proactive flow is installed whenever a switch connects.
116
117
        Args:
118
            event (:class:`~kytos.core.events.KytosEvent`):
119
                Event with new switch information.
120
121
        """
122 1
        try:
123 1
            of_version = event.content['switch'].connection.protocol.version
124 1
        except AttributeError:
125 1
            of_version = None
126
127 1
        flow_mod = self._build_lldp_flow_mod(of_version)
128
129 1
        if flow_mod:
130 1
            name = 'kytos/of_lldp.messages.out.ofpt_flow_mod'
131 1
            content = {'destination': event.content['switch'].connection,
132
                       'message': flow_mod}
133
134 1
            event_out = KytosEvent(name=name, content=content)
135 1
            self.controller.buffers.msg_out.put(event_out)
136
137 1
    @listen_to('kytos/of_core.v0x0[14].messages.in.ofpt_packet_in')
138
    def notify_uplink_detected(self, event):
139
        """Dispatch two KytosEvents to notify identified NNI interfaces.
140
141
        Args:
142
            event (:class:`~kytos.core.events.KytosEvent`):
143
                Event with an LLDP packet as data.
144
145
        """
146 1
        ethernet = self._unpack_non_empty(Ethernet, event.message.data)
147 1
        if ethernet.ether_type == EtherType.LLDP:
148 1
            try:
149 1
                lldp = self._unpack_non_empty(LLDP, ethernet.data)
150 1
                dpid = self._unpack_non_empty(DPID, lldp.chassis_id.sub_value)
151
            except struct.error:
152
                #: If we have a LLDP packet but we cannot unpack it, or the
153
                #: unpacked packet does not contain the dpid attribute, then
154
                #: we are dealing with a LLDP generated by someone else. Thus
155
                #: this packet is not useful for us and we may just ignore it.
156
                return
157
158 1
            switch_a = event.source.switch
159 1
            port_a = event.message.in_port
160 1
            switch_b = None
161 1
            port_b = None
162
163
            # in_port is currently a UBInt16 in v0x01 and an Int in v0x04.
164 1
            if isinstance(port_a, int):
165 1
                port_a = UBInt32(port_a)
166
167 1
            try:
168 1
                switch_b = self.controller.get_switch_by_dpid(dpid.value)
169 1
                of_version = switch_b.connection.protocol.version
170 1
                port_type = UBInt16 if of_version == 0x01 else UBInt32
171 1
                port_b = self._unpack_non_empty(port_type,
172
                                                lldp.port_id.sub_value)
173
            except AttributeError:
174
                log.debug("Couldn't find datapath %s.", dpid.value)
175
176
            # Return if any of the needed information are not available
177 1
            if not (switch_a and port_a and switch_b and port_b):
178
                return
179
180 1
            interface_a = switch_a.get_interface_by_port_no(port_a.value)
181 1
            interface_b = switch_b.get_interface_by_port_no(port_b.value)
182
183 1
            event_out = KytosEvent(name='kytos/of_lldp.interface.is.nni',
184
                                   content={'interface_a': interface_a,
185
                                            'interface_b': interface_b})
186 1
            self.controller.buffers.app.put(event_out)
187
188 1
    def notify_lldp_change(self, state, interface_ids):
189
        """Dispatch a KytosEvent to notify changes to the LLDP status."""
190 1
        content = {'attribute': 'LLDP',
191
                   'state': state,
192
                   'interface_ids': interface_ids}
193 1
        event_out = KytosEvent(name='kytos/of_lldp.network_status.updated',
194
                               content=content)
195 1
        self.controller.buffers.app.put(event_out)
196
197 1
    def shutdown(self):
198
        """End of the application."""
199
        log.debug('Shutting down...')
200
201 1
    @staticmethod
202
    def _build_lldp_packet_out(version, port_number, data):
203
        """Build a LLDP PacketOut message.
204
205
        Args:
206
            version (int): OpenFlow version
207
            port_number (int): Switch port number where the packet must be
208
                forwarded to.
209
            data (bytes): Binary data to be sent through the port.
210
211
        Returns:
212
            PacketOut message for the specific given OpenFlow version, if it
213
                is supported.
214
            None if the OpenFlow version is not supported.
215
216
        """
217 1
        if version == 0x01:
218 1
            action_output_class = AO10
219 1
            packet_out_class = PO10
220 1
        elif version == 0x04:
221 1
            action_output_class = AO13
222 1
            packet_out_class = PO13
223
        else:
224 1
            log.info('Openflow version %s is not yet supported.', version)
225 1
            return None
226
227 1
        output_action = action_output_class()
228 1
        output_action.port = port_number
229
230 1
        packet_out = packet_out_class()
231 1
        packet_out.data = data
232 1
        packet_out.actions.append(output_action)
233
234 1
        return packet_out
235
236 1
    def _build_lldp_flow_mod(self, version):
237
        """Build a FlodMod message to send LLDP to the controller.
238
239
        Args:
240
            version (int): OpenFlow version.
241
242
        Returns:
243
            FlowMod message for the specific given OpenFlow version, if it is
244
                supported.
245
            None if the OpenFlow version is not supported.
246
247
        """
248 1
        if version == 0x01:
249 1
            flow_mod = FM10()
250 1
            flow_mod.command = FMC.OFPFC_ADD
251 1
            flow_mod.priority = settings.FLOW_PRIORITY
252 1
            flow_mod.match.dl_type = EtherType.LLDP
253 1
            if self.vlan_id:
254 1
                flow_mod.match.dl_vlan = self.vlan_id
255 1
            flow_mod.actions.append(AO10(port=Port10.OFPP_CONTROLLER))
256
257 1
        elif version == 0x04:
258 1
            flow_mod = FM13()
259 1
            flow_mod.command = FMC.OFPFC_ADD
260 1
            flow_mod.priority = settings.FLOW_PRIORITY
261
262 1
            match_lldp = OxmTLV()
263 1
            match_lldp.oxm_field = OxmOfbMatchField.OFPXMT_OFB_ETH_TYPE
264 1
            match_lldp.oxm_value = EtherType.LLDP.to_bytes(2, 'big')
265 1
            flow_mod.match.oxm_match_fields.append(match_lldp)
266
267 1
            if self.vlan_id:
268 1
                match_vlan = OxmTLV()
269 1
                match_vlan.oxm_field = OxmOfbMatchField.OFPXMT_OFB_VLAN_VID
270 1
                vlan_value = self.vlan_id | VlanId.OFPVID_PRESENT
271 1
                match_vlan.oxm_value = vlan_value.to_bytes(2, 'big')
272 1
                flow_mod.match.oxm_match_fields.append(match_vlan)
273
274 1
            instruction = InstructionApplyAction()
275 1
            instruction.actions.append(AO13(port=Port13.OFPP_CONTROLLER))
276 1
            flow_mod.instructions.append(instruction)
277
278
        else:
279 1
            flow_mod = None
280
281 1
        return flow_mod
282
283 1
    @staticmethod
284
    def _unpack_non_empty(desired_class, data):
285
        """Unpack data using an instance of desired_class.
286
287
        Args:
288
            desired_class (class): The class to be used to unpack data.
289
            data (bytes): bytes to be unpacked.
290
291
        Return:
292
            An instance of desired_class class with data unpacked into it.
293
294
        Raises:
295
            UnpackException if the unpack could not be performed.
296
297
        """
298 1
        obj = desired_class()
299
300 1
        if hasattr(data, 'value'):
301 1
            data = data.value
302
303 1
        obj.unpack(data)
304
305 1
        return obj
306
307 1
    @staticmethod
308
    def _get_data(req):
309
        """Get request data."""
310 1
        data = req.get_json()  # Valid format { "interfaces": [...] }
311 1
        return data.get('interfaces', [])
312
313 1
    def _get_interfaces(self):
314
        """Get all interfaces."""
315 1
        interfaces = []
316 1
        for switch in list(self.controller.switches.values()):
317 1
            interfaces += list(switch.interfaces.values())
318 1
        return interfaces
319
320 1
    @staticmethod
321
    def _get_interfaces_dict(interfaces):
322
        """Return a dict of interfaces."""
323 1
        return {inter.id: inter for inter in interfaces}
324
325 1
    def _get_lldp_interfaces(self):
326
        """Get interfaces enabled to receive LLDP packets."""
327 1
        return [inter.id for inter in self._get_interfaces() if inter.lldp]
328
329 1
    @rest('v1/interfaces', methods=['GET'])
330
    def get_lldp_interfaces(self):
331
        """Return all the interfaces that have LLDP traffic enabled."""
332 1
        return jsonify({"interfaces": self._get_lldp_interfaces()}), 200
333
334 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...
335
    def disable_lldp(self):
336
        """Disables an interface to receive LLDP packets."""
337 1
        interface_ids = self._get_data(request)
338 1
        changed_interfaces = interface_ids
339 1
        error_list = []  # List of interfaces that were not activated.
340 1
        interface_ids = filter(None, interface_ids)
341 1
        interfaces = self._get_interfaces()
342 1
        if not interfaces:
343 1
            return jsonify("No interfaces were found."), 404
344 1
        interfaces = self._get_interfaces_dict(interfaces)
345 1
        for id_ in interface_ids:
346 1
            interface = interfaces.get(id_)
347 1
            if interface:
348 1
                interface.lldp = False
349
            else:
350 1
                error_list.append(id_)
351 1
        if not error_list:
352
353 1
            self.notify_lldp_change('disabled', changed_interfaces)
354 1
            return jsonify(
355
                "All the requested interfaces have been disabled."), 200
356
357
        # Return a list of interfaces that couldn't be disabled
358 1
        msg_error = "Some interfaces couldn't be found and deactivated: "
359 1
        return jsonify({msg_error:
360
                        error_list}), 400
361
362 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...
363
    def enable_lldp(self):
364
        """Enable an interface to receive LLDP packets."""
365 1
        interface_ids = self._get_data(request)
366 1
        changed_interfaces = interface_ids
367 1
        error_list = []  # List of interfaces that were not activated.
368 1
        interface_ids = filter(None, interface_ids)
369 1
        interfaces = self._get_interfaces()
370 1
        if not interfaces:
371 1
            return jsonify("No interfaces were found."), 404
372 1
        interfaces = self._get_interfaces_dict(interfaces)
373 1
        for id_ in interface_ids:
374 1
            interface = interfaces.get(id_)
375 1
            if interface:
376 1
                interface.lldp = True
377
            else:
378 1
                error_list.append(id_)
379 1
        if not error_list:
380 1
            self.notify_lldp_change('enabled', changed_interfaces)
381 1
            return jsonify(
382
                "All the requested interfaces have been enabled."), 200
383
384
        # Return a list of interfaces that couldn't be enabled
385 1
        msg_error = "Some interfaces couldn't be found and activated: "
386 1
        return jsonify({msg_error:
387
                        error_list}), 400
388