Passed
Push — master ( 045ae5...4b578f )
by Vinicius
01:55 queued 13s
created
1
"""Main module of kytos/topology Kytos Network Application.
2
3
Manage the network topology
4
"""
5
# pylint: disable=wrong-import-order
6
7 1
import time
8 1
from collections import defaultdict
9 1
from datetime import timezone
10 1
from threading import Lock
11 1
from typing import List, Optional
12
13 1
from flask import jsonify, request
14 1
from werkzeug.exceptions import BadRequest, UnsupportedMediaType
15
16 1
from kytos.core import KytosEvent, KytosNApp, log, rest
17 1
from kytos.core.common import EntityStatus
18 1
from kytos.core.exceptions import KytosLinkCreationError
19 1
from kytos.core.helpers import listen_to, now
20 1
from kytos.core.interface import Interface
21 1
from kytos.core.link import Link
22 1
from kytos.core.switch import Switch
23 1
from napps.kytos.topology import settings
24
25 1
from .controllers import TopoController
26 1
from .exceptions import RestoreError
27 1
from .models import Topology
28
29 1
DEFAULT_LINK_UP_TIMER = 10
30
31
32 1
class Main(KytosNApp):  # pylint: disable=too-many-public-methods
33
    """Main class of kytos/topology NApp.
34
35
    This class is the entry point for this napp.
36
    """
37
38 1
    def setup(self):
39
        """Initialize the NApp's links list."""
40 1
        self.links = {}
41 1
        self.intf_available_tags = {}
42 1
        self.link_up_timer = getattr(settings, 'LINK_UP_TIMER',
43
                                     DEFAULT_LINK_UP_TIMER)
44
45 1
        self._links_lock = Lock()
46 1
        self._links_notify_lock = defaultdict(Lock)
47 1
        self.topo_controller = self.get_topo_controller()
48 1
        Link.register_status_func(f"{self.napp_id}_link_up_timer",
49
                                  self.link_status_hook_link_up_timer)
50 1
        self.topo_controller.bootstrap_indexes()
51 1
        self.load_topology()
52
53 1
    @staticmethod
54 1
    def get_topo_controller() -> TopoController:
55
        """Get TopoController."""
56
        return TopoController()
57
58 1
    def execute(self):
59
        """Execute once when the napp is running."""
60
        pass
61
62 1
    def shutdown(self):
63
        """Do nothing."""
64
        log.info('NApp kytos/topology shutting down.')
65
66 1
    @staticmethod
67 1
    def _get_metadata():
68
        """Return a JSON with metadata."""
69 1
        try:
70 1
            metadata = request.get_json()
71 1
            content_type = request.content_type
72 1
        except BadRequest as err:
73 1
            result = 'The request body is not a well-formed JSON.'
74 1
            raise BadRequest(result) from err
75 1
        if content_type is None:
76
            result = 'The request body is empty.'
77
            raise BadRequest(result)
78 1
        if metadata is None:
79 1
            if content_type != 'application/json':
80
                result = ('The content type must be application/json '
81
                          f'(received {content_type}).')
82
            else:
83 1
                result = 'Metadata is empty.'
84 1
            raise UnsupportedMediaType(result)
85 1
        return metadata
86
87 1
    def _get_link_or_create(self, endpoint_a, endpoint_b):
88
        """Get an existing link or create a new one.
89
90
        Returns:
91
            Tuple(Link, bool): Link and a boolean whether it has been created.
92
        """
93 1
        new_link = Link(endpoint_a, endpoint_b)
94
95 1
        for link in self.links.values():
96 1
            if new_link == link:
97 1
                return (link, False)
98
99 1
        self.links[new_link.id] = new_link
100 1
        return (new_link, True)
101
102 1
    def _get_switches_dict(self):
103
        """Return a dictionary with the known switches."""
104 1
        switches = {'switches': {}}
105 1
        for idx, switch in enumerate(self.controller.switches.copy().values()):
106 1
            switch_data = switch.as_dict()
107 1
            if not all(key in switch_data['metadata']
108
                       for key in ('lat', 'lng')):
109
                # Switches are initialized somewhere in the ocean
110
                switch_data['metadata']['lat'] = str(0.0)
111
                switch_data['metadata']['lng'] = str(-30.0+idx*10.0)
112 1
            switches['switches'][switch.id] = switch_data
113 1
        return switches
114
115 1
    def _get_links_dict(self):
116
        """Return a dictionary with the known links."""
117 1
        return {'links': {link.id: link.as_dict() for link in
118
                          self.links.copy().values()}}
119
120 1
    def _get_topology_dict(self):
121
        """Return a dictionary with the known topology."""
122 1
        return {'topology': {**self._get_switches_dict(),
123
                             **self._get_links_dict()}}
124
125 1
    def _get_topology(self):
126
        """Return an object representing the topology."""
127 1
        return Topology(self.controller.switches.copy(), self.links.copy())
128
129 1
    def _get_link_from_interface(self, interface):
130
        """Return the link of the interface, or None if it does not exist."""
131 1
        with self._links_lock:
132 1
            for link in self.links.values():
133 1
                if interface in (link.endpoint_a, link.endpoint_b):
134 1
                    return link
135 1
            return None
136
137 1
    def _load_link(self, link_att):
138 1
        endpoint_a = link_att['endpoint_a']['id']
139 1
        endpoint_b = link_att['endpoint_b']['id']
140 1
        link_str = link_att['id']
141 1
        log.info(f"Loading link: {link_str}")
142 1
        interface_a = self.controller.get_interface_by_id(endpoint_a)
143 1
        interface_b = self.controller.get_interface_by_id(endpoint_b)
144
145 1
        error = f"Fail to load endpoints for link {link_str}. "
146 1
        if not interface_a:
147 1
            raise RestoreError(f"{error}, endpoint_a {endpoint_a} not found")
148 1
        if not interface_b:
