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

build.main.Main.used_unused_vlan()   A

Complexity

Conditions 4

Size

Total Lines 12
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 4

Importance

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