Passed
Pull Request — master (#123)
by
unknown
12:46 queued 08:33
created

build.main.Main.on_switches_metadata_changed()   A

Complexity

Conditions 1

Size

Total Lines 5
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1.125

Importance

Changes 0
Metric Value
cc 1
eloc 4
nop 2
dl 0
loc 5
rs 10
c 0
b 0
f 0
ccs 2
cts 4
cp 0.5
crap 1.125
1
"""NApp responsible to discover new switches and hosts."""
2 1
import struct
3 1
from threading import Lock
4
5 1
import httpx
6 1
import tenacity
7 1
from napps.kytos.of_core.msg_prios import of_msg_prio
8 1
from napps.kytos.of_lldp import constants, settings
9 1
from napps.kytos.of_lldp.managers import LivenessManager, LoopManager
10 1
from napps.kytos.of_lldp.managers.loop_manager import LoopState
11 1
from napps.kytos.of_lldp.utils import (get_cookie, try_to_gen_intf_mac,
12
                                       update_flow)
13 1
from pyof.foundation.basic_types import DPID, UBInt32
14 1
from pyof.foundation.network_types import LLDP, VLAN, Ethernet, EtherType
15 1
from pyof.v0x04.common.action import ActionOutput as AO13
16 1
from pyof.v0x04.common.port import PortNo as Port13
17 1
from pyof.v0x04.controller2switch.packet_out import PacketOut as PO13
18 1
from tenacity import (retry, retry_if_exception_type, stop_after_attempt,
19
                      wait_combine, wait_fixed, wait_random)
20
21 1
from kytos.core import KytosEvent, KytosNApp, log, rest
22 1
from kytos.core.exceptions import KytosTagError
23 1
from kytos.core.helpers import alisten_to, listen_to
24 1
from kytos.core.link import Link
25 1
from kytos.core.rest_api import (HTTPException, JSONResponse, Request,
26
                                 aget_json_or_400, get_json_or_400)
27 1
from kytos.core.retry import before_sleep
28 1
from kytos.core.switch import Switch
29
30 1
from .controllers import LivenessController
31
32
33 1
class Main(KytosNApp):
34
    """Main OF_LLDP NApp Class."""
35
36 1
    def setup(self):
37
        """Make this NApp run in a loop."""
38 1
        self.vlan_id = None
39 1
        self.polling_time = settings.POLLING_TIME
40 1
        if hasattr(settings, "FLOW_VLAN_VID"):
41 1
            self.vlan_id = settings.FLOW_VLAN_VID
42 1
        self.liveness_dead_multipler = settings.LIVENESS_DEAD_MULTIPLIER
43 1
        self.execute_as_loop(self.polling_time)
44 1
        self.loop_manager = LoopManager(self.controller)
45 1
        self.dead_interval = self.polling_time * self.liveness_dead_multipler
46 1
        self.liveness_controller = self.get_liveness_controller()
47 1
        self.liveness_controller.bootstrap_indexes()
48 1
        self.liveness_manager = LivenessManager(self.controller)
49 1
        self._liveness_ops_lock = Lock()
50 1
        Link.register_status_func(f"{self.napp_id}_liveness",
51
                                  LivenessManager.link_status_hook_liveness)
52 1
        status_reason_func = LivenessManager.link_status_reason_hook_liveness
53 1
        Link.register_status_reason_func(f"{self.napp_id}_liveness",
54
                                         status_reason_func)
55 1
        self.table_group = {"base": 0}
56
57 1
    @staticmethod
58 1
    def get_liveness_controller() -> LivenessController:
59
        """Get LivenessController."""
60
        return LivenessController()
61
62 1
    def execute(self):
63
        """Send LLDP Packets every 'POLLING_TIME' seconds to all switches."""
64 1
        switches = list(self.controller.switches.values())
65 1
        for switch in switches:
66 1
            try:
67 1
                of_version = switch.connection.protocol.version
68
            except AttributeError:
69
                of_version = None
70
71 1
            if not switch.is_connected():
72
                continue
73
74 1
            if of_version == 0x04:
75 1
                port_type = UBInt32
76 1
                local_port = Port13.OFPP_LOCAL
77
            else:
78
                # skip the current switch with unsupported OF version
79
                continue
80
81 1
            interfaces = list(switch.interfaces.values())
82 1
            for interface in interfaces:
83
                # Interface marked to receive lldp packet
84
                # Only send LLDP packet to active interface
85 1
                if (not interface.lldp or not interface.is_active()
86
                   or not interface.is_enabled()):
87
                    continue
88
                # Avoid the interface that connects to the controller.
89 1
                if interface.port_number == local_port:
90
                    continue
91
92 1
                lldp = LLDP()
93 1
                lldp.chassis_id.sub_value = DPID(switch.dpid)
94 1
                lldp.port_id.sub_value = port_type(interface.port_number)
95
96 1
                src_addr = try_to_gen_intf_mac(interface.address, switch.id,
97
                                               interface.port_number)
98 1
                ethernet = Ethernet()
99 1
                ethernet.ether_type = EtherType.LLDP
100 1
                ethernet.source = src_addr
101 1
                ethernet.destination = constants.LLDP_MULTICAST_MAC
102 1
                ethernet.data = lldp.pack()
103
                # self.vlan_id == None will result in a packet with no VLAN.
104 1
                ethernet.vlans.append(VLAN(vid=self.vlan_id))
105
106 1
                packet_out = self._build_lldp_packet_out(
107
                                    of_version,
108
                                    interface.port_number, ethernet.pack())
109
110 1
                if packet_out is None:
111
                    continue
112
113 1
                event_out = KytosEvent(
114
                    name='kytos/of_lldp.messages.out.ofpt_packet_out',
115
                    priority=of_msg_prio(packet_out.header.message_type.value),
116
                    content={
117
                            'destination': switch.connection,
118
                            'message': packet_out})
119
120 1
                self.controller.buffers.msg_out.put(event_out)
121 1
                log.debug(
122
                    "Sending a LLDP PacketOut to the switch %s",
123
                    switch.dpid)
124
125 1
                msg = 'Switch: %s (%s)'
126 1
                msg += ' Interface: %s'
127 1
                msg += ' -- LLDP PacketOut --'
128 1
                msg += ' Ethernet: eth_type (%s) | src (%s) | dst (%s) /'
129 1
                msg += ' LLDP: Switch (%s) | portno (%s)'
130
131 1
                log.debug(
132
                    msg,
133
                    switch.connection, switch.dpid,
134
                    interface.id, ethernet.ether_type,
135
                    ethernet.source, ethernet.destination,
136
                    switch.dpid, interface.port_number)
137
138 1
        self.try_to_publish_stopped_loops()
139 1
        self.liveness_manager.reaper(self.dead_interval)
140
141 1
    def load_liveness(self) -> None:
142
        """Load liveness."""
143 1
        enabled_intf_ids = {
144
            intf["id"]
145
            for intf in self.liveness_controller.get_enabled_interfaces()
146
        }
147 1
        intfs_to_enable = [
148
            intf
149
            for intf in self._get_interfaces()
150
            if intf.id in enabled_intf_ids
151
        ]
152 1
        self.liveness_manager.enable(*intfs_to_enable)
153
154 1
    def try_to_publish_stopped_loops(self):
155
        """Try to publish current stopped loops."""
156
        for dpid, port_pairs in self.loop_manager.get_stopped_loops().items():
157
            try:
158
                switch = self.controller.get_switch_by_dpid(dpid)
159
                for port_pair in port_pairs:
160
                    interface_a = switch.interfaces[port_pair[0]]
161
                    interface_b = switch.interfaces[port_pair[1]]
162
                    self.loop_manager.publish_loop_state(
163
                        interface_a, interface_b, LoopState.stopped.value
164
                    )
165
            except (KeyError, AttributeError) as exc:
166
                log.error("try_to_publish_stopped_loops failed with switch:"
167
                          f"{dpid}, port_pair: {port_pair}. {str(exc)}")
168
169 1
    @listen_to('kytos/topology.switch.(enabled|disabled)')
170 1
    def handle_lldp_flows(self, event):
171
        """Install or remove flows in a switch.
172
173
        Install a flow to send LLDP packets to the controller. The proactive
174
        flow is installed whenever a switch is enabled. If the switch is
175
        disabled the flow is removed.
176
177
        Args:
178
            event (:class:`~kytos.core.events.KytosEvent`):
179
                Event with new switch information.
180
181
        """
182
        self._handle_lldp_flows(event)
183
184 1
    @alisten_to("kytos/of_lldp.loop.action.log")
185 1
    async def on_lldp_loop_log_action(self, event: KytosEvent):
186
        """Handle LLDP loop log action."""
187
        interface_a = event.content["interface_a"]
188
        interface_b = event.content["interface_b"]
189
        await self.loop_manager.handle_log_action(interface_a, interface_b)
190
191 1
    @alisten_to("kytos/of_lldp.loop.action.disable")
192 1
    async def on_lldp_loop_disable_action(self, event: KytosEvent):
193
        """Handle LLDP loop disable action."""
194
        interface_a = event.content["interface_a"]
195
        interface_b = event.content["interface_b"]
196
        await self.loop_manager.handle_disable_action(interface_a, interface_b)
197
198 1
    @alisten_to("kytos/of_lldp.loop.stopped")
199 1
    async def on_lldp_loop_stopped(self, event: KytosEvent):
200
        """Handle LLDP loop stopped."""
201
        dpid = event.content["dpid"]
202
        port_pair = event.content["port_numbers"]
203
        try:
204
            switch = self.controller.get_switch_by_dpid(dpid)
205
            interface_a = switch.interfaces[port_pair[0]]
206
            interface_b = switch.interfaces[port_pair[1]]
207
            await self.loop_manager.handle_loop_stopped(interface_a,
208
                                                        interface_b)
209
        except (KeyError, AttributeError) as exc:
210
            log.error("on_lldp_loop_stopped failed with: "
211
                      f"{event.content} {str(exc)}")
212
213 1
    @alisten_to("kytos/topology.topology_loaded")
214 1
    async def on_topology_loaded(self, event):
215
        """Handle on topology loaded."""
216 1
        topology = event.content["topology"]
217 1
        await self.loop_manager.handle_topology_loaded(topology)
218 1
        self.load_liveness()
219
220 1
    @listen_to("kytos/topology.switch.deleted")
221 1
    def handle_switch_deleted(self, event: KytosEvent) -> None:
222
        """Handle on switch deleted."""
223
        with self._liveness_ops_lock:
224
            self.on_switch_deleted(event)
225
226 1
    def on_switch_deleted(self, event: KytosEvent) -> None:
227
        """Handle on switch deleted."""
228 1
        switch = event.content["switch"]
229 1
        found_intfs = []
230 1
        for intf in list(switch.interfaces.values()):
231 1
            if intf.id in self.liveness_manager.interfaces:
232 1
                found_intfs.append(intf)
233 1
        if found_intfs:
234 1
            intf_ids = [intf.id for intf in found_intfs]
235 1
            log.info(
236
                f"Disabling liveness on {switch} with interfaces "
237
                f" deleted {intf_ids} "
238
            )
239 1
            self.liveness_manager.disable(*found_intfs)
240 1
            self.liveness_controller.delete_interfaces(intf_ids)
241
242 1
    @listen_to("kytos/topology.interface.deleted")
243 1
    def handle_interface_deleted(self, event: KytosEvent) -> None:
244
        """Handle on interface deleted."""
245
        with self._liveness_ops_lock:
246
            self.on_interface_deleted(event)
247
248 1
    def on_interface_deleted(self, event: KytosEvent) -> None:
249
        """Handle on interface deleted."""
250 1
        intf = event.content["interface"]
251 1
        if intf.id in self.liveness_manager.interfaces:
252 1
            log.info(f"Disabling liveness on {intf} deleted")
253 1
            self.liveness_manager.disable(intf)
254 1
            self.liveness_controller.delete_interface(intf.id)
255
256 1
    @alisten_to("kytos/topology.switches.metadata.(added|removed)")
257 1
    async def on_switches_metadata_changed(self, event):
258
        """Handle on switches metadata changed."""
259
        switch = event.content["switch"]
260
        await self.loop_manager.handle_switch_metadata_changed(switch)
261
262 1
    def _handle_lldp_flows(self, event):
263
        """Install or remove flows in a switch.
264
265
        Install a flow to send LLDP packets to the controller. The proactive
266
        flow is installed whenever a switch is enabled. If the switch is
267
        disabled the flow is removed.
268
        """
269 1
        try:
270 1
            dpid = event.content['dpid']
271 1
            switch = self.controller.get_switch_by_dpid(dpid)
272 1
            of_version = switch.connection.protocol.version
273
        except AttributeError:
274
            of_version = None
275
276 1
        try:
277 1
            installed_flows = self.get_flows_by_switch(switch.id)
278 1
        except tenacity.RetryError as err:
279 1
            msg = f"Error: {err.last_attempt.exception()} when "\
280
                   "obtaining flows."
281 1
            log.error(msg)
282 1
            return
283 1
        except ValueError as err:
284 1
            log.error(f"Error when getting flows, error: {err}")
285 1
            return
286
287 1
        flow = None
288 1
        if ("switch.enabled" in event.name and not installed_flows or
289
                "switch.disabled" in event.name and installed_flows):
290 1
            flow = self._build_lldp_flow(of_version, get_cookie(switch.dpid))
291
292 1
        if flow:
293 1
            data = {'flows': [flow]}
294 1
            try:
295 1
                self.send_flow(switch, event.name, data=data)
296 1
            except tenacity.RetryError as err:
297 1
                msg = f"Error: {err.last_attempt.exception()} when"\
298
                      f" sending flows to {switch.id}, {data}"
299 1
                log.error(msg)
300
301
    # pylint: disable=unexpected-keyword-arg
302 1
    @retry(
303
        stop=stop_after_attempt(3),
304
        wait=wait_combine(wait_fixed(3), wait_random(min=2, max=7)),
305
        before_sleep=before_sleep,
306
        retry=retry_if_exception_type(httpx.RequestError),
307
        after=update_flow(),
308
    )
309 1
    def send_flow(self, switch, event_name, data=None):
310
        """Send flows to flow_manager to be installed/deleted"""
311 1
        endpoint = f'{settings.FLOW_MANAGER_URL}/flows/{switch.id}'
312 1
        client_error = {424, 404, 400}
313 1
        if event_name == 'kytos/topology.switch.enabled':
314 1
            for flow in data['flows']:
315 1
                flow.pop("cookie_mask", None)
316 1
            res = httpx.post(endpoint, json=data, timeout=10)
317 1
            if res.is_server_error or res.status_code in client_error:
318 1
                raise httpx.RequestError(res.text)
319 1
            self.use_vlan(switch)
320
321 1
        elif event_name == 'kytos/topology.switch.disabled':
322 1
            res = httpx.request("DELETE", endpoint, json=data, timeout=10)
323 1
            if res.is_server_error or res.status_code in client_error:
324
                raise httpx.RequestError(res.text)
325 1
            self.make_vlan_available(switch)
326
327 1
    def use_vlan(self, switch: Switch) -> None:
328
        """Use vlan from interface"""
329 1
        if self.vlan_id is None:
330 1
            return
331 1
        for interface_id in switch.interfaces:
332 1
            interface = switch.interfaces[interface_id]
333 1
            try:
334 1
                interface.atomic_use_tags(
335
                    self.controller,
336
                    "vlan",
337
                    self.vlan_id
338
                )
339 1
            except KytosTagError as err:
340 1
                log.error(err)
341
342 1
    def make_vlan_available(self, switch: Switch) -> None:
343
        """Makes vlan from interface available"""
344 1
        if self.vlan_id is None:
345 1
            return
346 1
        for interface_id in switch.interfaces:
347 1
            interface = switch.interfaces[interface_id]
348 1
            try:
349 1
                conflict = interface.atomic_make_tags_available(
350
                    self.controller,
351
                    "vlan",
352
                    self.vlan_id
353
                )
354 1
                if conflict:
355 1
                    log.warning(f"Tags {conflict} was already available"
356
                                f" in {switch.id}:{interface_id}")
357 1
            except KytosTagError as err:
358 1
                log.error(err)
359
360 1
    @retry(
361
        stop=stop_after_attempt(3),
362
        wait=wait_combine(wait_fixed(3), wait_random(min=2, max=7)),
363
        before_sleep=before_sleep,
364
        retry=retry_if_exception_type(httpx.RequestError),
365
    )
366 1
    def get_flows_by_switch(self, dpid: str) -> dict:
367
        """Get of_lldp flows by switch"""
368 1
        start = settings.COOKIE_PREFIX << 56
369 1
        end = start | 0x00FFFFFFFFFFFFFF
370 1
        endpoint = f'{settings.FLOW_MANAGER_URL}/stored_flows?state='\
371
                   f'installed&cookie_range={start}&cookie_range={end}'\
372
                   f'&dpid={dpid}'
373 1
        res = httpx.get(endpoint)
374 1
        if res.is_server_error or res.status_code == 404:
375
            raise httpx.RequestError(res.text)
376 1
        if res.status_code == 400:
377 1
            raise ValueError(res.json()["description"])
378
        return res.json()
379
380 1
    @alisten_to('kytos/of_core.v0x04.messages.in.ofpt_packet_in')
381 1
    async def on_ofpt_packet_in(self, event):
382
        """Dispatch two KytosEvents to notify identified NNI interfaces.
383
384
        Args:
385
            event (:class:`~kytos.core.events.KytosEvent`):
386
                Event with an LLDP packet as data.
387
388
        """
389 1
        ethernet = self._unpack_non_empty(Ethernet, event.message.data)
390 1
        if ethernet.ether_type == EtherType.LLDP:
391 1
            try:
392 1
                lldp = self._unpack_non_empty(LLDP, ethernet.data)
393 1
                dpid = self._unpack_non_empty(DPID, lldp.chassis_id.sub_value)
394
            except struct.error:
395
                #: If we have a LLDP packet but we cannot unpack it, or the
396
                #: unpacked packet does not contain the dpid attribute, then
397
                #: we are dealing with a LLDP generated by someone else. Thus
398
                #: this packet is not useful for us and we may just ignore it.
399
                return
400
401 1
            switch_a = event.source.switch
402 1
            port_a = event.message.in_port
403 1
            switch_b = None
404 1
            port_b = None
405
406
            # in_port is currently an Int in v0x04.
407 1
            if isinstance(port_a, int):
408 1
                port_a = UBInt32(port_a)
409
410 1
            try:
411 1
                switch_b = self.controller.get_switch_by_dpid(dpid.value)
412 1
                port_type = UBInt32
413 1
                port_b = self._unpack_non_empty(port_type,
414
                                                lldp.port_id.sub_value)
415
            except AttributeError:
416
                log.debug("Couldn't find datapath %s.", dpid.value)
417
418
            # Return if any of the needed information are not available
419 1
            if not (switch_a and port_a and switch_b and port_b):
420
                return
421
422 1
            interface_a = switch_a.get_interface_by_port_no(port_a.value)
423 1
            interface_b = switch_b.get_interface_by_port_no(port_b.value)
424 1
            if not interface_a or not interface_b:
425 1
                return
426
427 1
            await self.loop_manager.process_if_looped(interface_a, interface_b)
428 1
            await self.liveness_manager.consume_hello_if_enabled(interface_a,
429
                                                                 interface_b)
430 1
            event_out = KytosEvent(name='kytos/of_lldp.interface.is.nni',
431
                                   content={'interface_a': interface_a,
432
                                            'interface_b': interface_b})
433 1
            await self.controller.buffers.app.aput(event_out)
434
435 1
    def notify_lldp_change(self, state, interface_ids):
436
        """Dispatch a KytosEvent to notify changes to the LLDP status."""
437 1
        content = {'attribute': 'LLDP',
438
                   'state': state,
439
                   'interface_ids': interface_ids}
440 1
        event_out = KytosEvent(name='kytos/of_lldp.network_status.updated',
441
                               content=content)
442 1
        self.controller.buffers.app.put(event_out)
443
444 1
    def publish_liveness_status(self, event_suffix, interfaces):
445
        """Dispatch a KytosEvent to publish liveness admin status."""
446 1
        content = {"interfaces": interfaces}
447 1
        name = f"kytos/of_lldp.liveness.{event_suffix}"
448 1
        event_out = KytosEvent(name=name, content=content)
449 1
        self.controller.buffers.app.put(event_out)
450
451 1
    def shutdown(self):
452
        """End of the application."""
453
        log.debug('Shutting down...')
454
455 1
    @staticmethod
456 1
    def _build_lldp_packet_out(version, port_number, data):
457
        """Build a LLDP PacketOut message.
458
459
        Args:
460
            version (int): OpenFlow version
461
            port_number (int): Switch port number where the packet must be
462
                forwarded to.
463
            data (bytes): Binary data to be sent through the port.
464
465
        Returns:
466
            PacketOut message for the specific given OpenFlow version, if it
467
                is supported.
468
            None if the OpenFlow version is not supported.
469
470
        """
471 1
        if version == 0x04:
472 1
            action_output_class = AO13
473 1
            packet_out_class = PO13
474
        else:
475 1
            log.info('Openflow version %s is not yet supported.', version)
476 1
            return None
477
478 1
        output_action = action_output_class()
479 1
        output_action.port = port_number
480
481 1
        packet_out = packet_out_class()
482 1
        packet_out.data = data
483 1
        packet_out.actions.append(output_action)
484
485 1
        return packet_out
486
487 1
    def _build_lldp_flow(self, version, cookie,
488
                         cookie_mask=0xffffffffffffffff):
489
        """Build a Flow message to send LLDP to the controller.
490
491
        Args:
492
            version (int): OpenFlow version.
493
494
        Returns:
495
            Flow dictionary message for the specific given OpenFlow version,
496
            if it is supported.
497
            None if the OpenFlow version is not supported.
498
499
        """
500 1
        flow = {}
501 1
        if version == 0x04:
502 1
            flow['actions'] = [{'action_type': 'output',
503
                                'port': Port13.OFPP_CONTROLLER}]
504
        else:
505 1
            return None
506
507 1
        match = {}
508 1
        self.set_flow_table_group_owner(flow)
509 1
        flow['priority'] = settings.FLOW_PRIORITY
510 1
        flow['cookie'] = cookie
511 1
        flow['cookie_mask'] = cookie_mask
512 1
        match['dl_type'] = EtherType.LLDP
513 1
        if self.vlan_id:
514 1
            match['dl_vlan'] = self.vlan_id
515 1
        flow['match'] = match
516
517 1
        return flow
518
519 1
    @staticmethod
520 1
    def _unpack_non_empty(desired_class, data):
521
        """Unpack data using an instance of desired_class.
522
523
        Args:
524
            desired_class (class): The class to be used to unpack data.
525
            data (bytes): bytes to be unpacked.
526
527
        Return:
528
            An instance of desired_class class with data unpacked into it.
529
530
        Raises:
531
            UnpackException if the unpack could not be performed.
532
533
        """
534 1
        obj = desired_class()
535
536 1
        if hasattr(data, 'value'):
537 1
            data = data.value
538
539 1
        obj.unpack(data)
540
541 1
        return obj
542
543 1
    def _get_data(self, request: Request) -> list:
544
        """Get request data."""
545 1
        data = get_json_or_400(request, self.controller.loop)
546 1
        return data.get('interfaces', [])
547
548 1
    def _get_interfaces(self):
549
        """Get all interfaces."""
550 1
        interfaces = []
551 1
        for switch in list(self.controller.switches.values()):
552 1
            interfaces += list(switch.interfaces.values())
553 1
        return interfaces
554
555 1
    @staticmethod
556 1
    def _get_interfaces_dict(interfaces):
557
        """Return a dict of interfaces."""
558 1
        return {inter.id: inter for inter in interfaces}
559
560 1
    def _get_lldp_interfaces(self):
561
        """Get interfaces enabled to receive LLDP packets."""
562 1
        return [inter.id for inter in self._get_interfaces() if inter.lldp]
563
564 1
    @rest('v1/interfaces', methods=['GET'])
565 1
    async def get_lldp_interfaces(self, _request: Request) -> JSONResponse:
566
        """Return all the interfaces that have LLDP traffic enabled."""
567 1
        return JSONResponse({"interfaces": self._get_lldp_interfaces()})
568
569 1
    @rest('v1/interfaces/disable', methods=['POST'])
570 1
    def disable_lldp(self, request: Request) -> JSONResponse:
571
        """Disables an interface to receive LLDP packets."""
572 1
        interface_ids = self._get_data(request)
573 1
        error_list = []  # List of interfaces that were not activated.
574 1
        changed_interfaces = []
575 1
        interface_ids = filter(None, interface_ids)
576 1
        interfaces = self._get_interfaces()
577 1
        intfs = []
578 1
        if not interfaces:
579
            raise HTTPException(404, detail="No interfaces were found.")
580 1
        interfaces = self._get_interfaces_dict(interfaces)
581 1
        with self._liveness_ops_lock:
582 1
            for id_ in interface_ids:
583 1
                interface = interfaces.get(id_)
584 1
                if interface:
585 1
                    interface.lldp = False
586 1
                    changed_interfaces.append(id_)
587 1
                    intfs.append(interface)
588
                else:
589 1
                    error_list.append(id_)
590 1
            if changed_interfaces:
591 1
                self.notify_lldp_change('disabled', changed_interfaces)
592 1
                intf_ids = [intf.id for intf in intfs]
593 1
                self.liveness_controller.disable_interfaces(intf_ids)
594 1
                self.liveness_manager.disable(*intfs)
595 1
                self.publish_liveness_status("disabled", intfs)
596 1
        if not error_list:
597 1
            return JSONResponse(
598
                "All the requested interfaces have been disabled.")
599
600
        # Return a list of interfaces that couldn't be disabled
601 1
        msg_error = "Some interfaces couldn't be found and deactivated: "
602 1
        return JSONResponse({msg_error: error_list}, status_code=400)
603
604 1
    @rest('v1/interfaces/enable', methods=['POST'])
605 1
    def enable_lldp(self, request: Request) -> JSONResponse:
606
        """Enable an interface to receive LLDP packets."""
607 1
        interface_ids = self._get_data(request)
608 1
        error_list = []  # List of interfaces that were not activated.
609 1
        changed_interfaces = []
610 1
        interface_ids = filter(None, interface_ids)
611 1
        interfaces = self._get_interfaces()
612 1
        if not interfaces:
613
            raise HTTPException(404, detail="No interfaces were found.")
614 1
        interfaces = self._get_interfaces_dict(interfaces)
615 1
        with self._liveness_ops_lock:
616 1
            for id_ in interface_ids:
617 1
                interface = interfaces.get(id_)
618 1
                if interface:
619 1
                    interface.lldp = True
620 1
                    changed_interfaces.append(id_)
621
                else:
622 1
                    error_list.append(id_)
623 1
            if changed_interfaces:
624 1
                self.notify_lldp_change('enabled', changed_interfaces)
625 1
        if not error_list:
626 1
            return JSONResponse(
627
                "All the requested interfaces have been enabled.")
628
629
        # Return a list of interfaces that couldn't be enabled
630 1
        msg_error = "Some interfaces couldn't be found and activated: "
631 1
        return JSONResponse({msg_error: error_list}, status_code=400)
632
633 1
    @rest("v1/liveness/enable", methods=["POST"])
634 1
    def enable_liveness(self, request: Request) -> JSONResponse:
635
        """Enable liveness link detection on interfaces."""
636 1
        intf_ids = self._get_data(request)
637 1
        if not intf_ids:
638
            raise HTTPException(400, "Interfaces payload is empty")
639 1
        interfaces = {intf.id: intf for intf in self._get_interfaces()}
640 1
        diff = set(intf_ids) - set(interfaces.keys())
641 1
        if diff:
642
            raise HTTPException(404, f"Interface IDs {diff} not found")
643
644 1
        intfs = [interfaces[_id] for _id in intf_ids]
645 1
        with self._liveness_ops_lock:
646 1
            non_lldp = [intf.id for intf in intfs if not intf.lldp]
647 1
            if non_lldp:
648
                msg = f"Interface IDs {non_lldp} don't have LLDP enabled"
649
                raise HTTPException(400, msg)
650 1
            self.liveness_controller.enable_interfaces(intf_ids)
651 1
            self.liveness_manager.enable(*intfs)
652 1
            self.publish_liveness_status("enabled", intfs)
653 1
        return JSONResponse({})
654
655 1
    @rest("v1/liveness/disable", methods=["POST"])
656 1
    def disable_liveness(self, request: Request) -> JSONResponse:
657
        """Disable liveness link detection on interfaces."""
658 1
        intf_ids = self._get_data(request)
659 1
        if not intf_ids:
660
            raise HTTPException(400, "Interfaces payload is empty")
661
662 1
        interfaces = {intf.id: intf for intf in self._get_interfaces()}
663 1
        diff = set(intf_ids) - set(interfaces.keys())
664 1
        if diff:
665
            raise HTTPException(404, f"Interface IDs {diff} not found")
666
667 1
        intfs = [interfaces[_id] for _id in intf_ids if _id in interfaces]
668 1
        with self._liveness_ops_lock:
669 1
            self.liveness_controller.disable_interfaces(intf_ids)
670 1
            self.liveness_manager.disable(*intfs)
671 1
            self.publish_liveness_status("disabled", intfs)
672 1
        return JSONResponse({})
673
674 1
    @rest("v1/liveness/", methods=["GET"])
675 1
    async def get_liveness_interfaces(self, request: Request) -> JSONResponse:
676
        """Get liveness interfaces."""
677 1
        args = request.query_params
678 1
        interface_id = args.get("interface_id")
679 1
        if interface_id:
680
            status, last_hello_at = self.liveness_manager.get_interface_status(
681
                interface_id
682
            )
683
            if not status:
684
                return {"interfaces": []}, 200
685
            body = {
686
                "interfaces": [
687
                    {
688
                        "id": interface_id,
689
                        "status": status,
690
                        "last_hello_at": last_hello_at,
691
                    }
692
                ]
693
            }
694
            return JSONResponse(body)
695 1
        interfaces = []
696 1
        for interface_id in list(self.liveness_manager.interfaces.keys()):
697
            status, last_hello_at = self.liveness_manager.get_interface_status(
698
                interface_id
699
            )
700
            interfaces.append({"id": interface_id, "status": status,
701
                              "last_hello_at": last_hello_at})
702 1
        return JSONResponse({"interfaces": interfaces})
703
704 1
    @rest("v1/liveness/pair", methods=["GET"])
705 1
    async def get_liveness_interface_pairs(self,
706
                                           _request: Request) -> JSONResponse:
707
        """Get liveness interface pairs."""
708 1
        pairs = []
709 1
        for entry in list(self.liveness_manager.liveness.values()):
710
            lsm = entry["lsm"]
711
            link = entry["interface_a"].link
712
            pair = {
713
                "interface_a": {
714
                    "id": entry["interface_a"].id,
715
                    "status": lsm.ilsm_a.state,
716
                    "last_hello_at": lsm.ilsm_a.last_hello_at,
717
                },
718
                "interface_b": {
719
                    "id": entry["interface_b"].id,
720
                    "status": lsm.ilsm_b.state,
721
                    "last_hello_at": lsm.ilsm_b.last_hello_at,
722
                },
723
                "link_id": link.id if link else None,
724
                "status": lsm.state
725
            }
726
            pairs.append(pair)
727 1
        return JSONResponse({"pairs": pairs})
728
729 1
    @rest('v1/polling_time', methods=['GET'])
730 1
    async def get_time(self, _request: Request) -> JSONResponse:
731
        """Get LLDP polling time in seconds."""
732 1
        return JSONResponse({"polling_time": self.polling_time})
733
734 1
    @rest('v1/polling_time', methods=['POST'])
735 1
    async def set_time(self, request: Request) -> JSONResponse:
736
        """Set LLDP polling time."""
737
        # pylint: disable=attribute-defined-outside-init
738 1
        try:
739 1
            payload = await aget_json_or_400(request)
740 1
            polling_time = int(payload['polling_time'])
741 1
            if polling_time <= 0:
742
                msg = f"invalid polling_time {polling_time}, " \
743
                        "must be greater than zero"
744
                raise HTTPException(400, detail=msg)
745 1
            self.polling_time = polling_time
746 1
            self.execute_as_loop(self.polling_time)
747 1
            log.info("Polling time has been updated to %s"
748
                     " second(s), but this change will not be saved"
749
                     " permanently.", self.polling_time)
750 1
            return JSONResponse("Polling time has been updated.")
751 1
        except (ValueError, KeyError) as error:
752 1
            msg = f"This operation is not completed: {error}"
753 1
            raise HTTPException(400, detail=msg) from error
754
755 1
    def set_flow_table_group_owner(self,
756
                                   flow: dict,
757
                                   group: str = "base") -> dict:
758
        """Set owner, table_group and table_id"""
759 1
        flow["table_id"] = self.table_group[group]
760 1
        flow["owner"] = "of_lldp"
761 1
        flow["table_group"] = group
762 1
        return flow
763
764
    # pylint: disable=attribute-defined-outside-init
765 1
    @alisten_to("kytos/of_multi_table.enable_table")
766 1
    async def on_table_enabled(self, event):
767
        """Handle a recently table enabled.
768
        of_lldp only allows "base" as flow group
769
        """
770 1
        table_group = event.content.get("of_lldp", None)
771 1
        if not table_group:
772
            return
773 1
        for group in table_group:
774 1
            if group not in settings.TABLE_GROUP_ALLOWED:
775 1
                log.error(f'The table group "{group}" is not allowed for '
776
                          f'of_lldp. Allowed table groups are '
777
                          f'{settings.TABLE_GROUP_ALLOWED}')
778 1
                return
779 1
        self.table_group.update(table_group)
780 1
        content = {"group_table": self.table_group}
781 1
        event_out = KytosEvent(name="kytos/of_lldp.enable_table",
782
                               content=content)
783
        await self.controller.buffers.app.aput(event_out)
784