149
            raise RestoreError(f"{error}, endpoint_b {endpoint_b} not found")
150
151 1
        with self._links_lock:
152 1
            link, _ = self._get_link_or_create(interface_a, interface_b)
153
154 1
        if link_att['enabled']:
155 1
            link.enable()
156
        else:
157 1
            link.disable()
158
159 1
        link.extend_metadata(link_att["metadata"])
160 1
        interface_a.update_link(link)
161 1
        interface_b.update_link(link)
162 1
        interface_a.nni = True
163 1
        interface_b.nni = True
164
165 1
    def _load_switch(self, switch_id, switch_att):
166 1
        log.info(f'Loading switch dpid: {switch_id}')
167 1
        switch = self.controller.get_switch_or_create(switch_id)
168 1
        if switch_att['enabled']:
169 1
            switch.enable()
170
        else:
171 1
            switch.disable()
172 1
        switch.description['manufacturer'] = switch_att.get('manufacturer', '')
173 1
        switch.description['hardware'] = switch_att.get('hardware', '')
174 1
        switch.description['software'] = switch_att.get('software')
175 1
        switch.description['serial'] = switch_att.get('serial', '')
176 1
        switch.description['data_path'] = switch_att.get('data_path', '')
177 1
        switch.extend_metadata(switch_att["metadata"])
178
179 1
        for iface_id, iface_att in switch_att.get('interfaces', {}).items():
180 1
            log.info(f'Loading interface iface_id={iface_id}')
181 1
            interface = switch.update_or_create_interface(
182
                            port_no=iface_att['port_number'],
183
                            name=iface_att['name'],
184
                            address=iface_att.get('mac', None),
185
                            speed=iface_att.get('speed', None))
186 1
            if iface_att['enabled']:
187 1
                interface.enable()
188
            else:
189 1
                interface.disable()
190 1
            interface.lldp = iface_att['lldp']
191 1
            interface.extend_metadata(iface_att["metadata"])
192 1
            name = 'kytos/topology.port.created'
193 1
            event = KytosEvent(name=name, content={
194
                                              'switch': switch_id,
195
                                              'port': interface.port_number,
196
                                              'port_description': {
197
                                                  'alias': interface.name,
198
                                                  'mac': interface.address,
199
                                                  'state': interface.state
200
                                                  }
201
                                              })
202 1
            self.controller.buffers.app.put(event)
203
204 1
        intf_ids = [v["id"] for v in switch_att.get("interfaces", {}).values()]
205 1
        intf_details = self.topo_controller.get_interfaces_details(intf_ids)
206 1
        with self._links_lock:
207 1
            self.load_interfaces_available_tags(switch, intf_details)
208
209
    # pylint: disable=attribute-defined-outside-init
210 1
    def load_topology(self):
211
        """Load network topology from DB."""
212 1
        topology = self.topo_controller.get_topology()
213 1
        switches = topology["topology"]["switches"]
214 1
        links = topology["topology"]["links"]
215
216 1
        failed_switches = {}
217 1
        log.debug(f"_load_network_status switches={switches}")
218 1
        for switch_id, switch_att in switches.items():
219 1
            try:
220 1
                self._load_switch(switch_id, switch_att)
221
            # pylint: disable=broad-except
222 1
            except Exception as err:
223 1
                failed_switches[switch_id] = err
224 1
                log.error(f'Error loading switch: {err}')
225
226 1
        failed_links = {}
227 1
        log.debug(f"_load_network_status links={links}")
228 1
        for link_id, link_att in links.items():
229 1
            try:
230 1
                self._load_link(link_att)
231
            # pylint: disable=broad-except
232 1
            except Exception as err:
233 1
                failed_links[link_id] = err
234 1
                log.error(f'Error loading link {link_id}: {err}')
235
236 1
        name = 'kytos/topology.topology_loaded'
237 1
        event = KytosEvent(
238
            name=name,
239
            content={
240
                'topology': self._get_topology(),
241
                'failed_switches': failed_switches,
242
                'failed_links': failed_links
243
            })
244 1
        self.controller.buffers.app.put(event)
245
246 1
    @rest('v3/')
247 1
    def get_topology(self):
248
        """Return the latest known topology.
249
250
        This topology is updated when there are network events.
251
        """
252 1
        return jsonify(self._get_topology_dict())
253
254
    # Switch related methods
255 1
    @rest('v3/switches')
256 1
    def get_switches(self):
257
        """Return a json with all the switches in the topology."""
258
        return jsonify(self._get_switches_dict())
259
260 1
    @rest('v3/switches/<dpid>/enable', methods=['POST'])
261 1
    def enable_switch(self, dpid):
262
        """Administratively enable a switch in the topology."""
263 1
        try:
264 1
            switch = self.controller.switches[dpid]
265 1
            self.topo_controller.enable_switch(dpid)
266 1
            switch.enable()
267 1
        except KeyError:
268 1
            return jsonify("Switch not found"), 404
269
270 1
        self.notify_switch_enabled(dpid)
271 1
        self.notify_topology_update()
272 1
        self.notify_switch_links_status(switch, "link enabled")
273 1
        return jsonify("Operation successful"), 201
274
275 1
    @rest('v3/switches/<dpid>/disable', methods=['POST'])
276 1
    def disable_switch(self, dpid):
277
        """Administratively disable a switch in the topology."""
278 1
        try:
279 1
            switch = self.controller.switches[dpid]
280 1
            self.topo_controller.disable_switch(dpid)
281 1
            switch.disable()
282 1
        except KeyError:
283 1
            return jsonify("Switch not found"), 404
284
285 1
        self.notify_switch_disabled(dpid)
286 1
        self.notify_topology_update()
287 1
        self.notify_switch_links_status(switch, "link disabled")
288 1
        return jsonify("Operation successful"), 201
289
290 1
    @rest('v3/switches/<dpid>/metadata')
