Passed
Push — master ( 33e026...27d34c )
by Vinicius
21:02 queued 19:15
created

build.main.Main.set_time()   A

Complexity

Conditions 3

Size

Total Lines 20
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 3.0213

Importance

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