Test Failed
Pull Request — master (#56)
by Vinicius
07:13
created

build.main.Main.load_liveness()   A

Complexity

Conditions 1

Size

Total Lines 6
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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