291 1
    def get_switch_metadata(self, dpid):
292
        """Get metadata from a switch."""
293 1
        try:
294 1
            return jsonify({"metadata":
295
                            self.controller.switches[dpid].metadata}), 200
296 1
        except KeyError:
297 1
            return jsonify("Switch not found"), 404
298
299 1
    @rest('v3/switches/<dpid>/metadata', methods=['POST'])
300 1
    def add_switch_metadata(self, dpid):
301
        """Add metadata to a switch."""
302 1
        metadata = self._get_metadata()
303
304 1
        try:
305 1
            switch = self.controller.switches[dpid]
306 1
        except KeyError:
307 1
            return jsonify("Switch not found"), 404
308
309 1
        self.topo_controller.add_switch_metadata(dpid, metadata)
310 1
        switch.extend_metadata(metadata)
311 1
        self.notify_metadata_changes(switch, 'added')
312 1
        return jsonify("Operation successful"), 201
313
314 1
    @rest('v3/switches/<dpid>/metadata/<key>', methods=['DELETE'])
315 1
    def delete_switch_metadata(self, dpid, key):
316
        """Delete metadata from a switch."""
317 1
        try:
318 1
            switch = self.controller.switches[dpid]
319 1
        except KeyError:
320 1
            return jsonify("Switch not found"), 404
321
322 1
        try:
323 1
            _ = switch.metadata[key]
324
        except KeyError:
325
            return jsonify("Metadata not found"), 404
326
327 1
        self.topo_controller.delete_switch_metadata_key(dpid, key)
328 1
        switch.remove_metadata(key)
329 1
        self.notify_metadata_changes(switch, 'removed')
330 1
        return jsonify("Operation successful"), 200
331
332
    # Interface related methods
333 1
    @rest('v3/interfaces')
334 1
    def get_interfaces(self):
335
        """Return a json with all the interfaces in the topology."""
336 1
        interfaces = {}
337 1
        switches = self._get_switches_dict()
338 1
        for switch in switches['switches'].values():
339 1
            for interface_id, interface in switch['interfaces'].items():
340 1
                interfaces[interface_id] = interface
341
342 1
        return jsonify({'interfaces': interfaces})
343
344 1 View Code Duplication
    @rest('v3/interfaces/switch/<dpid>/enable', methods=['POST'])
0 ignored issues
show
This code seems to be duplicated in your project.
Loading history...
345 1
    @rest('v3/interfaces/<interface_enable_id>/enable', methods=['POST'])
346 1
    def enable_interface(self, interface_enable_id=None, dpid=None):
347
        """Administratively enable interfaces in the topology."""
348 1
        if dpid is None:
349 1
            dpid = ":".join(interface_enable_id.split(":")[:-1])
350 1
        try:
351 1
            switch = self.controller.switches[dpid]
352 1
        except KeyError as exc:
353 1
            return jsonify(f"Switch not found: {exc}"), 404
354
355 1
        if interface_enable_id:
356 1
            interface_number = int(interface_enable_id.split(":")[-1])
357
358 1
            try:
359 1
                interface = switch.interfaces[interface_number]
360 1
                self.topo_controller.enable_interface(interface.id)
361 1
                interface.enable()
362 1
                self.notify_interface_link_status(interface, "link enabled")
363 1
            except KeyError:
364 1
                msg = f"Switch {dpid} interface {interface_number} not found"
365 1
                return jsonify(msg), 404
366
        else:
367 1
            for interface in switch.interfaces.copy().values():
368 1
                interface.enable()
369 1
                self.notify_interface_link_status(interface, "link enabled")
370 1
            self.topo_controller.upsert_switch(switch.id, switch.as_dict())
371 1
        self.notify_topology_update()
372 1
        return jsonify("Operation successful"), 200
373
374 1 View Code Duplication
    @rest('v3/interfaces/switch/<dpid>/disable', methods=['POST'])
0 ignored issues
show
This code seems to be duplicated in your project.
Loading history...
375 1
    @rest('v3/interfaces/<interface_disable_id>/disable', methods=['POST'])
376 1
    def disable_interface(self, interface_disable_id=None, dpid=None):
377
        """Administratively disable interfaces in the topology."""
378 1
        if dpid is None:
379 1
            dpid = ":".join(interface_disable_id.split(":")[:-1])
380 1
        try:
381 1
            switch = self.controller.switches[dpid]
382 1
        except KeyError as exc:
383 1
            return jsonify(f"Switch not found: {exc}"), 404
384
385 1
        if interface_disable_id:
386 1
            interface_number = int(interface_disable_id.split(":")[-1])
387
388 1
            try:
389 1
                interface = switch.interfaces[interface_number]
390 1
                self.topo_controller.disable_interface(interface.id)
391 1
                interface.disable()
392 1
                self.notify_interface_link_status(interface, "link disabled")
393 1
            except KeyError:
394 1
                msg = f"Switch {dpid} interface {interface_number} not found"
395 1
                return jsonify(msg), 404
396
        else:
397 1
            for interface in switch.interfaces.copy().values():
398 1
                interface.disable()
399 1
                self.notify_interface_link_status(interface, "link disabled")
400 1
            self.topo_controller.upsert_switch(switch.id, switch.as_dict())
401 1
        self.notify_topology_update()
402 1
        return jsonify("Operation successful"), 200
403
404 1
    @rest('v3/interfaces/<interface_id>/metadata')
405 1
    def get_interface_metadata(self, interface_id):
406
        """Get metadata from an interface."""
407 1
        switch_id = ":".join(interface_id.split(":")[:-1])
408 1
        interface_number = int(interface_id.split(":")[-1])
409 1
        try:
410 1
            switch = self.controller.switches[switch_id]
411 1
        except KeyError:
412 1
            return jsonify("Switch not found"), 404
413
414 1
        try:
415 1
            interface = switch.interfaces[interface_number]
