Passed
Push — master ( c00de3...bc1c3d )
by Humberto
01:15 queued 11s
created

build.main.Main.get_time()   A

Complexity

Conditions 1

Size

Total Lines 4
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 3
nop 1
dl 0
loc 4
rs 10
c 0
b 0
f 0
ccs 2
cts 2
cp 1
crap 1
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
        self.polling_time = settings.POLLING_TIME
31 1
        if hasattr(settings, "FLOW_VLAN_VID"):
32 1
            self.vlan_id = settings.FLOW_VLAN_VID
33 1
        self.execute_as_loop(self.polling_time)
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 = '\n'
98 1
                msg += 'Switch: %s (%s)\n'
99 1
                msg += ' Interfaces: %s\n'
100 1
                msg += ' -- LLDP PacketOut --\n'
101 1
                msg += ' Ethernet: eth_type (%s) | src (%s) | dst (%s)'
102 1
                msg += '\n'
103 1
                msg += ' LLDP: Switch (%s) | port (%s)'
104
105 1
                log.debug(
106
                    msg,
107
                    switch.connection.address, switch.dpid,
108
                    switch.interfaces, ethernet.ether_type,
109
                    ethernet.source, ethernet.destination,
110
                    switch.dpid, interface.port_number)
111
112 1
    @listen_to('kytos/of_core.handshake.completed')
113
    def install_lldp_flow(self, event):
114
        """Install a flow to send LLDP packets to the controller.
115
116
        The proactive flow is installed whenever a switch connects.
117
118
        Args:
119
            event (:class:`~kytos.core.events.KytosEvent`):
120
                Event with new switch information.
121
122
        """
123 1
        try:
124 1
            of_version = event.content['switch'].connection.protocol.version
125 1
        except AttributeError:
126 1
            of_version = None
127
128 1
        flow_mod = self._build_lldp_flow_mod(of_version)
129
130 1
        if flow_mod:
131 1
            name = 'kytos/of_lldp.messages.out.ofpt_flow_mod'
132 1
            content = {'destination': event.content['switch'].connection,
133
                       'message': flow_mod}
134
135 1
            event_out = KytosEvent(name=name, content=content)
136 1
            self.controller.buffers.msg_out.put(event_out)
137
138 1
    @listen_to('kytos/of_core.v0x0[14].messages.in.ofpt_packet_in')
139
    def notify_uplink_detected(self, event):
140
        """Dispatch two KytosEvents to notify identified NNI interfaces.
141
142
        Args:
143
            event (:class:`~kytos.core.events.KytosEvent`):
144
                Event with an LLDP packet as data.
145
146
        """
147 1
        ethernet = self._unpack_non_empty(Ethernet, event.message.data)
148 1
        if ethernet.ether_type == EtherType.LLDP:
149 1
            try:
150 1
                lldp = self._unpack_non_empty(LLDP, ethernet.data)
151 1
                dpid = self._unpack_non_empty(DPID, lldp.chassis_id.sub_value)
152
            except struct.error:
153
                #: If we have a LLDP packet but we cannot unpack it, or the
154
                #: unpacked packet does not contain the dpid attribute, then
155
                #: we are dealing with a LLDP generated by someone else. Thus
156
                #: this packet is not useful for us and we may just ignore it.
157
                return
158
159 1
            switch_a = event.source.switch
160 1
            port_a = event.message.in_port
161 1
            switch_b = None
162 1
            port_b = None
163
164
            # in_port is currently a UBInt16 in v0x01 and an Int in v0x04.
165 1
            if isinstance(port_a, int):
166 1
                port_a = UBInt32(port_a)
167
168 1
            try:
169 1
                switch_b = self.controller.get_switch_by_dpid(dpid.value)
170 1
                of_version = switch_b.connection.protocol.version
171 1
                port_type = UBInt16 if of_version == 0x01 else UBInt32
172 1
                port_b = self._unpack_non_empty(port_type,
173
                                                lldp.port_id.sub_value)
174
            except AttributeError:
175
                log.debug("Couldn't find datapath %s.", dpid.value)
176
177
            # Return if any of the needed information are not available
