Passed
Pull Request — master (#96)
by
unknown
03:29
created

build.main.Main._handle_lldp_flows()   A

Complexity

Conditions 4

Size

Total Lines 25
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 4.0312

Importance

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