Passed
Pull Request — master (#96)
by
unknown
04:09
created

build.main.Main.get_flows_by_switch()   A

Complexity

Conditions 3

Size

Total Lines 18
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3.009

Importance

Changes 0
Metric Value
cc 3
eloc 14
nop 2
dl 0
loc 18
ccs 9
cts 10
cp 0.9
crap 3.009
rs 9.7
c 0
b 0
f 0
1
"""NApp responsible to discover new switches and hosts."""
2 1
import struct
3
4 1
import httpx
5 1
import tenacity
6 1
from napps.kytos.of_core.msg_prios import of_msg_prio
7 1
from napps.kytos.of_lldp import constants, settings
8 1
from napps.kytos.of_lldp.managers import LivenessManager, LoopManager
9 1
from napps.kytos.of_lldp.managers.loop_manager import LoopState
10 1
from napps.kytos.of_lldp.utils import (get_cookie, try_to_gen_intf_mac,
11
                                       update_flow)
12 1
from pyof.foundation.basic_types import DPID, UBInt32
13 1
from pyof.foundation.network_types import LLDP, VLAN, Ethernet, EtherType
14 1
from pyof.v0x04.common.action import ActionOutput as AO13
15 1
from pyof.v0x04.common.port import PortNo as Port13
16 1
from pyof.v0x04.controller2switch.packet_out import PacketOut as PO13
17 1
from tenacity import (retry, retry_if_exception_type, stop_after_attempt,
18
                      wait_combine, wait_fixed, wait_random)
19
20 1
from kytos.core import KytosEvent, KytosNApp, log, rest
21 1
from kytos.core.helpers import alisten_to, listen_to
22 1
from kytos.core.link import Link
23 1
from kytos.core.rest_api import (HTTPException, JSONResponse, Request,
24
                                 aget_json_or_400, get_json_or_400)
25 1
from kytos.core.retry import before_sleep
26 1
from kytos.core.switch import Switch
27
28 1
from .controllers import LivenessController
29
30
31 1
class Main(KytosNApp):
32
    """Main OF_LLDP NApp Class."""
33
34 1
    def setup(self):
35
        """Make this NApp run in a loop."""
36 1
        self.vlan_id = None
37 1
        self.polling_time = settings.POLLING_TIME
38 1
        if hasattr(settings, "FLOW_VLAN_VID"):
39 1
            self.vlan_id = settings.FLOW_VLAN_VID
40 1
        self.liveness_dead_multipler = settings.LIVENESS_DEAD_MULTIPLIER
41 1
        self.execute_as_loop(self.polling_time)
42 1
        self.loop_manager = LoopManager(self.controller)
43 1
        self.dead_interval = self.polling_time * self.liveness_dead_multipler
44 1
        self.liveness_controller = self.get_liveness_controller()
45 1
        self.liveness_controller.bootstrap_indexes()
46 1
        self.liveness_manager = LivenessManager(self.controller)
47 1
        Link.register_status_func(f"{self.napp_id}_liveness",
48
                                  LivenessManager.link_status_hook_liveness)
49 1
        self.table_group = {"base": 0}
50
51 1
    @staticmethod
52 1
    def get_liveness_controller() -> LivenessController:
53
        """Get LivenessController."""
54
        return LivenessController()
55
56 1
    def execute(self):
57
        """Send LLDP Packets every 'POLLING_TIME' seconds to all switches."""
58 1
        switches = list(self.controller.switches.values())
59 1
        for switch in switches:
60 1
            try:
61 1
                of_version = switch.connection.protocol.version
62
            except AttributeError:
63
                of_version = None
64
65 1
            if not switch.is_connected():
66
                continue
67
68 1
            if of_version == 0x04:
69 1
                port_type = UBInt32
70 1
                local_port = Port13.OFPP_LOCAL
71
            else:
72
                # skip the current switch with unsupported OF version
73
                continue
74
75 1
            interfaces = list(switch.interfaces.values())
76 1
            for interface in interfaces:
77
                # Interface marked to receive lldp packet
78
                # Only send LLDP packet to active interface
79 1
                if (not interface.lldp or not interface.is_active()
80
                   or not interface.is_enabled()):
81
                    continue
82
                # Avoid the interface that connects to the controller.
83 1
                if interface.port_number == local_port:
84
                    continue
85
86 1
                lldp = LLDP()
87 1
                lldp.chassis_id.sub_value = DPID(switch.dpid)
88 1
                lldp.port_id.sub_value = port_type(interface.port_number)
89
90 1
                src_addr = try_to_gen_intf_mac(interface.address, switch.id,
91
                                               interface.port_number)
92 1
                ethernet = Ethernet()
93 1
                ethernet.ether_type = EtherType.LLDP
94 1
                ethernet.source = src_addr
95 1
                ethernet.destination = constants.LLDP_MULTICAST_MAC
96 1
                ethernet.data = lldp.pack()
97
                # self.vlan_id == None will result in a packet with no VLAN.
98 1
                ethernet.vlans.append(VLAN(vid=self.vlan_id))
99
100 1
                packet_out = self._build_lldp_packet_out(
101
                                    of_version,
102
                                    interface.port_number, ethernet.pack())
103
104 1
                if packet_out is None:
105
                    continue
106
107 1
                event_out = KytosEvent(
108
                    name='kytos/of_lldp.messages.out.ofpt_packet_out',
109
                    priority=of_msg_prio(packet_out.header.message_type.value),
110
                    content={
111
                            'destination': switch.connection,
112
                            'message': packet_out})
113
114 1
                self.controller.buffers.msg_out.put(event_out)
115 1
                log.debug(
116
                    "Sending a LLDP PacketOut to the switch %s",
117
                    switch.dpid)
118
119 1
                msg = 'Switch: %s (%s)'
120 1
                msg += ' Interface: %s'
121 1
                msg += ' -- LLDP PacketOut --'
122 1
                msg += ' Ethernet: eth_type (%s) | src (%s) | dst (%s) /'
123 1
                msg += ' LLDP: Switch (%s) | portno (%s)'
124
125 1
                log.debug(
126
                    msg,
127
                    switch.connection, switch.dpid,
128
                    interface.id, ethernet.ether_type,
129
                    ethernet.source, ethernet.destination,
130
                    switch.dpid, interface.port_number)
131
132 1
        self.try_to_publish_stopped_loops()
133 1
        self.liveness_manager.reaper(self.dead_interval)
134
135 1
    def load_liveness(self) -> None:
136
        """Load liveness."""
137 1
        interfaces = {intf.id: intf for intf in self._get_interfaces()}
138 1
        intfs = self.liveness_controller.get_enabled_interfaces()
139 1
        intfs_to_enable = [interfaces[intf["id"]] for intf in intfs]
140 1
        self.liveness_manager.enable(*intfs_to_enable)
141
142 1
    def try_to_publish_stopped_loops(self):
143
        """Try to publish current stopped loops."""
144
        for dpid, port_pairs in self.loop_manager.get_stopped_loops().items():
145
            try:
146
                switch = self.controller.get_switch_by_dpid(dpid)
147
                for port_pair in port_pairs:
148
                    interface_a = switch.interfaces[port_pair[0]]
149
                    interface_b = switch.interfaces[port_pair[1]]
150
                    self.loop_manager.publish_loop_state(
151
                        interface_a, interface_b, LoopState.stopped.value
152
                    )
153
            except (KeyError, AttributeError) as exc:
154
                log.error("try_to_publish_stopped_loops failed with switch:"
155
                          f"{dpid}, port_pair: {port_pair}. {str(exc)}")
156
157 1
    @listen_to('kytos/topology.switch.(enabled|disabled)')
158 1
    def handle_lldp_flows(self, event):
159
        """Install or remove flows in a switch.
160
161
        Install a flow to send LLDP packets to the controller. The proactive
162
        flow is installed whenever a switch is enabled. If the switch is
163
        disabled the flow is removed.
164
165
        Args:
166
            event (:class:`~kytos.core.events.KytosEvent`):
167
                Event with new switch information.
168
169
        """
170
        self._handle_lldp_flows(event)
171
172 1
    @listen_to("kytos/of_lldp.loop.action.log")
173 1
    def on_lldp_loop_log_action(self, event):
174
        """Handle LLDP loop log action."""
175
        interface_a = event.content["interface_a"]
176
        interface_b = event.content["interface_b"]
177
        self.loop_manager.handle_log_action(interface_a, interface_b)
178
179 1
    @listen_to("kytos/of_lldp.loop.action.disable")
180 1
    def on_lldp_loop_disable_action(self, event):
181
        """Handle LLDP loop disable action."""
182
        interface_a = event.content["interface_a"]
183
        interface_b = event.content["interface_b"]
184
        self.loop_manager.handle_disable_action(interface_a, interface_b)
185
186 1
    @listen_to("kytos/of_lldp.loop.detected")
187 1
    def on_lldp_loop_detected(self, event):
188
        """Handle LLDP loop detected."""
189
        interface_id = event.content["interface_id"]
190
        dpid = event.content["dpid"]
191
        port_pair = event.content["port_numbers"]
192
        self.loop_manager.handle_loop_detected(interface_id, dpid, port_pair)
193
194 1
    @listen_to("kytos/of_lldp.loop.stopped")
195 1
    def on_lldp_loop_stopped(self, event):
196
        """Handle LLDP loop stopped."""
197
        dpid = event.content["dpid"]
198
        port_pair = event.content["port_numbers"]
199
        try:
200
            switch = self.controller.get_switch_by_dpid(dpid)
201
            interface_a = switch.interfaces[port_pair[0]]
202
            interface_b = switch.interfaces[port_pair[1]]
203
            self.loop_manager.handle_loop_stopped(interface_a, interface_b)
204
        except (KeyError, AttributeError) as exc:
205
            log.error("on_lldp_loop_stopped failed with: "
206
                      f"{event.content} {str(exc)}")
207
208 1
    @listen_to("kytos/topology.topology_loaded")
209 1
    def on_topology_loaded(self, event):
210
        """Handle on topology loaded."""
211
        self.handle_topology_loaded(event)
212
213 1
    def handle_topology_loaded(self, event) -> None:
214
        """Handle on topology loaded."""
215 1
        topology = event.content["topology"]
216 1
        self.loop_manager.handle_topology_loaded(topology)
217 1
        self.load_liveness()
218
219 1
    @listen_to("kytos/topology.switches.metadata.(added|removed)")
220 1
    def on_switches_metadata_changed(self, event):
221
        """Handle on switches metadata changed."""
222
        switch = event.content["switch"]
223
        self.loop_manager.handle_switch_metadata_changed(switch)
224
225 1
    def _handle_lldp_flows(self, event):
226
        """Install or remove flows in a switch.
227
228
        Install a flow to send LLDP packets to the controller. The proactive
229
        flow is installed whenever a switch is enabled. If the switch is
230
        disabled the flow is removed.
231
        """
232 1
        try:
233 1
            dpid = event.content['dpid']
234 1
            switch = self.controller.get_switch_by_dpid(dpid)
235 1
            of_version = switch.connection.protocol.version
236
        except AttributeError:
237
            of_version = None
238
239 1
        try:
240 1
            installed_flows = self.get_flows_by_switch(switch.id)
241 1
        except tenacity.RetryError as err:
242 1
            msg = f"Error: {err.last_attempt.exception()} when "\
243
                   "obtaining flows."
244 1
            log.error(msg)
245 1
            return
246
247 1
        flow = None
248 1
        if ("switch.enabled" in event.name and not installed_flows or
249
                "switch.disabled" in event.name and installed_flows):
250 1
            flow = self._build_lldp_flow(of_version, get_cookie(switch.dpid))
251
252 1
        if flow:
253 1
            data = {'flows': [flow]}
254 1
            try:
255 1
                self.send_flow(switch, event.name, data=data)
256 1
            except tenacity.RetryError as err:
257 1
                msg = f"Error: {err.last_attempt.exception()} when"\
258
                      f" sending flows to {switch.id}, {data}"
259 1
                log.error(msg)
260
261
    # pylint: disable=unexpected-keyword-arg
262 1
    @retry(
263
        stop=stop_after_attempt(3),
264
        wait=wait_combine(wait_fixed(3), wait_random(min=2, max=7)),
265
        before_sleep=before_sleep,
266
        retry=retry_if_exception_type(httpx.RequestError),
267
        after=update_flow(),
268
    )
269 1
    def send_flow(self, switch, event_name, data=None):
270
        """Send flows to flow_manager to be installed/deleted"""
271 1
        endpoint = f'{settings.FLOW_MANAGER_URL}/flows/{switch.id}'
272 1
        client_error = {424, 404, 400}
273 1
        if event_name == 'kytos/topology.switch.enabled':
274 1
            for flow in data['flows']:
275 1
                flow.pop("cookie_mask", None)
276 1
            res = httpx.post(endpoint, json=data, timeout=10)
277 1
            if res.is_server_error or res.status_code in client_error:
278 1
                raise httpx.RequestError(res.text)
279 1
            self.use_vlan(switch)
280
281 1
        elif event_name == 'kytos/topology.switch.disabled':
282 1
            res = httpx.request("DELETE", endpoint, json=data, timeout=10)
283 1
            if res.is_server_error or res.status_code in client_error:
284 1
                raise httpx.RequestError(res.text)
285 1
            self.make_vlan_available(switch)
286
287 1
    def use_vlan(self, switch: Switch) -> None:
288
        """Use vlan from interface"""
289 1
        if self.vlan_id is None:
290 1
            return
291 1
        for interface_id in switch.interfaces:
292 1
            interface = switch.interfaces[interface_id]
293 1
            added = interface.use_tags(self.controller, self.vlan_id)
294 1
            if not added:
295 1
                log.warning(f"TAG {self.vlan_id} is not available in"
296
                            f" {switch.id}:{interface_id}.")
297
298 1
    def make_vlan_available(self, switch: Switch) -> None:
299
        """Makes vlan from interface available"""
300 1
        if self.vlan_id is None:
301 1
            return
302 1
        for interface_id in switch.interfaces:
303 1
            interface = switch.interfaces[interface_id]
304 1
            added = interface.make_tags_available(
305
                self.controller, self.vlan_id
306
            )
307 1
            if not added:
308 1
                log.warning(f"Tag {self.vlan_id} was already available"
309
                            f" in {switch.id}:{interface_id}")
310
311 1
    @retry(
312
        stop=stop_after_attempt(3),
313
        wait=wait_combine(wait_fixed(3), wait_random(min=2, max=7)),
314
        before_sleep=before_sleep,
315
        retry=retry_if_exception_type(httpx.RequestError),
316
    )
317 1
    def get_flows_by_switch(self, dpid: str) -> dict:
318
        """Get of_lldp flows by switch"""
319 1
        error_codes = {400, 404}
320 1
        start = settings.COOKIE_PREFIX << 56
321 1
        end = start | 0x00FFFFFFFFFFFFFF
322 1
        endpoint = f'{settings.FLOW_MANAGER_URL}/stored_flows?state='\
323
                   f'installed&cookie_range={start}&cookie_range={end}'\
324
                   f'&dpid={dpid}'
325 1
        res = httpx.get(endpoint)
326 1
        if res.is_server_error or res.status_code in error_codes:
327 1
            raise httpx.RequestError(res.text)
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