178 1
            if not (switch_a and port_a and switch_b and port_b):
179
                return
180
181 1
            interface_a = switch_a.get_interface_by_port_no(port_a.value)
182 1
            interface_b = switch_b.get_interface_by_port_no(port_b.value)
183
184 1
            event_out = KytosEvent(name='kytos/of_lldp.interface.is.nni',
185
                                   content={'interface_a': interface_a,
186
                                            'interface_b': interface_b})
187 1
            self.controller.buffers.app.put(event_out)
188
189 1
    def shutdown(self):
190
        """End of the application."""
191
        log.debug('Shutting down...')
192
193 1
    @staticmethod
194
    def _build_lldp_packet_out(version, port_number, data):
195
        """Build a LLDP PacketOut message.
196
197
        Args:
198
            version (int): OpenFlow version
199
            port_number (int): Switch port number where the packet must be
200
                forwarded to.
201
            data (bytes): Binary data to be sent through the port.
202
203
        Returns:
204
            PacketOut message for the specific given OpenFlow version, if it
205
                is supported.
206
            None if the OpenFlow version is not supported.
207
208
        """
209 1
        if version == 0x01:
210 1
            action_output_class = AO10
211 1
            packet_out_class = PO10
212 1
        elif version == 0x04:
213 1
            action_output_class = AO13
214 1
            packet_out_class = PO13
215
        else:
216 1
            log.info('Openflow version %s is not yet supported.', version)
217 1
            return None
218
219 1
        output_action = action_output_class()
220 1
        output_action.port = port_number
221
222 1
        packet_out = packet_out_class()
223 1
        packet_out.data = data
224 1
        packet_out.actions.append(output_action)
225
226 1
        return packet_out
227
228 1
    def _build_lldp_flow_mod(self, version):
229
        """Build a FlodMod message to send LLDP to the controller.
230
231
        Args:
232
            version (int): OpenFlow version.
233
234
        Returns:
235
            FlowMod message for the specific given OpenFlow version, if it is
236
                supported.
237
            None if the OpenFlow version is not supported.
238
239
        """
240 1
        if version == 0x01:
241 1
            flow_mod = FM10()
242 1
            flow_mod.command = FMC.OFPFC_ADD
243 1
            flow_mod.priority = settings.FLOW_PRIORITY
244 1
            flow_mod.match.dl_type = EtherType.LLDP
245 1
            if self.vlan_id:
246 1
                flow_mod.match.dl_vlan = self.vlan_id
247 1
            flow_mod.actions.append(AO10(port=Port10.OFPP_CONTROLLER))
248
249 1
        elif version == 0x04:
250 1
            flow_mod = FM13()
251 1
            flow_mod.command = FMC.OFPFC_ADD
252 1
            flow_mod.priority = settings.FLOW_PRIORITY
253
254 1
            match_lldp = OxmTLV()
255 1
            match_lldp.oxm_field = OxmOfbMatchField.OFPXMT_OFB_ETH_TYPE
256 1
            match_lldp.oxm_value = EtherType.LLDP.to_bytes(2, 'big')
257 1
            flow_mod.match.oxm_match_fields.append(match_lldp)
258
259 1
            if self.vlan_id:
260 1
                match_vlan = OxmTLV()
261 1
                match_vlan.oxm_field = OxmOfbMatchField.OFPXMT_OFB_VLAN_VID
262 1
                vlan_value = self.vlan_id | VlanId.OFPVID_PRESENT
263 1
                match_vlan.oxm_value = vlan_value.to_bytes(2, 'big')
264 1
                flow_mod.match.oxm_match_fields.append(match_vlan)
265
266 1
            instruction = InstructionApplyAction()
267 1
            instruction.actions.append(AO13(port=Port13.OFPP_CONTROLLER))
268 1
            flow_mod.instructions.append(instruction)
269
270
        else:
271 1
            flow_mod = None
272
273 1
        return flow_mod
274
275 1
    @staticmethod
276
    def _unpack_non_empty(desired_class, data):
