Passed
Push — master ( 836a42...e3800b )
by Vinicius
02:14 queued 13s
created

build.main.Main.disable_liveness()   A

Complexity

Conditions 3

Size

Total Lines 17
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 3.0261

Importance

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