Test Failed
Pull Request — master (#95)
by
unknown
02:42
created

build.main.Main.send_flow()   A

Complexity

Conditions 5

Size

Total Lines 20
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 5.0073

Importance

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