Passed
Pull Request — master (#99)
by
unknown
07:06
created

build.main   F

Complexity

Total Complexity 120

Size/Duplication

Total Lines 737
Duplicated Lines 0 %

Test Coverage

Coverage 84.3%

Importance

Changes 0
Metric Value
eloc 513
dl 0
loc 737
ccs 376
cts 446
cp 0.843
rs 2
c 0
b 0
f 0
wmc 120

40 Methods

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

How to fix   Complexity   

Complexity

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

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

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