Test Failed
Pull Request — master (#101)
by Vinicius
07:51 queued 03:18
created

build.main.Main.on_lldp_loop_stopped()   A

Complexity

Conditions 2

Size

Total Lines 13
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 3.372

Importance

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