416 1
        except KeyError:
417 1
            return jsonify("Interface not found"), 404
418
419 1
        return jsonify({"metadata": interface.metadata}), 200
420
421 1
    @rest('v3/interfaces/<interface_id>/metadata', methods=['POST'])
422 1
    def add_interface_metadata(self, interface_id):
423
        """Add metadata to an interface."""
424 1
        metadata = self._get_metadata()
425 1
        switch_id = ":".join(interface_id.split(":")[:-1])
426 1
        interface_number = int(interface_id.split(":")[-1])
427 1
        try:
428 1
            switch = self.controller.switches[switch_id]
429 1
        except KeyError:
430 1
            return jsonify("Switch not found"), 404
431
432 1
        try:
433 1
            interface = switch.interfaces[interface_number]
434 1
            self.topo_controller.add_interface_metadata(interface.id, metadata)
435 1
        except KeyError:
436 1
            return jsonify("Interface not found"), 404
437
438 1
        interface.extend_metadata(metadata)
439 1
        self.notify_metadata_changes(interface, 'added')
440 1
        return jsonify("Operation successful"), 201
441
442 1
    @rest('v3/interfaces/<interface_id>/metadata/<key>', methods=['DELETE'])
443 1
    def delete_interface_metadata(self, interface_id, key):
444
        """Delete metadata from an interface."""
445 1
        switch_id = ":".join(interface_id.split(":")[:-1])
446 1
        interface_number = int(interface_id.split(":")[-1])
447
448 1
        try:
449 1
            switch = self.controller.switches[switch_id]
450 1
        except KeyError:
451 1
            return jsonify("Switch not found"), 404
452
453 1
        try:
454 1
            interface = switch.interfaces[interface_number]
455 1
        except KeyError:
456 1
            return jsonify("Interface not found"), 404
457
458 1
        try:
459 1
            _ = interface.metadata[key]
460 1
        except KeyError:
461 1
            return jsonify("Metadata not found"), 404
462
463 1
        self.topo_controller.delete_interface_metadata_key(interface.id, key)
464 1
        interface.remove_metadata(key)
465 1
        self.notify_metadata_changes(interface, 'removed')
466 1
        return jsonify("Operation successful"), 200
467
468
    # Link related methods
469 1
    @rest('v3/links')
470 1
    def get_links(self):
471
        """Return a json with all the links in the topology.
472
473
        Links are connections between interfaces.
474
        """
475
        return jsonify(self._get_links_dict()), 200
476
477 1
    @rest('v3/links/<link_id>/enable', methods=['POST'])
478 1
    def enable_link(self, link_id):
479
        """Administratively enable a link in the topology."""
480 1
        try:
481 1
            with self._links_lock:
482 1
                link = self.links[link_id]
483 1
                self.topo_controller.enable_link(link_id)
484 1
                link.enable()
485 1
        except KeyError:
486 1
            return jsonify("Link not found"), 404
487 1
        self.notify_link_status_change(
488
            self.links[link_id],
489
            reason='link enabled'
490
        )
491 1
        self.notify_topology_update()
492 1
        return jsonify("Operation successful"), 201
493
494 1
    @rest('v3/links/<link_id>/disable', methods=['POST'])
495 1
    def disable_link(self, link_id):
496
        """Administratively disable a link in the topology."""
497 1
        try:
498 1
            with self._links_lock:
499 1
                link = self.links[link_id]
500 1
                self.topo_controller.disable_link(link_id)
501 1
                link.disable()
502 1
        except KeyError:
503 1
            return jsonify("Link not found"), 404
504 1
        self.notify_link_status_change(
505
            self.links[link_id],
506
            reason='link disabled'
507
        )
508 1
        self.notify_topology_update()
509 1
        return jsonify("Operation successful"), 201
510
511 1
    @rest('v3/links/<link_id>/metadata')
512 1
    def get_link_metadata(self, link_id):
513
        """Get metadata from a link."""
514 1
        try:
515 1
            return jsonify({"metadata": self.links[link_id].metadata}), 200
516 1
        except KeyError:
517 1
            return jsonify("Link not found"), 404
518
519 1
    @rest('v3/links/<link_id>/metadata', methods=['POST'])
520 1
    def add_link_metadata(self, link_id):
521
        """Add metadata to a link."""
522 1
        metadata = self._get_metadata()
523 1
        try:
524 1
            link = self.links[link_id]
525 1
        except KeyError:
526 1
            return jsonify("Link not found"), 404
527
528 1
        self.topo_controller.add_link_metadata(link_id, metadata)
529 1
        link.extend_metadata(metadata)
530 1
        self.notify_metadata_changes(link, 'added')
531 1
        return jsonify("Operation successful"), 201
532
533 1
    @rest('v3/links/<link_id>/metadata/<key>', methods=['DELETE'])
534 1
    def delete_link_metadata(self, link_id, key):
535
        """Delete metadata from a link."""
536 1
        try:
537 1
            link = self.links[link_id]
538 1
        except KeyError:
539 1
            return jsonify("Link not found"), 404
540
541 1
        try:
542 1
            _ = link.metadata[key]
543 1
        except KeyError:
544 1
            return jsonify("Metadata not found"), 404
545
546 1
        self.topo_controller.delete_link_metadata_key(link.id, key)
547 1
        link.remove_metadata(key)
548 1
        self.notify_metadata_changes(link, 'removed')
549 1
        return jsonify("Operation successful"), 200
550
551 1
    def notify_current_topology(self) -> None:
552
        """Notify current topology."""
553 1
        name = "kytos/topology.current"
554 1
        event = KytosEvent(name=name, content={"topology":
555
                                               self._get_topology()})
556 1
        self.controller.buffers.app.put(event)
557
558 1
    @listen_to("kytos/topology.get")
559 1
    def on_get_topology(self, _event) -> None:
560
        """Handle kytos/topology.get."""
