Passed
Push — master ( eaed3c...825740 )
by Vinicius
04:58 queued 16s
created

build.main.Main.set_flow_table_group_owner()   A

Complexity

Conditions 1

Size

Total Lines 8
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

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