Passed
Pull Request — master (#96)
by
unknown
03:25
created

build.main   F

Complexity

Total Complexity 110

Size/Duplication

Total Lines 702
Duplicated Lines 0 %

Test Coverage

Coverage 82.08%

Importance

Changes 0
Metric Value
eloc 484
dl 0
loc 702
ccs 348
cts 424
cp 0.8208
rs 2
c 0
b 0
f 0
wmc 110

40 Methods

Rating   Name   Duplication   Size   Complexity  
A Main.try_to_publish_stopped_loops() 0 13 4
A Main.on_switches_metadata_changed() 0 5 1
A Main.on_lldp_loop_disable_action() 0 6 1
A Main.on_lldp_loop_stopped() 0 12 2
A Main.setup() 0 16 2
C Main.execute() 0 78 11
A Main.on_lldp_loop_detected() 0 7 1
A Main.load_liveness() 0 6 1
A Main.get_liveness_controller() 0 4 1
A Main.on_lldp_loop_log_action() 0 6 1
A Main.handle_topology_loaded() 0 5 1
A Main.on_topology_loaded() 0 4 1
A Main.handle_lldp_flows() 0 14 1
B Main.disable_lldp() 0 33 6
A Main.enable_liveness() 0 20 4
A Main._unpack_non_empty() 0 23 2
A Main.get_liveness_interface_pairs() 0 22 2
A Main._get_interfaces_dict() 0 4 1
A Main.use_vlan() 0 8 3
A Main.set_time() 0 20 3
C Main.send_flow() 0 24 10
A Main._handle_lldp_flows() 0 24 4
A Main.get_time() 0 4 1
A Main.publish_liveness_status() 0 6 1
A Main.shutdown() 0 3 1
A Main.set_flow_table_group_owner() 0 8 1
A Main.get_flows_by_switch() 0 9 1
A Main.notify_lldp_change() 0 8 1
A Main.disable_liveness() 0 17 3
A Main.get_lldp_interfaces() 0 4 1
A Main._get_lldp_interfaces() 0 3 1
A Main.make_vlan_available() 0 8 3
C Main.on_ofpt_packet_in() 0 54 11
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

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.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
237
        except AttributeError:
238
            of_version = None
239
240 1
        flow = self._build_lldp_flow(of_version, get_cookie(switch.dpid))
241 1
        if flow:
242 1
            data = {'flows': [flow]}
243 1
            try:
244 1
                self.send_flow(switch, event.name, data=data)
245 1
            except tenacity.RetryError as err:
246 1
                msg = f"Error:{err.last_attempt.exception()} when"\
247
                      f" sending flows to {switch.id}, {data}"
248 1
                log.error(msg)
249
250
    # pylint: disable=unexpected-keyword-arg
251 1
    @retry(
252
        stop=stop_after_attempt(3),
253
        wait=wait_combine(wait_fixed(3), wait_random(min=2, max=7)),
254
        before_sleep=before_sleep,
255
        retry=retry_if_exception_type(httpx.RequestError),
256
        after=update_flow(),
257
    )
258 1
    def send_flow(self, switch, event_name, data=None):
259
        """Send flows to flow_manager to be installed/deleted"""
260 1
        destination = switch.id
261 1
        endpoint = f'{settings.FLOW_MANAGER_URL}/flows/{destination}'
262 1
        flows = self.get_flows_by_switch(destination)
263 1
        if event_name == 'kytos/topology.switch.enabled' and not flows:
264 1
            for flow in data['flows']:
265 1
                flow.pop("cookie_mask", None)
266 1
            res = httpx.post(endpoint, json=data, timeout=10)
267 1
            if res.is_server_error or res.status_code == 424:
268 1
                raise httpx.RequestError(res.text)
269
            self.use_vlan(switch)
270 1
        elif event_name == 'kytos/topology.switch.disabled' and flows:
271 1
            res = httpx.request("DELETE", endpoint, json=data, timeout=10)
272 1
            if res.is_server_error or res.status_code == 424:
273 1
                raise httpx.RequestError(res.text)
274
            self.make_vlan_available(switch)
275
276 1
    def use_vlan(self, switch: Switch) -> None:
277
        """Use vlan from interface"""
278 1
        if self.vlan_id is None:
279 1
            return
280 1
        tags = [self.vlan_id] * 2
281 1
        for interface_id in switch.interfaces:
282 1
            interface = switch.interfaces[interface_id]
283 1
            interface.use_tags(self.controller, tags)
284
285 1
    def make_vlan_available(self, switch: Switch) -> None:
286
        """Makes vlan from interface available"""
287 1
        if self.vlan_id is None:
288 1
            return
289 1
        tags = [self.vlan_id] * 2
290 1
        for interface_id in switch.interfaces:
291 1
            interface = switch.interfaces[interface_id]
292 1
            interface.make_tags_available(self.controller, tags)
293
294 1
    def get_flows_by_switch(self, dpid: str) -> dict:
295
        """Get of_lldp flows by switch"""
296
        start = settings.COOKIE_PREFIX << 56
297
        end = start | 0x00FFFFFFFFFFFFFF
298
        endpoint = f'{settings.FLOW_MANAGER_URL}/stored_flows?state='\
299
                   f'installed&cookie_range={start}&cookie_range={end}'\
300
                   f'&dpid={dpid}'
301
        res = httpx.get(endpoint)
302
        return res.json()
303
304 1
    @alisten_to('kytos/of_core.v0x04.messages.in.ofpt_packet_in')
305 1
    async def on_ofpt_packet_in(self, event):
306
        """Dispatch two KytosEvents to notify identified NNI interfaces.
307
308
        Args:
309
            event (:class:`~kytos.core.events.KytosEvent`):
310
                Event with an LLDP packet as data.
311
312
        """
313 1
        ethernet = self._unpack_non_empty(Ethernet, event.message.data)
314 1
        if ethernet.ether_type == EtherType.LLDP:
315 1
            try:
316 1
                lldp = self._unpack_non_empty(LLDP, ethernet.data)
317 1
                dpid = self._unpack_non_empty(DPID, lldp.chassis_id.sub_value)
318
            except struct.error:
319
                #: If we have a LLDP packet but we cannot unpack it, or the
320
                #: unpacked packet does not contain the dpid attribute, then
321
                #: we are dealing with a LLDP generated by someone else. Thus
322
                #: this packet is not useful for us and we may just ignore it.
323
                return
324
325 1
            switch_a = event.source.switch
326 1
            port_a = event.message.in_port
327 1
            switch_b = None
328 1
            port_b = None
329
330
            # in_port is currently an Int in v0x04.
331 1
            if isinstance(port_a, int):
332 1
                port_a = UBInt32(port_a)
333
334 1
            try:
335 1
                switch_b = self.controller.get_switch_by_dpid(dpid.value)
336 1
                port_type = UBInt32
337 1
                port_b = self._unpack_non_empty(port_type,
338
                                                lldp.port_id.sub_value)
339
            except AttributeError:
340
                log.debug("Couldn't find datapath %s.", dpid.value)
341
342
            # Return if any of the needed information are not available
343 1
            if not (switch_a and port_a and switch_b and port_b):
344
                return
345
346 1
            interface_a = switch_a.get_interface_by_port_no(port_a.value)
347 1
            interface_b = switch_b.get_interface_by_port_no(port_b.value)
348 1
            if not interface_a or not interface_b:
349 1
                return
350
351 1
            await self.loop_manager.process_if_looped(interface_a, interface_b)
352 1
            await self.liveness_manager.consume_hello_if_enabled(interface_a,
353
                                                                 interface_b)
354 1
            event_out = KytosEvent(name='kytos/of_lldp.interface.is.nni',
355
                                   content={'interface_a': interface_a,
356
                                            'interface_b': interface_b})
357 1
            await self.controller.buffers.app.aput(event_out)
358
359 1
    def notify_lldp_change(self, state, interface_ids):
360
        """Dispatch a KytosEvent to notify changes to the LLDP status."""
361 1
        content = {'attribute': 'LLDP',
362
                   'state': state,
363
                   'interface_ids': interface_ids}
364 1
        event_out = KytosEvent(name='kytos/of_lldp.network_status.updated',
365
                               content=content)
366 1
        self.controller.buffers.app.put(event_out)
367
368 1
    def publish_liveness_status(self, event_suffix, interfaces):
369
        """Dispatch a KytosEvent to publish liveness admin status."""
370 1
        content = {"interfaces": interfaces}
371 1
        name = f"kytos/of_lldp.liveness.{event_suffix}"
372 1
        event_out = KytosEvent(name=name, content=content)
373 1
        self.controller.buffers.app.put(event_out)
374
375 1
    def shutdown(self):
376
        """End of the application."""
377
        log.debug('Shutting down...')
378
379 1
    @staticmethod
380 1
    def _build_lldp_packet_out(version, port_number, data):
381
        """Build a LLDP PacketOut message.
382
383
        Args:
384
            version (int): OpenFlow version
385
            port_number (int): Switch port number where the packet must be
386
                forwarded to.
387
            data (bytes): Binary data to be sent through the port.
388
389
        Returns:
390
            PacketOut message for the specific given OpenFlow version, if it
391
                is supported.
392
            None if the OpenFlow version is not supported.
393
394
        """
395 1
        if version == 0x04:
396 1
            action_output_class = AO13
397 1
            packet_out_class = PO13
398
        else:
399 1
            log.info('Openflow version %s is not yet supported.', version)
400 1
            return None
401
402 1
        output_action = action_output_class()
403 1
        output_action.port = port_number
404
405 1
        packet_out = packet_out_class()
406 1
        packet_out.data = data
407 1
        packet_out.actions.append(output_action)
408
409 1
        return packet_out
410
411 1
    def _build_lldp_flow(self, version, cookie,
412
                         cookie_mask=0xffffffffffffffff):
413
        """Build a Flow message to send LLDP to the controller.
414
415
        Args:
416
            version (int): OpenFlow version.
417
418
        Returns:
419
            Flow dictionary message for the specific given OpenFlow version,
420
            if it is supported.
421
            None if the OpenFlow version is not supported.
422
423
        """
424 1
        flow = {}
425 1
        if version == 0x04:
426 1
            flow['actions'] = [{'action_type': 'output',
427
                                'port': Port13.OFPP_CONTROLLER}]
428
        else:
429 1
            return None
430
431 1
        match = {}
432 1
        self.set_flow_table_group_owner(flow)
433 1
        flow['priority'] = settings.FLOW_PRIORITY
434 1
        flow['cookie'] = cookie
435 1
        flow['cookie_mask'] = cookie_mask
436 1
        match['dl_type'] = EtherType.LLDP
437 1
        if self.vlan_id:
438 1
            match['dl_vlan'] = self.vlan_id
439 1
        flow['match'] = match
440
441 1
        return flow
442
443 1
    @staticmethod
444 1
    def _unpack_non_empty(desired_class, data):
445
        """Unpack data using an instance of desired_class.
446
447
        Args:
448
            desired_class (class): The class to be used to unpack data.
449
            data (bytes): bytes to be unpacked.
450
451
        Return:
452
            An instance of desired_class class with data unpacked into it.
453
454
        Raises:
455
            UnpackException if the unpack could not be performed.
456
457
        """
458 1
        obj = desired_class()
459
460 1
        if hasattr(data, 'value'):
461 1
            data = data.value
462
463 1
        obj.unpack(data)
464
465 1
        return obj
466
467 1
    def _get_data(self, request: Request) -> list:
468
        """Get request data."""
469 1
        data = get_json_or_400(request, self.controller.loop)
470 1
        return data.get('interfaces', [])
471
472 1
    def _get_interfaces(self):
473
        """Get all interfaces."""
474 1
        interfaces = []
475 1
        for switch in list(self.controller.switches.values()):
476 1
            interfaces += list(switch.interfaces.values())
477 1
        return interfaces
478
479 1
    @staticmethod
480 1
    def _get_interfaces_dict(interfaces):
481
        """Return a dict of interfaces."""
482 1
        return {inter.id: inter for inter in interfaces}
483
484 1
    def _get_lldp_interfaces(self):
485
        """Get interfaces enabled to receive LLDP packets."""
486 1
        return [inter.id for inter in self._get_interfaces() if inter.lldp]
487
488 1
    @rest('v1/interfaces', methods=['GET'])
489 1
    async def get_lldp_interfaces(self, _request: Request) -> JSONResponse:
490
        """Return all the interfaces that have LLDP traffic enabled."""
491 1
        return JSONResponse({"interfaces": self._get_lldp_interfaces()})
492
493 1
    @rest('v1/interfaces/disable', methods=['POST'])
494 1
    def disable_lldp(self, request: Request) -> JSONResponse:
495
        """Disables an interface to receive LLDP packets."""
496 1
        interface_ids = self._get_data(request)
497 1
        error_list = []  # List of interfaces that were not activated.
498 1
        changed_interfaces = []
499 1
        interface_ids = filter(None, interface_ids)
500 1
        interfaces = self._get_interfaces()
501 1
        intfs = []
502 1
        if not interfaces:
503
            raise HTTPException(404, detail="No interfaces were found.")
504 1
        interfaces = self._get_interfaces_dict(interfaces)
505 1
        for id_ in interface_ids:
506 1
            interface = interfaces.get(id_)
507 1
            if interface:
508 1
                interface.lldp = False
509 1
                changed_interfaces.append(id_)
510 1
                intfs.append(interface)
511
            else:
512 1
                error_list.append(id_)
513 1
        if changed_interfaces:
514 1
            self.notify_lldp_change('disabled', changed_interfaces)
515 1
            intf_ids = [intf.id for intf in intfs]
516 1
            self.liveness_controller.disable_interfaces(intf_ids)
517 1
            self.liveness_manager.disable(*intfs)
518 1
            self.publish_liveness_status("disabled", intfs)
519 1
        if not error_list:
520 1
            return JSONResponse(
521
                "All the requested interfaces have been disabled.")
522
523
        # Return a list of interfaces that couldn't be disabled
524 1
        msg_error = "Some interfaces couldn't be found and deactivated: "
525 1
        return JSONResponse({msg_error: error_list}, status_code=400)
526
527 1
    @rest('v1/interfaces/enable', methods=['POST'])
528 1
    def enable_lldp(self, request: Request) -> JSONResponse:
529
        """Enable an interface to receive LLDP packets."""
530 1
        interface_ids = self._get_data(request)
531 1
        error_list = []  # List of interfaces that were not activated.
532 1
        changed_interfaces = []
533 1
        interface_ids = filter(None, interface_ids)
534 1
        interfaces = self._get_interfaces()
535 1
        if not interfaces:
536
            raise HTTPException(404, detail="No interfaces were found.")
537 1
        interfaces = self._get_interfaces_dict(interfaces)
538 1
        for id_ in interface_ids:
539 1
            interface = interfaces.get(id_)
540 1
            if interface:
541 1
                interface.lldp = True
542 1
                changed_interfaces.append(id_)
543
            else:
544 1
                error_list.append(id_)
545 1
        if changed_interfaces:
546 1
            self.notify_lldp_change('enabled', changed_interfaces)
547 1
        if not error_list:
548 1
            return JSONResponse(
549
                "All the requested interfaces have been enabled.")
550
551
        # Return a list of interfaces that couldn't be enabled
552 1
        msg_error = "Some interfaces couldn't be found and activated: "
553 1
        return JSONResponse({msg_error: error_list}, status_code=400)
554
555 1
    @rest("v1/liveness/enable", methods=["POST"])
556 1
    def enable_liveness(self, request: Request) -> JSONResponse:
557
        """Enable liveness link detection on interfaces."""
558 1
        intf_ids = self._get_data(request)
559 1
        if not intf_ids:
560
            raise HTTPException(400, "Interfaces payload is empty")
561 1
        interfaces = {intf.id: intf for intf in self._get_interfaces()}
562 1
        diff = set(intf_ids) - set(interfaces.keys())
563 1
        if diff:
564
            raise HTTPException(404, f"Interface IDs {diff} not found")
565
566 1
        intfs = [interfaces[_id] for _id in intf_ids]
567 1
        non_lldp = [intf.id for intf in intfs if not intf.lldp]
568 1
        if non_lldp:
569
            msg = f"Interface IDs {non_lldp} don't have LLDP enabled"
570
            raise HTTPException(400, msg)
571 1
        self.liveness_controller.enable_interfaces(intf_ids)
572 1
        self.liveness_manager.enable(*intfs)
573 1
        self.publish_liveness_status("enabled", intfs)
574 1
        return JSONResponse({})
575
576 1
    @rest("v1/liveness/disable", methods=["POST"])
577 1
    def disable_liveness(self, request: Request) -> JSONResponse:
578
        """Disable liveness link detection on interfaces."""
579 1
        intf_ids = self._get_data(request)
580 1
        if not intf_ids:
581
            raise HTTPException(400, "Interfaces payload is empty")
582
583 1
        interfaces = {intf.id: intf for intf in self._get_interfaces()}
584 1
        diff = set(intf_ids) - set(interfaces.keys())
585 1
        if diff:
586
            raise HTTPException(404, f"Interface IDs {diff} not found")
587
588 1
        intfs = [interfaces[_id] for _id in intf_ids if _id in interfaces]
589 1
        self.liveness_controller.disable_interfaces(intf_ids)
590 1
        self.liveness_manager.disable(*intfs)
591 1
        self.publish_liveness_status("disabled", intfs)
592 1
        return JSONResponse({})
593
594 1
    @rest("v1/liveness/", methods=["GET"])
595 1
    async def get_liveness_interfaces(self, request: Request) -> JSONResponse:
596
        """Get liveness interfaces."""
597 1
        args = request.query_params
598 1
        interface_id = args.get("interface_id")
599 1
        if interface_id:
600
            status, last_hello_at = self.liveness_manager.get_interface_status(
601
                interface_id
602
            )
603
            if not status:
604
                return {"interfaces": []}, 200
605
            body = {
606
                "interfaces": [
607
                    {
608
                        "id": interface_id,
609
                        "status": status,
610
                        "last_hello_at": last_hello_at,
611
                    }
612
                ]
613
            }
614
            return JSONResponse(body)
615 1
        interfaces = []
616 1
        for interface_id in list(self.liveness_manager.interfaces.keys()):
617
            status, last_hello_at = self.liveness_manager.get_interface_status(
618
                interface_id
619
            )
620
            interfaces.append({"id": interface_id, "status": status,
621
                              "last_hello_at": last_hello_at})
622 1
        return JSONResponse({"interfaces": interfaces})
623
624 1
    @rest("v1/liveness/pair", methods=["GET"])
625 1
    async def get_liveness_interface_pairs(self,
626
                                           _request: Request) -> JSONResponse:
627
        """Get liveness interface pairs."""
628 1
        pairs = []
629 1
        for entry in list(self.liveness_manager.liveness.values()):
630
            lsm = entry["lsm"]
631
            pair = {
632
                "interface_a": {
633
                    "id": entry["interface_a"].id,
634
                    "status": lsm.ilsm_a.state,
635
                    "last_hello_at": lsm.ilsm_a.last_hello_at,
636
                },
637
                "interface_b": {
638
                    "id": entry["interface_b"].id,
639
                    "status": lsm.ilsm_b.state,
640
                    "last_hello_at": lsm.ilsm_b.last_hello_at,
641
                },
642
                "status": lsm.state
643
            }
644
            pairs.append(pair)
645 1
        return JSONResponse({"pairs": pairs})
646
647 1
    @rest('v1/polling_time', methods=['GET'])
648 1
    async def get_time(self, _request: Request) -> JSONResponse:
649
        """Get LLDP polling time in seconds."""
650 1
        return JSONResponse({"polling_time": self.polling_time})
651
652 1
    @rest('v1/polling_time', methods=['POST'])
653 1
    async def set_time(self, request: Request) -> JSONResponse:
654
        """Set LLDP polling time."""
655
        # pylint: disable=attribute-defined-outside-init
656 1
        try:
657 1
            payload = await aget_json_or_400(request)
658 1
            polling_time = int(payload['polling_time'])
659 1
            if polling_time <= 0:
660
                msg = f"invalid polling_time {polling_time}, " \
661
                        "must be greater than zero"
662
                raise HTTPException(400, detail=msg)
663 1
            self.polling_time = polling_time
664 1
            self.execute_as_loop(self.polling_time)
665 1
            log.info("Polling time has been updated to %s"
666
                     " second(s), but this change will not be saved"
667
                     " permanently.", self.polling_time)
668 1
            return JSONResponse("Polling time has been updated.")
669 1
        except (ValueError, KeyError) as error:
670 1
            msg = f"This operation is not completed: {error}"
671 1
            raise HTTPException(400, detail=msg) from error
672
673 1
    def set_flow_table_group_owner(self,
674
                                   flow: dict,
675
                                   group: str = "base") -> dict:
676
        """Set owner, table_group and table_id"""
677 1
        flow["table_id"] = self.table_group[group]
678 1
        flow["owner"] = "of_lldp"
679 1
        flow["table_group"] = group
680 1
        return flow
681
682
    # pylint: disable=attribute-defined-outside-init
683 1
    @alisten_to("kytos/of_multi_table.enable_table")
684 1
    async def on_table_enabled(self, event):
685
        """Handle a recently table enabled.
686
        of_lldp only allows "base" as flow group
687
        """
688 1
        table_group = event.content.get("of_lldp", None)
689 1
        if not table_group:
690
            return
691 1
        for group in table_group:
692 1
            if group not in settings.TABLE_GROUP_ALLOWED:
693 1
                log.error(f'The table group "{group}" is not allowed for '
694
                          f'of_lldp. Allowed table groups are '
695
                          f'{settings.TABLE_GROUP_ALLOWED}')
696 1
                return
697 1
        self.table_group.update(table_group)
698 1
        content = {"group_table": self.table_group}
699 1
        event_out = KytosEvent(name="kytos/of_lldp.enable_table",
700
                               content=content)
701
        await self.controller.buffers.app.aput(event_out)
702