561
        self.notify_current_topology()
562
563 1
    @listen_to("kytos/.*.liveness.(up|down)")
564 1
    def on_link_liveness_status(self, event) -> None:
565
        """Handle link liveness up|down status event."""
566
        link = Link(event.content["interface_a"], event.content["interface_b"])
567
        try:
568
            link = self.links[link.id]
569
        except KeyError:
570
            log.error(f"Link id {link.id} not found, {link}")
571
            return
572
        liveness_status = event.name.split(".")[-1]
573
        self.handle_link_liveness_status(self.links[link.id], liveness_status)
574
575 1
    def handle_link_liveness_status(self, link, liveness_status) -> None:
576
        """Handle link liveness."""
577 1
        metadata = {"liveness_status": liveness_status}
578 1
        log.info(f"Link liveness {liveness_status}: {link}")
579 1
        self.topo_controller.add_link_metadata(link.id, metadata)
580 1
        link.extend_metadata(metadata)
581 1
        self.notify_topology_update()
582 1
        if link.status == EntityStatus.UP and liveness_status == "up":
583 1
            self.notify_link_status_change(link, reason="liveness_up")
584 1
        if link.status == EntityStatus.DOWN and liveness_status == "down":
585 1
            self.notify_link_status_change(link, reason="liveness_down")
586
587 1
    @listen_to("kytos/.*.liveness.disabled")
588 1
    def on_link_liveness_disabled(self, event) -> None:
589
        """Handle link liveness disabled event."""
590
        interfaces = event.content["interfaces"]
591
        self.handle_link_liveness_disabled(interfaces)
592
593 1
    def get_links_from_interfaces(self, interfaces) -> dict:
594
        """Get links from interfaces."""
595 1
        links_found = {}
596 1
        with self._links_lock:
597 1
            for interface in interfaces:
598 1
                for link in self.links.values():
599 1
                    if any((
600
                        interface.id == link.endpoint_a.id,
601
                        interface.id == link.endpoint_b.id,
602
                    )):
603 1
                        links_found[link.id] = link
604 1
        return links_found
605
606 1
    def handle_link_liveness_disabled(self, interfaces) -> None:
607
        """Handle link liveness disabled."""
608 1
        log.info(f"Link liveness disabled interfaces: {interfaces}")
609
610 1
        key = "liveness_status"
611 1
        links = self.get_links_from_interfaces(interfaces)
612 1
        for link in links.values():
613 1
            link.remove_metadata(key)
614 1
        link_ids = list(links.keys())
615 1
        self.topo_controller.bulk_delete_link_metadata_key(link_ids, key)
616 1
        self.notify_topology_update()
617 1
        for link in links.values():
618 1
            self.notify_link_status_change(link, reason="liveness_disabled")
619
620 1
    @listen_to("kytos/.*.link_available_tags")
621 1
    def on_link_available_tags(self, event):
622
        """Handle on_link_available_tags."""
623
        with self._links_lock:
624
            self.handle_on_link_available_tags(event.content.get("link"))
625
626 1
    def handle_on_link_available_tags(self, link):
627
        """Handle on_link_available_tags."""
628 1
        if link.id not in self.links:
629
            return
630 1
        endpoint_a = self.links[link.id].endpoint_a
631 1
        endpoint_b = self.links[link.id].endpoint_b
632 1
        values_a = [tag.value for tag in endpoint_a.available_tags]
633 1
        values_b = [tag.value for tag in endpoint_b.available_tags]
634 1
        ids_details = [
635
            (endpoint_a.id, {"_id": endpoint_a.id,
636
                             "available_vlans": values_a}),
637
            (endpoint_b.id, {"_id": endpoint_b.id,
638
                             "available_vlans": values_b})
639
        ]
640 1
        self.topo_controller.bulk_upsert_interface_details(ids_details)
641
642 1
    @listen_to('.*.switch.(new|reconnected)')
643 1
    def on_new_switch(self, event):
644
        """Create a new Device on the Topology.
645
646
        Handle the event of a new created switch and update the topology with
647
        this new device. Also notify if the switch is enabled.
648
        """
649
        self.handle_new_switch(event)
650
651 1
    def handle_new_switch(self, event):
652
        """Create a new Device on the Topology."""
653 1
        switch = event.content['switch']
654 1
        switch.activate()
655 1
        self.topo_controller.upsert_switch(switch.id, switch.as_dict())
656 1
        log.debug('Switch %s added to the Topology.', switch.id)
657 1
        self.notify_topology_update()
658 1
        if switch.is_enabled():
659 1
            self.notify_switch_enabled(switch.id)
660
661 1
    @listen_to('.*.connection.lost')
662 1
    def on_connection_lost(self, event):
663
        """Remove a Device from the topology.
664
665
        Remove the disconnected Device and every link that has one of its
666
        interfaces.
667
        """
668
        self.handle_connection_lost(event)
669
670 1
    def handle_connection_lost(self, event):
671
        """Remove a Device from the topology."""
672 1
        switch = event.content['source'].switch
673 1
        if switch:
674 1
            switch.deactivate()
675 1
            self.topo_controller.deactivate_switch(switch.id)
676 1
            log.debug('Switch %s removed from the Topology.', switch.id)
677 1
            self.notify_topology_update()
678
679 1
    def handle_interfaces_created(self, event):
680
        """Update the topology based on the interfaces created."""
681 1
        interfaces = event.content["interfaces"]
682 1
        if not interfaces:
683
            return
684 1
        switch = interfaces[0].switch
685 1
        self.topo_controller.upsert_switch(switch.id, switch.as_dict())
686 1
        name = "kytos/topology.switch.interface.created"
687 1
        for interface in interfaces:
688 1
            event = KytosEvent(name=name, content={'interface': interface})
689 1
            self.controller.buffers.app.put(event)
690
691 1
    def handle_interface_created(self, event):
