Passed
Pull Request — master (#80)
by
unknown
06:50 queued 04:08
created

build.main   F

Complexity

Total Complexity 98

Size/Duplication

Total Lines 672
Duplicated Lines 0 %

Test Coverage

Coverage 82.43%

Importance

Changes 0
Metric Value
wmc 98
eloc 458
dl 0
loc 672
ccs 333
cts 404
cp 0.8243
rs 2
c 0
b 0
f 0

36 Methods

Rating   Name   Duplication   Size   Complexity  
B Main.disable_lldp() 0 33 6
A Main.enable_liveness() 0 20 4
A Main.get_liveness_interface_pairs() 0 22 2
A Main._get_interfaces_dict() 0 4 1
A Main.set_time() 0 20 3
A Main.get_time() 0 4 1
A Main.disable_liveness() 0 17 3
A Main.get_lldp_interfaces() 0 4 1
A Main._get_lldp_interfaces() 0 3 1
A Main.get_liveness_interfaces() 0 29 4
B Main.enable_lldp() 0 27 6
A Main._get_interfaces() 0 6 2
A Main._unpack_non_empty() 0 23 2
A Main.try_to_publish_stopped_loops() 0 13 4
A Main.on_switches_metadata_changed() 0 5 1
A Main.on_lldp_loop_disable_action() 0 6 1
A Main.on_lldp_loop_stopped() 0 12 2
C Main._handle_lldp_flows() 0 55 9
A Main.publish_liveness_status() 0 6 1
A Main.shutdown() 0 3 1
A Main.setup() 0 16 2
C Main.execute() 0 76 11
A Main.on_lldp_loop_detected() 0 7 1
A Main.load_liveness() 0 6 1
A Main.notify_lldp_change() 0 8 1
A Main.get_liveness_controller() 0 4 1
A Main.on_lldp_loop_log_action() 0 6 1
A Main.handle_topology_loaded() 0 5 1
C Main.on_ofpt_packet_in() 0 54 11
A Main.on_topology_loaded() 0 4 1
A Main._build_lldp_packet_out() 0 31 2
A Main.handle_lldp_flows() 0 14 1
A Main.set_flow_table_group_owner() 0 8 1
A Main.on_table_enabled() 0 19 4
A Main._get_data() 0 4 1
A Main._build_lldp_flow() 0 31 3

How to fix   Complexity   

Complexity

Complex classes like build.main often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
"""NApp responsible to discover new switches and hosts."""
2 1
import struct
3 1
import time
4
5 1
import requests
6 1
from napps.kytos.of_core.msg_prios import of_msg_prio
7 1
from napps.kytos.of_lldp import constants, settings
8 1
from napps.kytos.of_lldp.managers import LivenessManager, LoopManager
9 1
from napps.kytos.of_lldp.managers.loop_manager import LoopState
10 1
from napps.kytos.of_lldp.utils import get_cookie
11 1
from pyof.foundation.basic_types import DPID, UBInt32
12 1
from pyof.foundation.network_types import LLDP, VLAN, Ethernet, EtherType
13 1
from pyof.v0x04.common.action import ActionOutput as AO13
14 1
from pyof.v0x04.common.port import PortNo as Port13
15 1
from pyof.v0x04.controller2switch.packet_out import PacketOut as PO13
16
17 1
from kytos.core import KytosEvent, KytosNApp, log, rest
18 1
from kytos.core.helpers import alisten_to, listen_to
19 1
from kytos.core.link import Link
20 1
from kytos.core.rest_api import (HTTPException, JSONResponse, Request,
21
                                 aget_json_or_400, get_json_or_400)
22
23 1
from .controllers import LivenessController
24
25
26 1
class Main(KytosNApp):
27
    """Main OF_LLDP NApp Class."""
28
29 1
    def setup(self):
30
        """Make this NApp run in a loop."""
31 1
        self.vlan_id = None
32 1
        self.polling_time = settings.POLLING_TIME
33 1
        if hasattr(settings, "FLOW_VLAN_VID"):
34 1
            self.vlan_id = settings.FLOW_VLAN_VID
35 1
        self.liveness_dead_multipler = settings.LIVENESS_DEAD_MULTIPLIER
36 1
        self.execute_as_loop(self.polling_time)
37 1
        self.loop_manager = LoopManager(self.controller)
38 1
        self.dead_interval = self.polling_time * self.liveness_dead_multipler
39 1
        self.liveness_controller = self.get_liveness_controller()
40 1
        self.liveness_controller.bootstrap_indexes()
41 1
        self.liveness_manager = LivenessManager(self.controller)
42 1
        Link.register_status_func(f"{self.napp_id}_liveness",
43
                                  LivenessManager.link_status_hook_liveness)
44 1
        self.table_group = {"base": 0}
45
46 1
    @staticmethod
47 1
    def get_liveness_controller() -> LivenessController:
48
        """Get LivenessController."""
49
        return LivenessController()
50
51 1
    def execute(self):
52
        """Send LLDP Packets every 'POLLING_TIME' seconds to all switches."""
53 1
        switches = list(self.controller.switches.values())
54 1
        for switch in switches:
55 1
            try:
56 1
                of_version = switch.connection.protocol.version
57
            except AttributeError:
58
                of_version = None
59
60 1
            if not switch.is_connected():
61
                continue
62
63 1
            if of_version == 0x04:
64 1
                port_type = UBInt32
65 1
                local_port = Port13.OFPP_LOCAL
66
            else:
67
                # skip the current switch with unsupported OF version
68
                continue
69
70 1
            interfaces = list(switch.interfaces.values())
71 1
            for interface in interfaces:
72
                # Interface marked to receive lldp packet
73
                # Only send LLDP packet to active interface
74 1
                if (not interface.lldp or not interface.is_active()
75
                   or not interface.is_enabled()):
76
                    continue
77
                # Avoid the interface that connects to the controller.
78 1
                if interface.port_number == local_port:
79
                    continue
80
81 1
                lldp = LLDP()
82 1
                lldp.chassis_id.sub_value = DPID(switch.dpid)
83 1
                lldp.port_id.sub_value = port_type(interface.port_number)
84
85 1
                ethernet = Ethernet()
86 1
                ethernet.ether_type = EtherType.LLDP
87 1
                ethernet.source = interface.address
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
        if version == 0x04:
396 1
            flow['actions'] = [{'action_type': 'output',
397
                                'port': Port13.OFPP_CONTROLLER}]
398
        else:
399 1
            return None
400
401 1
        match = {}
402 1
        self.set_flow_table_group_owner(flow)
403 1
        flow['priority'] = settings.FLOW_PRIORITY
404 1
        flow['cookie'] = cookie
405 1
        flow['cookie_mask'] = cookie_mask
406 1
        match['dl_type'] = EtherType.LLDP
407 1
        if self.vlan_id:
408 1
            match['dl_vlan'] = self.vlan_id
409 1
        flow['match'] = match
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
    def _get_data(self, request: Request) -> list:
438
        """Get request data."""
439 1
        data = get_json_or_400(request, self.controller.loop)
440 1
        return data.get('interfaces', [])
441
442 1
    def _get_interfaces(self):
443
        """Get all interfaces."""
444 1
        interfaces = []
445 1
        for switch in list(self.controller.switches.values()):
446 1
            interfaces += list(switch.interfaces.values())
447 1
        return interfaces
448
449 1
    @staticmethod
450 1
    def _get_interfaces_dict(interfaces):
451
        """Return a dict of interfaces."""
452 1
        return {inter.id: inter for inter in interfaces}
453
454 1
    def _get_lldp_interfaces(self):
455
        """Get interfaces enabled to receive LLDP packets."""
456 1
        return [inter.id for inter in self._get_interfaces() if inter.lldp]
457
458 1
    @rest('v1/interfaces', methods=['GET'])
459 1
    async def get_lldp_interfaces(self, _request: Request) -> JSONResponse:
460
        """Return all the interfaces that have LLDP traffic enabled."""
461 1
        return JSONResponse({"interfaces": self._get_lldp_interfaces()})
462
463 1
    @rest('v1/interfaces/disable', methods=['POST'])
464 1
    def disable_lldp(self, request: Request) -> JSONResponse:
465
        """Disables an interface to receive LLDP packets."""
466 1
        interface_ids = self._get_data(request)
467 1
        error_list = []  # List of interfaces that were not activated.
468 1
        changed_interfaces = []
469 1
        interface_ids = filter(None, interface_ids)
470 1
        interfaces = self._get_interfaces()
471 1
        intfs = []
472 1
        if not interfaces:
473
            raise HTTPException(404, detail="No interfaces were found.")
474 1
        interfaces = self._get_interfaces_dict(interfaces)
475 1
        for id_ in interface_ids:
476 1
            interface = interfaces.get(id_)
477 1
            if interface:
478 1
                interface.lldp = False
479 1
                changed_interfaces.append(id_)
480 1
                intfs.append(interface)
481
            else:
482 1
                error_list.append(id_)
483 1
        if changed_interfaces:
484 1
            self.notify_lldp_change('disabled', changed_interfaces)
485 1
            intf_ids = [intf.id for intf in intfs]
486 1
            self.liveness_controller.disable_interfaces(intf_ids)
487 1
            self.liveness_manager.disable(*intfs)
488 1
            self.publish_liveness_status("disabled", intfs)
489 1
        if not error_list:
490 1
            return JSONResponse(
491
                "All the requested interfaces have been disabled.")
492
493
        # Return a list of interfaces that couldn't be disabled
494 1
        msg_error = "Some interfaces couldn't be found and deactivated: "
495 1
        return JSONResponse({msg_error: error_list}, status_code=400)
496
497 1
    @rest('v1/interfaces/enable', methods=['POST'])
498 1
    def enable_lldp(self, request: Request) -> JSONResponse:
499
        """Enable an interface to receive LLDP packets."""
500 1
        interface_ids = self._get_data(request)
501 1
        error_list = []  # List of interfaces that were not activated.
502 1
        changed_interfaces = []
503 1
        interface_ids = filter(None, interface_ids)
504 1
        interfaces = self._get_interfaces()
505 1
        if not interfaces:
506
            raise HTTPException(404, detail="No interfaces were found.")
507 1
        interfaces = self._get_interfaces_dict(interfaces)
508 1
        for id_ in interface_ids:
509 1
            interface = interfaces.get(id_)
510 1
            if interface:
511 1
                interface.lldp = True
512 1
                changed_interfaces.append(id_)
513
            else:
514 1
                error_list.append(id_)
515 1
        if changed_interfaces:
516 1
            self.notify_lldp_change('enabled', changed_interfaces)
517 1
        if not error_list:
518 1
            return JSONResponse(
519
                "All the requested interfaces have been enabled.")
520
521
        # Return a list of interfaces that couldn't be enabled
522 1
        msg_error = "Some interfaces couldn't be found and activated: "
523 1
        return JSONResponse({msg_error: error_list}, status_code=400)
524
525 1
    @rest("v1/liveness/enable", methods=["POST"])
526 1
    def enable_liveness(self, request: Request) -> JSONResponse:
527
        """Enable liveness link detection on interfaces."""
528 1
        intf_ids = self._get_data(request)
529 1
        if not intf_ids:
530
            raise HTTPException(400, "Interfaces payload is empty")
531 1
        interfaces = {intf.id: intf for intf in self._get_interfaces()}
532 1
        diff = set(intf_ids) - set(interfaces.keys())
533 1
        if diff:
534
            raise HTTPException(404, f"Interface IDs {diff} not found")
535
536 1
        intfs = [interfaces[_id] for _id in intf_ids]
537 1
        non_lldp = [intf.id for intf in intfs if not intf.lldp]
538 1
        if non_lldp:
539
            msg = f"Interface IDs {non_lldp} don't have LLDP enabled"
540
            raise HTTPException(400, msg)
541 1
        self.liveness_controller.enable_interfaces(intf_ids)
542 1
        self.liveness_manager.enable(*intfs)
543 1
        self.publish_liveness_status("enabled", intfs)
544 1
        return JSONResponse({})
545
546 1
    @rest("v1/liveness/disable", methods=["POST"])
547 1
    def disable_liveness(self, request: Request) -> JSONResponse:
548
        """Disable liveness link detection on interfaces."""
549 1
        intf_ids = self._get_data(request)
550 1
        if not intf_ids:
551
            raise HTTPException(400, "Interfaces payload is empty")
552
553 1
        interfaces = {intf.id: intf for intf in self._get_interfaces()}
554 1
        diff = set(intf_ids) - set(interfaces.keys())
555 1
        if diff:
556
            raise HTTPException(404, f"Interface IDs {diff} not found")
557
558 1
        intfs = [interfaces[_id] for _id in intf_ids if _id in interfaces]
559 1
        self.liveness_controller.disable_interfaces(intf_ids)
560 1
        self.liveness_manager.disable(*intfs)
561 1
        self.publish_liveness_status("disabled", intfs)
562 1
        return JSONResponse({})
563
564 1
    @rest("v1/liveness/", methods=["GET"])
565 1
    async def get_liveness_interfaces(self, request: Request) -> JSONResponse:
566
        """Get liveness interfaces."""
567 1
        args = request.query_params
568 1
        interface_id = args.get("interface_id")
569 1
        if interface_id:
570
            status, last_hello_at = self.liveness_manager.get_interface_status(
571
                interface_id
572
            )
573
            if not status:
574
                return {"interfaces": []}, 200
575
            body = {
576
                "interfaces": [
577
                    {
578
                        "id": interface_id,
579
                        "status": status,
580
                        "last_hello_at": last_hello_at,
581
                    }
582
                ]
583
            }
584
            return JSONResponse(body)
585 1
        interfaces = []
586 1
        for interface_id in list(self.liveness_manager.interfaces.keys()):
587
            status, last_hello_at = self.liveness_manager.get_interface_status(
588
                interface_id
589
            )
590
            interfaces.append({"id": interface_id, "status": status,
591
                              "last_hello_at": last_hello_at})
592 1
        return JSONResponse({"interfaces": interfaces})
593
594 1
    @rest("v1/liveness/pair", methods=["GET"])
595 1
    async def get_liveness_interface_pairs(self,
596
                                           _request: Request) -> JSONResponse:
597
        """Get liveness interface pairs."""
598 1
        pairs = []
599 1
        for entry in list(self.liveness_manager.liveness.values()):
600
            lsm = entry["lsm"]
601
            pair = {
602
                "interface_a": {
603
                    "id": entry["interface_a"].id,
604
                    "status": lsm.ilsm_a.state,
605
                    "last_hello_at": lsm.ilsm_a.last_hello_at,
606
                },
607
                "interface_b": {
608
                    "id": entry["interface_b"].id,
609
                    "status": lsm.ilsm_b.state,
610
                    "last_hello_at": lsm.ilsm_b.last_hello_at,
611
                },
612
                "status": lsm.state
613
            }
614
            pairs.append(pair)
615 1
        return JSONResponse({"pairs": pairs})
616
617 1
    @rest('v1/polling_time', methods=['GET'])
618 1
    async def get_time(self, _request: Request) -> JSONResponse:
619
        """Get LLDP polling time in seconds."""
620 1
        return JSONResponse({"polling_time": self.polling_time})
621
622 1
    @rest('v1/polling_time', methods=['POST'])
623 1
    async def set_time(self, request: Request) -> JSONResponse:
624
        """Set LLDP polling time."""
625
        # pylint: disable=attribute-defined-outside-init
626 1
        try:
627 1
            payload = await aget_json_or_400(request)
628 1
            polling_time = int(payload['polling_time'])
629 1
            if polling_time <= 0:
630
                msg = f"invalid polling_time {polling_time}, " \
631
                        "must be greater than zero"
632
                raise HTTPException(400, detail=msg)
633 1
            self.polling_time = polling_time
634 1
            self.execute_as_loop(self.polling_time)
635 1
            log.info("Polling time has been updated to %s"
636
                     " second(s), but this change will not be saved"
637
                     " permanently.", self.polling_time)
638 1
            return JSONResponse("Polling time has been updated.")
639 1
        except (ValueError, KeyError) as error:
640 1
            msg = f"This operation is not completed: {error}"
641 1
            raise HTTPException(400, detail=msg) from error
642
643 1
    def set_flow_table_group_owner(self,
644
                                   flow: dict,
645
                                   group: str = "base") -> dict:
646
        """Set owner, table_group and table_id"""
647 1
        flow["table_id"] = self.table_group[group]
648 1
        flow["owner"] = "of_lldp"
649 1
        flow["table_group"] = group
650 1
        return flow
651
652
    # pylint: disable=attribute-defined-outside-init
653 1
    @alisten_to("kytos/of_multi_table.enable_table")
654 1
    async def on_table_enabled(self, event):
655
        """Handle a recently table enabled.
656
        of_lldp only allows "base" as flow group
657
        """
658 1
        table_group = event.content.get("of_lldp", None)
659 1
        if not table_group:
660
            return
661 1
        for group in table_group:
662 1
            if group not in settings.TABLE_GROUP_ALLOWED:
663 1
                log.error(f'The table group "{group}" is not allowed for '
664
                          f'of_lldp. Allowed table groups are '
665
                          f'{settings.TABLE_GROUP_ALLOWED}')
666 1
                return
667 1
        self.table_group = table_group
668 1
        content = {"group_table": self.table_group}
669 1
        event_out = KytosEvent(name="kytos/of_lldp.enable_table",
670
                               content=content)
671
        await self.controller.buffers.app.aput(event_out)
672