Test Failed
Pull Request — master (#88)
by Vinicius
02:33
created

build.main.Main.set_flow_table_group_owner()   A

Complexity

Conditions 1

Size

Total Lines 8
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 7
nop 3
dl 0
loc 8
rs 10
c 0
b 0
f 0
ccs 5
cts 5
cp 1
crap 1
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, UBInt32
8 1
from pyof.foundation.network_types import LLDP, VLAN, Ethernet, EtherType
9 1
from pyof.v0x04.common.action import ActionOutput as AO13
10 1
from pyof.v0x04.common.port import PortNo as Port13
11 1
from pyof.v0x04.controller2switch.packet_out import PacketOut as PO13
12 1
13 1
from kytos.core import KytosEvent, KytosNApp, log, rest
14 1
from kytos.core.helpers import alisten_to, listen_to
15 1
from kytos.core.link import Link
16
from napps.kytos.of_core.msg_prios import of_msg_prio
17 1
from napps.kytos.of_lldp import constants, settings
18 1
from napps.kytos.of_lldp.managers import LivenessManager, LoopManager
19 1
from napps.kytos.of_lldp.managers.loop_manager import LoopState
20 1
from napps.kytos.of_lldp.utils import get_cookie, try_to_gen_intf_mac
21
22
from .controllers import LivenessController
23 1
24
25
class Main(KytosNApp):
26 1
    """Main OF_LLDP NApp Class."""
27
28
    def setup(self):
29 1
        """Make this NApp run in a loop."""
30
        self.vlan_id = None
31 1
        self.polling_time = settings.POLLING_TIME
32 1
        if hasattr(settings, "FLOW_VLAN_VID"):
33 1
            self.vlan_id = settings.FLOW_VLAN_VID
34 1
        self.liveness_dead_multipler = settings.LIVENESS_DEAD_MULTIPLIER
35 1
        self.execute_as_loop(self.polling_time)
36 1
        self.loop_manager = LoopManager(self.controller)
37 1
        self.dead_interval = self.polling_time * self.liveness_dead_multipler
38 1
        self.liveness_controller = self.get_liveness_controller()
39 1
        self.liveness_controller.bootstrap_indexes()
40 1
        self.liveness_manager = LivenessManager(self.controller)
41 1
        Link.register_status_func(f"{self.napp_id}_liveness",
42 1
                                  LivenessManager.link_status_hook_liveness)
43
44 1
    @staticmethod
45
    def get_liveness_controller() -> LivenessController:
46 1
        """Get LivenessController."""
47 1
        return LivenessController()
48
49
    def execute(self):
50
        """Send LLDP Packets every 'POLLING_TIME' seconds to all switches."""
51 1
        switches = list(self.controller.switches.values())
52
        for switch in switches:
53 1
            try:
54 1
                of_version = switch.connection.protocol.version
55 1
            except AttributeError:
56 1
                of_version = None
57
58
            if not switch.is_connected():
59
                continue
60 1
61
            if of_version == 0x04:
62
                port_type = UBInt32
63 1
                local_port = Port13.OFPP_LOCAL
64 1
            else:
65 1
                # skip the current switch with unsupported OF version
66
                continue
67
68
            interfaces = list(switch.interfaces.values())
69
            for interface in interfaces:
70 1
                # Interface marked to receive lldp packet
71 1
                # Only send LLDP packet to active interface
72
                if(not interface.lldp or not interface.is_active()
73
                   or not interface.is_enabled()):
74 1
                    continue
75
                # Avoid the interface that connects to the controller.
76
                if interface.port_number == local_port:
77
                    continue
78 1
79
                lldp = LLDP()
80
                lldp.chassis_id.sub_value = DPID(switch.dpid)
81 1
                lldp.port_id.sub_value = port_type(interface.port_number)
82 1
83 1
                src_addr = try_to_gen_intf_mac(interface.address, switch.id,
84
                                               interface.port_number)
85 1
                ethernet = Ethernet()
86 1
                ethernet.ether_type = EtherType.LLDP
87 1
                ethernet.source = src_addr
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
        match = {}
396 1
        flow['priority'] = settings.FLOW_PRIORITY
397
        flow['table_id'] = settings.TABLE_ID
398
        flow['cookie'] = cookie
399 1
        flow['cookie_mask'] = cookie_mask
400
        match['dl_type'] = EtherType.LLDP
401 1
        if self.vlan_id:
402 1
            match['dl_vlan'] = self.vlan_id
403 1
        flow['match'] = match
404 1
405 1
        if version == 0x04:
406 1
            flow['actions'] = [{'action_type': 'output',
407 1
                                'port': Port13.OFPP_CONTROLLER}]
408 1
        else:
409 1
            flow = None
410
411 1
        return flow
412
413 1
    @staticmethod
414 1
    def _unpack_non_empty(desired_class, data):
415
        """Unpack data using an instance of desired_class.
416
417
        Args:
418
            desired_class (class): The class to be used to unpack data.
419
            data (bytes): bytes to be unpacked.
420
421
        Return:
422
            An instance of desired_class class with data unpacked into it.
423
424
        Raises:
425
            UnpackException if the unpack could not be performed.
426
427
        """
428 1
        obj = desired_class()
429
430 1
        if hasattr(data, 'value'):
431 1
            data = data.value
432
433 1
        obj.unpack(data)
434
435 1
        return obj
436
437 1
    @staticmethod
438
    def _get_data(req):
439 1
        """Get request data."""
440 1
        data = req.get_json()  # Valid format { "interfaces": [...] }
441
        return data.get('interfaces', [])
442 1
443
    def _get_interfaces(self):
444 1
        """Get all interfaces."""
445 1
        interfaces = []
446 1
        for switch in list(self.controller.switches.values()):
447 1
            interfaces += list(switch.interfaces.values())
448
        return interfaces
449 1
450 1
    @staticmethod
451
    def _get_interfaces_dict(interfaces):
452 1
        """Return a dict of interfaces."""
453
        return {inter.id: inter for inter in interfaces}
454 1
455
    def _get_lldp_interfaces(self):
456 1
        """Get interfaces enabled to receive LLDP packets."""
457
        return [inter.id for inter in self._get_interfaces() if inter.lldp]
458 1
459 1
    @rest('v1/interfaces', methods=['GET'])
460
    def get_lldp_interfaces(self):
461 1
        """Return all the interfaces that have LLDP traffic enabled."""
462
        return jsonify({"interfaces": self._get_lldp_interfaces()}), 200
463 1
464 1
    @rest('v1/interfaces/disable', methods=['POST'])
465
    def disable_lldp(self):
466 1
        """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
        if not interfaces:
474 1
            return jsonify("No interfaces were found."), 404
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
                intfs.append(interface)
482 1
            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
            return jsonify(
492
                "All the requested interfaces have been disabled."), 200
493
494 1
        # Return a list of interfaces that couldn't be disabled
495 1
        msg_error = "Some interfaces couldn't be found and deactivated: "
496
        return jsonify({msg_error:
497 1
                        error_list}), 400
498 1
499
    @rest('v1/interfaces/enable', methods=['POST'])
500 1
    def enable_lldp(self):
501 1
        """Enable an interface to receive LLDP packets."""
502 1
        interface_ids = self._get_data(request)
503 1
        error_list = []  # List of interfaces that were not activated.
504 1
        changed_interfaces = []
505 1
        interface_ids = filter(None, interface_ids)
506
        interfaces = self._get_interfaces()
507 1
        if not interfaces:
508 1
            return jsonify("No interfaces were found."), 404
509 1
        interfaces = self._get_interfaces_dict(interfaces)
510 1
        for id_ in interface_ids:
511 1
            interface = interfaces.get(id_)
512 1
            if interface:
513
                interface.lldp = True
514 1
                changed_interfaces.append(id_)
515 1
            else:
516 1
                error_list.append(id_)
517 1
        if changed_interfaces:
518 1
            self.notify_lldp_change('enabled', changed_interfaces)
519
        if not error_list:
520
            return jsonify(
521
                "All the requested interfaces have been enabled."), 200
522 1
523 1
        # Return a list of interfaces that couldn't be enabled
524
        msg_error = "Some interfaces couldn't be found and activated: "
525 1
        return jsonify({msg_error:
526 1
                        error_list}), 400
527
528 1
    @rest("v1/liveness/enable", methods=["POST"])
529 1
    def enable_liveness(self):
530
        """Enable liveness link detection on interfaces."""
531 1
        intf_ids = self._get_data(request)
532 1
        if not intf_ids:
533 1
            return jsonify("Interfaces payload is empty"), 400
534
        interfaces = {intf.id: intf for intf in self._get_interfaces()}
535
        diff = set(intf_ids) - set(interfaces.keys())
536 1
        if diff:
537 1
            return jsonify(f"Interface IDs {diff} not found"), 404
538 1
539
        intfs = [interfaces[_id] for _id in intf_ids]
540
        non_lldp = [intf.id for intf in intfs if not intf.lldp]
541 1
        if non_lldp:
542 1
            msg = f"Interface IDs {non_lldp} don't have LLDP enabled"
543 1
            return jsonify(msg), 400
544 1
        self.liveness_controller.enable_interfaces(intf_ids)
545
        self.liveness_manager.enable(*intfs)
546 1
        self.publish_liveness_status("enabled", intfs)
547 1
        return jsonify(), 200
548
549 1
    @rest("v1/liveness/disable", methods=["POST"])
550 1
    def disable_liveness(self):
551
        """Disable liveness link detection on interfaces."""
552
        intf_ids = self._get_data(request)
553 1
        if not intf_ids:
554 1
            return jsonify("Interfaces payload is empty"), 400
555 1
556
        interfaces = {intf.id: intf for intf in self._get_interfaces()}
557
        diff = set(intf_ids) - set(interfaces.keys())
558 1
        if diff:
559 1
            return jsonify(f"Interface IDs {diff} not found"), 404
560 1
561 1
        intfs = [interfaces[_id] for _id in intf_ids if _id in interfaces]
562 1
        self.liveness_controller.disable_interfaces(intf_ids)
563
        self.liveness_manager.disable(*intfs)
564 1
        self.publish_liveness_status("disabled", intfs)
565 1
        return jsonify(), 200
566
567 1
    @rest("v1/liveness/", methods=["GET"])
568 1
    def get_liveness_interfaces(self):
569 1
        """Get liveness interfaces."""
570
        args = request.args
571
        interface_id = args.get("interface_id")
572
        if interface_id:
573
            status, last_hello_at = self.liveness_manager.get_interface_status(
574
                interface_id
575
            )
576
            if not status:
577
                return {"interfaces": []}, 200
578
            body = {
579
                "interfaces": [
580
                    {
581
                        "id": interface_id,
582
                        "status": status,
583
                        "last_hello_at": last_hello_at,
584
                    }
585 1
                ]
586 1
            }
587
            return jsonify(body), 200
588
        interfaces = []
589
        for interface_id in list(self.liveness_manager.interfaces.keys()):
590
            status, last_hello_at = self.liveness_manager.get_interface_status(
591
                interface_id
592 1
            )
593
            interfaces.append({"id": interface_id, "status": status,
594 1
                              "last_hello_at": last_hello_at})
595 1
        return jsonify({"interfaces": interfaces}), 200
596
597
    @rest("v1/liveness/pair", methods=["GET"])
598 1
    def get_liveness_interface_pairs(self):
599 1
        """Get liveness interface pairs."""
600
        pairs = []
601
        for entry in list(self.liveness_manager.liveness.values()):
602
            lsm = entry["lsm"]
603
            pair = {
604
                "interface_a": {
605
                    "id": entry["interface_a"].id,
606
                    "status": lsm.ilsm_a.state,
607
                    "last_hello_at": lsm.ilsm_a.last_hello_at,
608
                },
609
                "interface_b": {
610
                    "id": entry["interface_b"].id,
611
                    "status": lsm.ilsm_b.state,
612
                    "last_hello_at": lsm.ilsm_b.last_hello_at,
613
                },
614
                "status": lsm.state
615 1
            }
616
            pairs.append(pair)
617 1
        return jsonify({"pairs": pairs})
618 1
619
    @rest('v1/polling_time', methods=['GET'])
620 1
    def get_time(self):
621
        """Get LLDP polling time in seconds."""
622 1
        return jsonify({"polling_time": self.polling_time}), 200
623 1
624
    @rest('v1/polling_time', methods=['POST'])
625
    def set_time(self):
626 1
        """Set LLDP polling time."""
627 1
        # pylint: disable=attribute-defined-outside-init
628 1
        try:
629 1
            payload = request.get_json()
630
            polling_time = int(payload['polling_time'])
631
            if polling_time <= 0:
632
                raise ValueError(f"invalid polling_time {polling_time}, "
633 1
                                 "must be greater than zero")
634 1
            self.polling_time = polling_time
635 1
            self.execute_as_loop(self.polling_time)
636
            log.info("Polling time has been updated to %s"
637
                     " second(s), but this change will not be saved"
638 1
                     " permanently.", self.polling_time)
639 1
            return jsonify("Polling time has been updated."), 200
640 1
        except (ValueError, KeyError) as error:
641 1
            msg = f"This operation is not completed: {error}"
642
            return jsonify(msg), 400
643