692
        """Update the topology based on an interface created event.
693
694
        It's handled as a link_up in case a switch send a
695
        created event again and it can be belong to a link.
696
        """
697 1
        interface = event.content['interface']
698 1
        self.handle_interface_link_up(interface)
699
700 1
    @listen_to('.*.topology.switch.interface.created')
701 1
    def on_interface_created(self, event):
702
        """Handle individual interface create event.
703
704
        It's handled as a link_up in case a switch send a
705
        created event it can belong to an existign link.
706
        """
707
        self.handle_interface_created(event)
708
709 1
    @listen_to('.*.switch.interfaces.created')
710 1
    def on_interfaces_created(self, event):
711
        """Update the topology based on a list of created interfaces."""
712
        self.handle_interfaces_created(event)
713
714 1
    def handle_interface_down(self, event):
715
        """Update the topology based on a Port Modify event.
716
717
        The event notifies that an interface was changed to 'down'.
718
        """
719 1
        interface = event.content['interface']
720 1
        interface.deactivate()
721 1
        self.topo_controller.deactivate_interface(interface.id)
722 1
        self.handle_interface_link_down(interface)
723
724 1
    @listen_to('.*.switch.interface.deleted')
725 1
    def on_interface_deleted(self, event):
726
        """Update the topology based on a Port Delete event."""
727
        self.handle_interface_deleted(event)
728
729 1
    def handle_interface_deleted(self, event):
730
        """Update the topology based on a Port Delete event."""
731 1
        self.handle_interface_down(event)
732
733 1
    @listen_to('.*.switch.interface.link_up')
734 1
    def on_interface_link_up(self, event):
735
        """Update the topology based on a Port Modify event.
736
737
        The event notifies that an interface's link was changed to 'up'.
738
        """
739
        interface = event.content['interface']
740
        self.handle_interface_link_up(interface)
741
742 1
    def handle_interface_link_up(self, interface):
743
        """Update the topology based on a Port Modify event."""
744 1
        self.handle_link_up(interface)
745
746 1
    @listen_to('kytos/maintenance.end_switch')
747 1
    def on_switch_maintenance_end(self, event):
748
        """Handle the end of the maintenance of a switch."""
749
        self.handle_switch_maintenance_end(event)
750
751 1
    def handle_switch_maintenance_end(self, event):
752
        """Handle the end of the maintenance of a switch."""
753 1
        switches = event.content['switches']
754 1
        for switch in switches:
755 1
            switch.enable()
756 1
            switch.activate()
757 1
            for interface in switch.interfaces.values():
758 1
                interface.enable()
759 1
                self.handle_link_up(interface)
760
761 1
    def link_status_hook_link_up_timer(self, link) -> Optional[EntityStatus]:
762
        """Link status hook link up timer."""
763 1
        tnow = time.time()
764 1
        if (
765
            link.is_active()
766
            and link.is_enabled()
767
            and "last_status_change" in link.metadata
768
            and tnow - link.metadata['last_status_change'] < self.link_up_timer
769
        ):
770 1
            return EntityStatus.DOWN
771 1
        return None
772
773 1
    def notify_link_up_if_status(self, link, reason="link up") -> None:
774
        """Tries to notify link up and topology changes based on its status
775
776
        Currently, it needs to wait up to a timer."""
777 1
        time.sleep(self.link_up_timer)
778 1
        if link.status != EntityStatus.UP:
779
            return
780 1
        with self._links_notify_lock[link.id]:
781 1
            notified_at = link.get_metadata("notified_up_at")
782 1
            if (
783
                notified_at
784
                and (now() - notified_at.replace(tzinfo=timezone.utc)).seconds
785
                < self.link_up_timer
786
            ):
787 1
                return
788 1
            key, notified_at = "notified_up_at", now()
789 1
            link.update_metadata(key, now())
790 1
            self.topo_controller.add_link_metadata(link.id, {key: notified_at})
791 1
            self.notify_topology_update()
792 1
            self.notify_link_status_change(link, reason)
793
794 1
    def handle_link_up(self, interface):
795
        """Handle link up for an interface."""
796 1
        interface.activate()
797 1
        self.topo_controller.activate_interface(interface.id)
798 1
        self.notify_topology_update()
799 1
        link = self._get_link_from_interface(interface)
800 1
        if not link:
801
            return
802 1
        if link.endpoint_a == interface:
803 1
            other_interface = link.endpoint_b
804
        else:
805 1
            other_interface = link.endpoint_a
806 1
        if other_interface.is_active() is False:
807 1
            return
808 1
        metadata = {
809
            'last_status_change': time.time(),
810
            'last_status_is_active': True
811
        }
812 1
        link.extend_metadata(metadata)
813 1
        link.activate()
814 1
        self.topo_controller.activate_link(link.id, **metadata)
815 1
        self.notify_link_up_if_status(link, "link up")
816
817 1
    @listen_to('.*.switch.interface.link_down')
818 1
    def on_interface_link_down(self, event):
819
        """Update the topology based on a Port Modify event.
820
821
        The event notifies that an interface's link was changed to 'down'.
822
        """
823
        interface = event.content['interface']
824
        self.handle_interface_link_down(interface)
825
826 1
    def handle_interface_link_down(self, interface):
827
        """Update the topology based on an interface."""
828 1
        self.handle_link_down(interface)
829
830 1
    @listen_to('kytos/maintenance.start_switch')
831 1
    def on_switch_maintenance_start(self, event):
832
        """Handle the start of the maintenance of a switch."""
833
        self.handle_switch_maintenance_start(event)
834
835 1
    def handle_switch_maintenance_start(self, event):
836
        """Handle the start of the maintenance of a switch."""
837 1
        switches = event.content['switches']
838 1
        for switch in switches:
839 1
            switch.disable()
840 1
            switch.deactivate()
841 1
            for interface in switch.interfaces.values():