277
        """Unpack data using an instance of desired_class.
278
279
        Args:
280
            desired_class (class): The class to be used to unpack data.
281
            data (bytes): bytes to be unpacked.
282
283
        Return:
284
            An instance of desired_class class with data unpacked into it.
285
286
        Raises:
287
            UnpackException if the unpack could not be performed.
288
289
        """
290 1
        obj = desired_class()
291
292 1
        if hasattr(data, 'value'):
293 1
            data = data.value
294
295 1
        obj.unpack(data)
296
297 1
        return obj
298
299 1
    @staticmethod
300
    def _get_data(req):
301
        """Get request data."""
302 1
        data = req.get_json()  # Valid format { "interfaces": [...] }
303 1
        return data.get('interfaces', [])
304
305 1
    def _get_interfaces(self):
306
        """Get all interfaces."""
307 1
        interfaces = []
308 1
        for switch in list(self.controller.switches.values()):
309 1
            interfaces += list(switch.interfaces.values())
310 1
        return interfaces
311
312 1
    @staticmethod
313
    def _get_interfaces_dict(interfaces):
314
        """Return a dict of interfaces."""
315 1
        return {inter.id: inter for inter in interfaces}
316
317 1
    def _get_lldp_interfaces(self):
318
        """Get interfaces enabled to receive LLDP packets."""
319 1
        return [inter.id for inter in self._get_interfaces() if inter.lldp]
320
321 1
    @rest('v1/interfaces', methods=['GET'])
322
    def get_lldp_interfaces(self):
323
        """Return all the interfaces that have LLDP traffic enabled."""
324 1
        return jsonify({"interfaces": self._get_lldp_interfaces()}), 200
325
326 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...
327
    def disable_lldp(self):
328
        """Disables an interface to receive LLDP packets."""
329 1
        interface_ids = self._get_data(request)
330 1
        error_list = []  # List of interfaces that were not activated.
331 1
        interface_ids = filter(None, interface_ids)
332 1
        interfaces = self._get_interfaces()
333 1
        if not interfaces:
334 1
            return jsonify("No interfaces were found."), 404
335 1
        interfaces = self._get_interfaces_dict(interfaces)
336 1
        for id_ in interface_ids:
337 1
            interface = interfaces.get(id_)
338 1
            if interface:
339 1
                interface.lldp = False
340
            else:
341 1
                error_list.append(id_)
342 1
        if not error_list:
343 1
            return jsonify(
344
                "All the requested interfaces have been disabled."), 200
345
346
        # Return a list of interfaces that couldn't be disabled
347 1
        msg_error = "Some interfaces couldn't be found and deactivated: "
348 1
        return jsonify({msg_error:
349
                        error_list}), 400
350
351 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...
352
    def enable_lldp(self):
353
        """Enable an interface to receive LLDP packets."""
354 1
        interface_ids = self._get_data(request)
355 1
        error_list = []  # List of interfaces that were not activated.
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 = True
365
            else:
366 1
                error_list.append(id_)
367 1
        if not error_list:
368 1
            return jsonify(
369
                "All the requested interfaces have been enabled."), 200
370
371
        # Return a list of interfaces that couldn't be enabled
372 1
        msg_error = "Some interfaces couldn't be found and activated: "
373 1
        return jsonify({msg_error:
374
                        error_list}), 400
375
376 1
    @rest('v1/polling_time', methods=['GET'])
377
    def get_time(self):
378
        """Get LLDP polling time in seconds."""
379 1
        return jsonify({"polling_time": self.polling_time}), 200
380
381 1
    @rest('v1/polling_time', methods=['POST'])
382
    def set_time(self):
383
        """Set LLDP polling time."""
384
        # pylint: disable=attribute-defined-outside-init
385 1
        try:
386 1
            payload = request.get_json()
387 1
            self.polling_time = abs(int(payload['polling_time']))
388 1
            self.execute_as_loop(self.polling_time)
389 1
            log.info("Polling time has been updated to %s"
390
                     " second(s), but this change will not be saved"
391
                     " permanently.", self.polling_time)
392 1
            return jsonify("Polling time has been updated."), 200
393 1
        except (ValueError, KeyError) as error:
394 1
            msg = f"This operation is not completed: {error}"
395
            return jsonify(msg), 400
396