Passed
Pull Request — master (#78)
by Vinicius
06:02
created

build.main.Main._build_lldp_flow()   A

Complexity

Conditions 3

Size

Total Lines 31
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 3

Importance

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