Test Failed
Pull Request — master (#123)
by
unknown
07:24 queued 03:15
created

build.main.Main.make_vlan_available()   B

Complexity

Conditions 6

Size

Total Lines 17
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 6

Importance

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