842 1
                interface.disable()
843 1
                if interface.is_active():
844 1
                    self.handle_link_down(interface)
845
846 1
    def handle_link_down(self, interface):
847
        """Notify a link is down."""
848 1
        link = self._get_link_from_interface(interface)
849 1
        if link and link.is_active():
850 1
            link.deactivate()
851 1
            last_status_change = time.time()
852 1
            last_status_is_active = False
853 1
            metadata = {
854
                "last_status_change": last_status_change,
855
                "last_status_is_active": last_status_is_active,
856
            }
857 1
            link.extend_metadata(metadata)
858 1
            self.topo_controller.deactivate_link(link.id, last_status_change,
859
                                                 last_status_is_active)
860 1
            self.notify_link_status_change(link, reason="link down")
861 1
        if link and not link.is_active():
862 1
            with self._links_lock:
863 1
                last_status = link.get_metadata('last_status_is_active')
864 1
                last_status_change = link.get_metadata('last_status_change')
865 1
                metadata = {
866
                    "last_status_change": last_status_change,
867
                    "last_status_is_active": last_status,
868
                }
869 1
                if last_status:
870
                    link.extend_metadata(metadata)
871
                    self.topo_controller.deactivate_link(link.id,
872
                                                         last_status_change,
873
                                                         last_status)
874
                    self.notify_link_status_change(link, reason='link down')
875 1
        interface.deactivate()
876 1
        self.topo_controller.deactivate_interface(interface.id)
877 1
        self.notify_topology_update()
878
879 1
    @listen_to('.*.interface.is.nni')
880 1
    def on_add_links(self, event):
881
        """Update the topology with links related to the NNI interfaces."""
882
        self.add_links(event)
883
884 1
    def add_links(self, event):
885
        """Update the topology with links related to the NNI interfaces."""
886 1
        interface_a = event.content['interface_a']
887 1
        interface_b = event.content['interface_b']
888
889 1
        try:
890 1
            with self._links_lock:
891 1
                link, created = self._get_link_or_create(interface_a,
892
                                                         interface_b)
893 1
                interface_a.update_link(link)
894 1
                interface_b.update_link(link)
895
896 1
                link.endpoint_a = interface_a
897 1
                link.endpoint_b = interface_b
898
899 1
                interface_a.nni = True
900 1
                interface_b.nni = True
901
902
        except KytosLinkCreationError as err:
903
            log.error(f'Error creating link: {err}.')
904
            return
905
906 1
        if not created:
907
            return
908
909 1
        self.notify_topology_update()
910 1
        if not link.is_active():
911
            return
912
913 1
        metadata = {
914
            'last_status_change': time.time(),
915
            'last_status_is_active': True
916
        }
917 1
        link.extend_metadata(metadata)
918 1
        self.topo_controller.upsert_link(link.id, link.as_dict())
919 1
        self.notify_link_up_if_status(link, "link up")
920
921 1
    @listen_to('.*.of_lldp.network_status.updated')
922 1
    def on_lldp_status_updated(self, event):
923
        """Handle of_lldp.network_status.updated from of_lldp."""
924
        self.handle_lldp_status_updated(event)
925
926 1
    @listen_to(".*.topo_controller.upsert_switch")
927 1
    def on_topo_controller_upsert_switch(self, event) -> None:
928
        """Listen to topo_controller_upsert_switch."""
929
        self.handle_topo_controller_upsert_switch(event.content["switch"])
930
931 1
    def handle_topo_controller_upsert_switch(self, switch) -> Optional[dict]:
932
        """Handle topo_controller_upsert_switch."""
933 1
        return self.topo_controller.upsert_switch(switch.id, switch.as_dict())
934
935 1
    def handle_lldp_status_updated(self, event) -> None:
936
        """Handle .*.network_status.updated events from of_lldp."""
937 1
        content = event.content
938 1
        interface_ids = content["interface_ids"]
939 1
        switches = set()
940 1
        for interface_id in interface_ids:
941 1
            dpid = ":".join(interface_id.split(":")[:-1])
942 1
            switch = self.controller.get_switch_by_dpid(dpid)
943 1
            if switch:
944 1
                switches.add(switch)
945
946 1
        name = "kytos/topology.topo_controller.upsert_switch"
947 1
        for switch in switches:
948 1
            event = KytosEvent(name=name, content={"switch": switch})
949 1
            self.controller.buffers.app.put(event)
950
951 1
    def notify_switch_enabled(self, dpid):
952
        """Send an event to notify that a switch is enabled."""
953 1
        name = 'kytos/topology.switch.enabled'
954 1
        event = KytosEvent(name=name, content={'dpid': dpid})
955 1
        self.controller.buffers.app.put(event)
956
957 1
    def notify_switch_links_status(self, switch, reason):
958
        """Send an event to notify the status of a link in a switch"""
959 1
        with self._links_lock:
960 1
            for link in self.links.values():
961 1
                if switch in (link.endpoint_a.switch, link.endpoint_b.switch):
962 1
                    if reason == "link enabled":
963 1
                        name = 'kytos/topology.notify_link_up_if_status'
964 1
                        content = {'reason': reason, "link": link}
965 1
                        event = KytosEvent(name=name, content=content)
966 1
                        self.controller.buffers.app.put(event)
967
                    else:
968 1
                        self.notify_link_status_change(link, reason)
969
970 1
    def notify_switch_disabled(self, dpid):
971
        """Send an event to notify that a switch is disabled."""
972 1
        name = 'kytos/topology.switch.disabled'
973 1
        event = KytosEvent(name=name, content={'dpid': dpid})
974 1
        self.controller.buffers.app.put(event)
975
976 1
    def notify_topology_update(self):
977
        """Send an event to notify about updates on the topology."""
978 1
        name = 'kytos/topology.updated'
979 1
        event = KytosEvent(name=name, content={'topology':
980
                                               self._get_topology()})
