Passed
Pull Request — master (#32)
by
unknown
02:46
created

build.main.Main.disable_lldp()   A

Complexity

Conditions 5

Size

Total Lines 17
Code Lines 16

Duplication

Lines 17
Ratio 100 %

Code Coverage

Tests 0
CRAP Score 30

Importance

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