981 1
        self.controller.buffers.app.put(event)
982
983 1
    def notify_interface_link_status(self, interface, reason):
984
        """Send an event to notify the status of a link from
985
        an interface."""
986 1
        link = self._get_link_from_interface(interface)
987 1
        if link:
988 1
            if reason == "link enabled":
989 1
                name = 'kytos/topology.notify_link_up_if_status'
990 1
                content = {'reason': reason, "link": link}
991 1
                event = KytosEvent(name=name, content=content)
992 1
                self.controller.buffers.app.put(event)
993
            else:
994 1
                self.notify_link_status_change(link, reason)
995
996 1
    def notify_link_status_change(self, link, reason='not given'):
997
        """Send an event to notify about a status change on a link."""
998 1
        name = 'kytos/topology.'
999 1
        if link.status == EntityStatus.UP:
1000
            status = 'link_up'
1001
        else:
1002 1
            status = 'link_down'
1003 1
        event = KytosEvent(
1004
            name=name+status,
1005
            content={
1006
                'link': link,
1007
                'reason': reason
1008
            })
1009 1
        self.controller.buffers.app.put(event)
1010
1011 1
    def notify_metadata_changes(self, obj, action):
1012
        """Send an event to notify about metadata changes."""
1013 1
        if isinstance(obj, Switch):
1014 1
            entity = 'switch'
1015 1
            entities = 'switches'
1016 1
        elif isinstance(obj, Interface):
1017 1
            entity = 'interface'
1018 1
            entities = 'interfaces'
1019 1
        elif isinstance(obj, Link):
1020 1
            entity = 'link'
1021 1
            entities = 'links'
1022
        else:
1023 1
            raise ValueError(
1024
                'Invalid object, supported: Switch, Interface, Link'
1025
            )
1026
1027 1
        name = f'kytos/topology.{entities}.metadata.{action}'
1028 1
        content = {entity: obj, 'metadata': obj.metadata.copy()}
1029 1
        event = KytosEvent(name=name, content=content)
1030 1
        self.controller.buffers.app.put(event)
1031 1
        log.debug(f'Metadata from {obj.id} was {action}.')
1032
1033 1
    @listen_to('kytos/topology.notify_link_up_if_status')
1034 1
    def on_notify_link_up_if_status(self, event):
1035
        """Tries to notify link up and topology changes"""
1036
        link = event.content["link"]
1037
        reason = event.content["reason"]
1038
        self.notify_link_up_if_status(link, reason)
1039
1040 1
    @listen_to('.*.switch.port.created')
1041 1
    def on_notify_port_created(self, event):
1042
        """Notify when a port is created."""
1043
        self.notify_port_created(event)
1044
1045 1
    def notify_port_created(self, event):
1046
        """Notify when a port is created."""
1047 1
        name = 'kytos/topology.port.created'
1048 1
        event = KytosEvent(name=name, content=event.content)
1049 1
        self.controller.buffers.app.put(event)
1050
1051 1
    @staticmethod
1052 1
    def load_interfaces_available_tags(switch: Switch,
1053
                                       interfaces_details: List[dict]) -> None:
1054
        """Load interfaces available tags (vlans)."""
1055 1
        if not interfaces_details:
1056
            return
1057 1
        for interface_details in interfaces_details:
1058 1
            available_vlans = interface_details["available_vlans"]
1059 1
            if not available_vlans:
1060
                continue
1061 1
            log.debug(f"Interface id {interface_details['id']} loading "
1062
                      f"{len(interface_details['available_vlans'])} "
1063
                      "available tags")
1064 1
            port_number = int(interface_details["id"].split(":")[-1])
1065 1
            interface = switch.interfaces[port_number]
1066 1
            interface.set_available_tags(interface_details['available_vlans'])
1067
1068 1
    @listen_to('kytos/maintenance.start_link')
1069 1
    def on_link_maintenance_start(self, event):
1070
        """Deals with the start of links maintenance."""
1071
        with self._links_lock:
1072
            self.handle_link_maintenance_start(event)
1073
1074 1
    def handle_link_maintenance_start(self, event):
1075
        """Deals with the start of links maintenance."""
1076 1
        notify_links = []
1077 1
        maintenance_links = event.content['links']
1078 1
        for maintenance_link in maintenance_links:
1079 1
            try:
1080 1
                link = self.links[maintenance_link.id]
1081 1
            except KeyError:
1082 1
                continue
1083 1
            notify_links.append(link)
1084 1
        for link in notify_links:
1085 1
            link.disable()
1086 1
            link.deactivate()
1087 1
            link.endpoint_a.deactivate()
1088 1
            link.endpoint_b.deactivate()
1089 1
            link.endpoint_a.disable()
1090 1
            link.endpoint_b.disable()
1091 1
            self.notify_link_status_change(link, reason='maintenance')
1092
1093 1
    @listen_to('kytos/maintenance.end_link')
1094 1
    def on_link_maintenance_end(self, event):
1095
        """Deals with the end of links maintenance."""
1096
        with self._links_lock:
1097
            self.handle_link_maintenance_end(event)
1098
1099 1
    def handle_link_maintenance_end(self, event):
1100
        """Deals with the end of links maintenance."""
1101 1
        notify_links = []
1102 1
        maintenance_links = event.content['links']
1103 1
        for maintenance_link in maintenance_links:
1104 1
            try:
1105 1
                link = self.links[maintenance_link.id]
1106 1
            except KeyError:
1107 1
                continue
1108 1
            notify_links.append(link)
1109 1
        for link in notify_links:
1110 1
            link.enable()
1111 1
            link.activate()
1112 1
            link.endpoint_a.activate()
1113 1
            link.endpoint_b.activate()
1114 1
            link.endpoint_a.enable()
1115 1
            link.endpoint_b.enable()
1116
            self.notify_link_status_change(link, reason='maintenance')
1117