Passed
Push — master ( 7054ad...045ae5 )
by Vinicius
09:28 queued 07:48
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
        return jsonify("Operation successful"), 201
273
274 1
    @rest('v3/switches/<dpid>/disable', methods=['POST'])
275 1
    def disable_switch(self, dpid):
276
        """Administratively disable a switch in the topology."""
277 1
        try:
278 1
            switch = self.controller.switches[dpid]
279 1
            self.topo_controller.disable_switch(dpid)
280 1
            switch.disable()
281 1
        except KeyError:
282 1
            return jsonify("Switch not found"), 404
283
284 1
        self.notify_switch_disabled(dpid)
285 1
        self.notify_topology_update()
286 1
        return jsonify("Operation successful"), 201
287
288 1
    @rest('v3/switches/<dpid>/metadata')
289 1
    def get_switch_metadata(self, dpid):
290
        """Get metadata from a switch."""
291 1
        try:
292 1
            return jsonify({"metadata":
293
                            self.controller.switches[dpid].metadata}), 200
294 1
        except KeyError:
295 1
            return jsonify("Switch not found"), 404
296
297 1
    @rest('v3/switches/<dpid>/metadata', methods=['POST'])
298 1
    def add_switch_metadata(self, dpid):
299
        """Add metadata to a switch."""
300 1
        metadata = self._get_metadata()
301
302 1
        try:
303 1
            switch = self.controller.switches[dpid]
304 1
        except KeyError:
305 1
            return jsonify("Switch not found"), 404
306
307 1
        self.topo_controller.add_switch_metadata(dpid, metadata)
308 1
        switch.extend_metadata(metadata)
309 1
        self.notify_metadata_changes(switch, 'added')
310 1
        return jsonify("Operation successful"), 201
311
312 1
    @rest('v3/switches/<dpid>/metadata/<key>', methods=['DELETE'])
313 1
    def delete_switch_metadata(self, dpid, key):
314
        """Delete metadata from a switch."""
315 1
        try:
316 1
            switch = self.controller.switches[dpid]
317 1
        except KeyError:
318 1
            return jsonify("Switch not found"), 404
319
320 1
        try:
321 1
            _ = switch.metadata[key]
322
        except KeyError:
323
            return jsonify("Metadata not found"), 404
324
325 1
        self.topo_controller.delete_switch_metadata_key(dpid, key)
326 1
        switch.remove_metadata(key)
327 1
        self.notify_metadata_changes(switch, 'removed')
328 1
        return jsonify("Operation successful"), 200
329
330
    # Interface related methods
331 1
    @rest('v3/interfaces')
332 1
    def get_interfaces(self):
333
        """Return a json with all the interfaces in the topology."""
334 1
        interfaces = {}
335 1
        switches = self._get_switches_dict()
336 1
        for switch in switches['switches'].values():
337 1
            for interface_id, interface in switch['interfaces'].items():
338 1
                interfaces[interface_id] = interface
339
340 1
        return jsonify({'interfaces': interfaces})
341
342 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...
343 1
    @rest('v3/interfaces/<interface_enable_id>/enable', methods=['POST'])
344 1
    def enable_interface(self, interface_enable_id=None, dpid=None):
345
        """Administratively enable interfaces in the topology."""
346 1
        if dpid is None:
347 1
            dpid = ":".join(interface_enable_id.split(":")[:-1])
348 1
        try:
349 1
            switch = self.controller.switches[dpid]
350 1
        except KeyError as exc:
351 1
            return jsonify(f"Switch not found: {exc}"), 404
352
353 1
        if interface_enable_id:
354 1
            interface_number = int(interface_enable_id.split(":")[-1])
355
356 1
            try:
357 1
                interface = switch.interfaces[interface_number]
358 1
                self.topo_controller.enable_interface(interface.id)
359 1
                interface.enable()
360 1
            except KeyError:
361 1
                msg = f"Switch {dpid} interface {interface_number} not found"
362 1
                return jsonify(msg), 404
363
        else:
364 1
            for interface in switch.interfaces.copy().values():
365 1
                interface.enable()
366 1
            self.topo_controller.upsert_switch(switch.id, switch.as_dict())
367 1
        self.notify_topology_update()
368 1
        return jsonify("Operation successful"), 200
369
370 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...
371 1
    @rest('v3/interfaces/<interface_disable_id>/disable', methods=['POST'])
372 1
    def disable_interface(self, interface_disable_id=None, dpid=None):
373
        """Administratively disable interfaces in the topology."""
374 1
        if dpid is None:
375 1
            dpid = ":".join(interface_disable_id.split(":")[:-1])
376 1
        try:
377 1
            switch = self.controller.switches[dpid]
378 1
        except KeyError as exc:
379 1
            return jsonify(f"Switch not found: {exc}"), 404
380
381 1
        if interface_disable_id:
382 1
            interface_number = int(interface_disable_id.split(":")[-1])
383
384 1
            try:
385 1
                interface = switch.interfaces[interface_number]
386 1
                self.topo_controller.disable_interface(interface.id)
387 1
                interface.disable()
388 1
            except KeyError:
389 1
                msg = f"Switch {dpid} interface {interface_number} not found"
390 1
                return jsonify(msg), 404
391
        else:
392 1
            for interface in switch.interfaces.copy().values():
393 1
                interface.disable()
394 1
            self.topo_controller.upsert_switch(switch.id, switch.as_dict())
395 1
        self.notify_topology_update()
396 1
        return jsonify("Operation successful"), 200
397
398 1
    @rest('v3/interfaces/<interface_id>/metadata')
399 1
    def get_interface_metadata(self, interface_id):
400
        """Get metadata from an interface."""
401 1
        switch_id = ":".join(interface_id.split(":")[:-1])
402 1
        interface_number = int(interface_id.split(":")[-1])
403 1
        try:
404 1
            switch = self.controller.switches[switch_id]
405 1
        except KeyError:
406 1
            return jsonify("Switch not found"), 404
407
408 1
        try:
409 1
            interface = switch.interfaces[interface_number]
410 1
        except KeyError:
411 1
            return jsonify("Interface not found"), 404
412
413 1
        return jsonify({"metadata": interface.metadata}), 200
414
415 1
    @rest('v3/interfaces/<interface_id>/metadata', methods=['POST'])
416 1
    def add_interface_metadata(self, interface_id):
417
        """Add metadata to an interface."""
418 1
        metadata = self._get_metadata()
419 1
        switch_id = ":".join(interface_id.split(":")[:-1])
420 1
        interface_number = int(interface_id.split(":")[-1])
421 1
        try:
422 1
            switch = self.controller.switches[switch_id]
423 1
        except KeyError:
424 1
            return jsonify("Switch not found"), 404
425
426 1
        try:
427 1
            interface = switch.interfaces[interface_number]
428 1
            self.topo_controller.add_interface_metadata(interface.id, metadata)
429 1
        except KeyError:
430 1
            return jsonify("Interface not found"), 404
431
432 1
        interface.extend_metadata(metadata)
433 1
        self.notify_metadata_changes(interface, 'added')
434 1
        return jsonify("Operation successful"), 201
435
436 1
    @rest('v3/interfaces/<interface_id>/metadata/<key>', methods=['DELETE'])
437 1
    def delete_interface_metadata(self, interface_id, key):
438
        """Delete metadata from an interface."""
439 1
        switch_id = ":".join(interface_id.split(":")[:-1])
440 1
        interface_number = int(interface_id.split(":")[-1])
441
442 1
        try:
443 1
            switch = self.controller.switches[switch_id]
444 1
        except KeyError:
445 1
            return jsonify("Switch not found"), 404
446
447 1
        try:
448 1
            interface = switch.interfaces[interface_number]
449 1
        except KeyError:
450 1
            return jsonify("Interface not found"), 404
451
452 1
        try:
453 1
            _ = interface.metadata[key]
454 1
        except KeyError:
455 1
            return jsonify("Metadata not found"), 404
456
457 1
        self.topo_controller.delete_interface_metadata_key(interface.id, key)
458 1
        interface.remove_metadata(key)
459 1
        self.notify_metadata_changes(interface, 'removed')
460 1
        return jsonify("Operation successful"), 200
461
462
    # Link related methods
463 1
    @rest('v3/links')
464 1
    def get_links(self):
465
        """Return a json with all the links in the topology.
466
467
        Links are connections between interfaces.
468
        """
469
        return jsonify(self._get_links_dict()), 200
470
471 1
    @rest('v3/links/<link_id>/enable', methods=['POST'])
472 1
    def enable_link(self, link_id):
473
        """Administratively enable a link in the topology."""
474 1
        try:
475 1
            with self._links_lock:
476 1
                link = self.links[link_id]
477 1
                self.topo_controller.enable_link(link_id)
478 1
                link.enable()
479 1
        except KeyError:
480 1
            return jsonify("Link not found"), 404
481 1
        self.notify_link_status_change(
482
            self.links[link_id],
483
            reason='link enabled'
484
        )
485 1
        self.notify_topology_update()
486 1
        return jsonify("Operation successful"), 201
487
488 1
    @rest('v3/links/<link_id>/disable', methods=['POST'])
489 1
    def disable_link(self, link_id):
490
        """Administratively disable a link in the topology."""
491 1
        try:
492 1
            with self._links_lock:
493 1
                link = self.links[link_id]
494 1
                self.topo_controller.disable_link(link_id)
495 1
                link.disable()
496 1
        except KeyError:
497 1
            return jsonify("Link not found"), 404
498 1
        self.notify_link_status_change(
499
            self.links[link_id],
500
            reason='link disabled'
501
        )
502 1
        self.notify_topology_update()
503 1
        return jsonify("Operation successful"), 201
504
505 1
    @rest('v3/links/<link_id>/metadata')
506 1
    def get_link_metadata(self, link_id):
507
        """Get metadata from a link."""
508 1
        try:
509 1
            return jsonify({"metadata": self.links[link_id].metadata}), 200
510 1
        except KeyError:
511 1
            return jsonify("Link not found"), 404
512
513 1
    @rest('v3/links/<link_id>/metadata', methods=['POST'])
514 1
    def add_link_metadata(self, link_id):
515
        """Add metadata to a link."""
516 1
        metadata = self._get_metadata()
517 1
        try:
518 1
            link = self.links[link_id]
519 1
        except KeyError:
520 1
            return jsonify("Link not found"), 404
521
522 1
        self.topo_controller.add_link_metadata(link_id, metadata)
523 1
        link.extend_metadata(metadata)
524 1
        self.notify_metadata_changes(link, 'added')
525 1
        return jsonify("Operation successful"), 201
526
527 1
    @rest('v3/links/<link_id>/metadata/<key>', methods=['DELETE'])
528 1
    def delete_link_metadata(self, link_id, key):
529
        """Delete metadata from a link."""
530 1
        try:
531 1
            link = self.links[link_id]
532 1
        except KeyError:
533 1
            return jsonify("Link not found"), 404
534
535 1
        try:
536 1
            _ = link.metadata[key]
537 1
        except KeyError:
538 1
            return jsonify("Metadata not found"), 404
539
540 1
        self.topo_controller.delete_link_metadata_key(link.id, key)
541 1
        link.remove_metadata(key)
542 1
        self.notify_metadata_changes(link, 'removed')
543 1
        return jsonify("Operation successful"), 200
544
545 1
    def notify_current_topology(self) -> None:
546
        """Notify current topology."""
547 1
        name = "kytos/topology.current"
548 1
        event = KytosEvent(name=name, content={"topology":
549
                                               self._get_topology()})
550 1
        self.controller.buffers.app.put(event)
551
552 1
    @listen_to("kytos/topology.get")
553 1
    def on_get_topology(self, _event) -> None:
554
        """Handle kytos/topology.get."""
555
        self.notify_current_topology()
556
557 1
    @listen_to("kytos/.*.liveness.(up|down)")
558 1
    def on_link_liveness_status(self, event) -> None:
559
        """Handle link liveness up|down status event."""
560
        link = Link(event.content["interface_a"], event.content["interface_b"])
561
        try:
562
            link = self.links[link.id]
563
        except KeyError:
564
            log.error(f"Link id {link.id} not found, {link}")
565
            return
566
        liveness_status = event.name.split(".")[-1]
567
        self.handle_link_liveness_status(self.links[link.id], liveness_status)
568
569 1
    def handle_link_liveness_status(self, link, liveness_status) -> None:
570
        """Handle link liveness."""
571 1
        metadata = {"liveness_status": liveness_status}
572 1
        log.info(f"Link liveness {liveness_status}: {link}")
573 1
        self.topo_controller.add_link_metadata(link.id, metadata)
574 1
        link.extend_metadata(metadata)
575 1
        self.notify_topology_update()
576 1
        if link.status == EntityStatus.UP and liveness_status == "up":
577 1
            self.notify_link_status_change(link, reason="liveness_up")
578 1
        if link.status == EntityStatus.DOWN and liveness_status == "down":
579 1
            self.notify_link_status_change(link, reason="liveness_down")
580
581 1
    @listen_to("kytos/.*.liveness.disabled")
582 1
    def on_link_liveness_disabled(self, event) -> None:
583
        """Handle link liveness disabled event."""
584
        interfaces = event.content["interfaces"]
585
        self.handle_link_liveness_disabled(interfaces)
586
587 1
    def get_links_from_interfaces(self, interfaces) -> dict:
588
        """Get links from interfaces."""
589 1
        links_found = {}
590 1
        with self._links_lock:
591 1
            for interface in interfaces:
592 1
                for link in self.links.values():
593 1
                    if any((
594
                        interface.id == link.endpoint_a.id,
595
                        interface.id == link.endpoint_b.id,
596
                    )):
597 1
                        links_found[link.id] = link
598 1
        return links_found
599
600 1
    def handle_link_liveness_disabled(self, interfaces) -> None:
601
        """Handle link liveness disabled."""
602 1
        log.info(f"Link liveness disabled interfaces: {interfaces}")
603
604 1
        key = "liveness_status"
605 1
        links = self.get_links_from_interfaces(interfaces)
606 1
        for link in links.values():
607 1
            link.remove_metadata(key)
608 1
        link_ids = list(links.keys())
609 1
        self.topo_controller.bulk_delete_link_metadata_key(link_ids, key)
610 1
        self.notify_topology_update()
611 1
        for link in links.values():
612 1
            self.notify_link_status_change(link, reason="liveness_disabled")
613
614 1
    @listen_to("kytos/.*.link_available_tags")
615 1
    def on_link_available_tags(self, event):
616
        """Handle on_link_available_tags."""
617
        with self._links_lock:
618
            self.handle_on_link_available_tags(event.content.get("link"))
619
620 1
    def handle_on_link_available_tags(self, link):
621
        """Handle on_link_available_tags."""
622 1
        if link.id not in self.links:
623
            return
624 1
        endpoint_a = self.links[link.id].endpoint_a
625 1
        endpoint_b = self.links[link.id].endpoint_b
626 1
        values_a = [tag.value for tag in endpoint_a.available_tags]
627 1
        values_b = [tag.value for tag in endpoint_b.available_tags]
628 1
        ids_details = [
629
            (endpoint_a.id, {"_id": endpoint_a.id,
630
                             "available_vlans": values_a}),
631
            (endpoint_b.id, {"_id": endpoint_b.id,
632
                             "available_vlans": values_b})
633
        ]
634 1
        self.topo_controller.bulk_upsert_interface_details(ids_details)
635
636 1
    @listen_to('.*.switch.(new|reconnected)')
637 1
    def on_new_switch(self, event):
638
        """Create a new Device on the Topology.
639
640
        Handle the event of a new created switch and update the topology with
641
        this new device. Also notify if the switch is enabled.
642
        """
643
        self.handle_new_switch(event)
644
645 1
    def handle_new_switch(self, event):
646
        """Create a new Device on the Topology."""
647 1
        switch = event.content['switch']
648 1
        switch.activate()
649 1
        self.topo_controller.upsert_switch(switch.id, switch.as_dict())
650 1
        log.debug('Switch %s added to the Topology.', switch.id)
651 1
        self.notify_topology_update()
652 1
        if switch.is_enabled():
653 1
            self.notify_switch_enabled(switch.id)
654
655 1
    @listen_to('.*.connection.lost')
656 1
    def on_connection_lost(self, event):
657
        """Remove a Device from the topology.
658
659
        Remove the disconnected Device and every link that has one of its
660
        interfaces.
661
        """
662
        self.handle_connection_lost(event)
663
664 1
    def handle_connection_lost(self, event):
665
        """Remove a Device from the topology."""
666 1
        switch = event.content['source'].switch
667 1
        if switch:
668 1
            switch.deactivate()
669 1
            self.topo_controller.deactivate_switch(switch.id)
670 1
            log.debug('Switch %s removed from the Topology.', switch.id)
671 1
            self.notify_topology_update()
672
673 1
    def handle_interfaces_created(self, event):
674
        """Update the topology based on the interfaces created."""
675 1
        interfaces = event.content["interfaces"]
676 1
        if not interfaces:
677
            return
678 1
        switch = interfaces[0].switch
679 1
        self.topo_controller.upsert_switch(switch.id, switch.as_dict())
680 1
        name = "kytos/topology.switch.interface.created"
681 1
        for interface in interfaces:
682 1
            event = KytosEvent(name=name, content={'interface': interface})
683 1
            self.controller.buffers.app.put(event)
684
685 1
    def handle_interface_created(self, event):
686
        """Update the topology based on an interface created event.
687
688
        It's handled as a link_up in case a switch send a
689
        created event again and it can be belong to a link.
690
        """
691 1
        interface = event.content['interface']
692 1
        self.handle_interface_link_up(interface)
693
694 1
    @listen_to('.*.topology.switch.interface.created')
695 1
    def on_interface_created(self, event):
696
        """Handle individual interface create event.
697
698
        It's handled as a link_up in case a switch send a
699
        created event it can belong to an existign link.
700
        """
701
        self.handle_interface_created(event)
702
703 1
    @listen_to('.*.switch.interfaces.created')
704 1
    def on_interfaces_created(self, event):
705
        """Update the topology based on a list of created interfaces."""
706
        self.handle_interfaces_created(event)
707
708 1
    def handle_interface_down(self, event):
709
        """Update the topology based on a Port Modify event.
710
711
        The event notifies that an interface was changed to 'down'.
712
        """
713 1
        interface = event.content['interface']
714 1
        interface.deactivate()
715 1
        self.topo_controller.deactivate_interface(interface.id)
716 1
        self.handle_interface_link_down(interface)
717
718 1
    @listen_to('.*.switch.interface.deleted')
719 1
    def on_interface_deleted(self, event):
720
        """Update the topology based on a Port Delete event."""
721
        self.handle_interface_deleted(event)
722
723 1
    def handle_interface_deleted(self, event):
724
        """Update the topology based on a Port Delete event."""
725 1
        self.handle_interface_down(event)
726
727 1
    @listen_to('.*.switch.interface.link_up')
728 1
    def on_interface_link_up(self, event):
729
        """Update the topology based on a Port Modify event.
730
731
        The event notifies that an interface's link was changed to 'up'.
732
        """
733
        interface = event.content['interface']
734
        self.handle_interface_link_up(interface)
735
736 1
    def handle_interface_link_up(self, interface):
737
        """Update the topology based on a Port Modify event."""
738 1
        self.handle_link_up(interface)
739
740 1
    @listen_to('kytos/maintenance.end_switch')
741 1
    def on_switch_maintenance_end(self, event):
742
        """Handle the end of the maintenance of a switch."""
743
        self.handle_switch_maintenance_end(event)
744
745 1
    def handle_switch_maintenance_end(self, event):
746
        """Handle the end of the maintenance of a switch."""
747 1
        switches = event.content['switches']
748 1
        for switch in switches:
749 1
            switch.enable()
750 1
            switch.activate()
751 1
            for interface in switch.interfaces.values():
752 1
                interface.enable()
753 1
                self.handle_link_up(interface)
754
755 1
    def link_status_hook_link_up_timer(self, link) -> Optional[EntityStatus]:
756
        """Link status hook link up timer."""
757 1
        tnow = time.time()
758 1
        if (
759
            link.is_active()
760
            and link.is_enabled()
761
            and "last_status_change" in link.metadata
762
            and tnow - link.metadata['last_status_change'] < self.link_up_timer
763
        ):
764 1
            return EntityStatus.DOWN
765 1
        return None
766
767 1
    def notify_link_up_if_status(self, link) -> None:
768
        """Tries to notify link up and topology changes based on its status
769
770
        Currently, it needs to wait up to a timer."""
771 1
        time.sleep(self.link_up_timer)
772 1
        if link.status != EntityStatus.UP:
773
            return
774 1
        with self._links_notify_lock[link.id]:
775 1
            notified_at = link.get_metadata("notified_up_at")
776 1
            if (
777
                notified_at
778
                and (now() - notified_at.replace(tzinfo=timezone.utc)).seconds
779
                < self.link_up_timer
780
            ):
781 1
                return
782 1
            key, notified_at = "notified_up_at", now()
783 1
            link.update_metadata(key, now())
784 1
            self.topo_controller.add_link_metadata(link.id, {key: notified_at})
785 1
            self.notify_topology_update()
786 1
            self.notify_link_status_change(link, reason="link up")
787
788 1
    def handle_link_up(self, interface):
789
        """Handle link up for an interface."""
790 1
        interface.activate()
791 1
        self.topo_controller.activate_interface(interface.id)
792 1
        self.notify_topology_update()
793 1
        link = self._get_link_from_interface(interface)
794 1
        if not link:
795
            return
796 1
        if link.endpoint_a == interface:
797 1
            other_interface = link.endpoint_b
798
        else:
799 1
            other_interface = link.endpoint_a
800 1
        if other_interface.is_active() is False:
801 1
            return
802 1
        metadata = {
803
            'last_status_change': time.time(),
804
            'last_status_is_active': True
805
        }
806 1
        link.extend_metadata(metadata)
807 1
        link.activate()
808 1
        self.topo_controller.activate_link(link.id, **metadata)
809 1
        self.notify_link_up_if_status(link)
810
811 1
    @listen_to('.*.switch.interface.link_down')
812 1
    def on_interface_link_down(self, event):
813
        """Update the topology based on a Port Modify event.
814
815
        The event notifies that an interface's link was changed to 'down'.
816
        """
817
        interface = event.content['interface']
818
        self.handle_interface_link_down(interface)
819
820 1
    def handle_interface_link_down(self, interface):
821
        """Update the topology based on an interface."""
822 1
        self.handle_link_down(interface)
823
824 1
    @listen_to('kytos/maintenance.start_switch')
825 1
    def on_switch_maintenance_start(self, event):
826
        """Handle the start of the maintenance of a switch."""
827
        self.handle_switch_maintenance_start(event)
828
829 1
    def handle_switch_maintenance_start(self, event):
830
        """Handle the start of the maintenance of a switch."""
831 1
        switches = event.content['switches']
832 1
        for switch in switches:
833 1
            switch.disable()
834 1
            switch.deactivate()
835 1
            for interface in switch.interfaces.values():
836 1
                interface.disable()
837 1
                if interface.is_active():
838 1
                    self.handle_link_down(interface)
839
840 1
    def handle_link_down(self, interface):
841
        """Notify a link is down."""
842 1
        link = self._get_link_from_interface(interface)
843 1
        if link and link.is_active():
844 1
            link.deactivate()
845 1
            last_status_change = time.time()
846 1
            last_status_is_active = False
847 1
            metadata = {
848
                "last_status_change": last_status_change,
849
                "last_status_is_active": last_status_is_active,
850
            }
851 1
            link.extend_metadata(metadata)
852 1
            self.topo_controller.deactivate_link(link.id, last_status_change,
853
                                                 last_status_is_active)
854 1
            self.notify_link_status_change(link, reason="link down")
855 1
        if link and not link.is_active():
856 1
            with self._links_lock:
857 1
                last_status = link.get_metadata('last_status_is_active')
858 1
                last_status_change = link.get_metadata('last_status_change')
859 1
                metadata = {
860
                    "last_status_change": last_status_change,
861
                    "last_status_is_active": last_status,
862
                }
863 1
                if last_status:
864
                    link.extend_metadata(metadata)
865
                    self.topo_controller.deactivate_link(link.id,
866
                                                         last_status_change,
867
                                                         last_status)
868
                    self.notify_link_status_change(link, reason='link down')
869 1
        interface.deactivate()
870 1
        self.topo_controller.deactivate_interface(interface.id)
871 1
        self.notify_topology_update()
872
873 1
    @listen_to('.*.interface.is.nni')
874 1
    def on_add_links(self, event):
875
        """Update the topology with links related to the NNI interfaces."""
876
        self.add_links(event)
877
878 1
    def add_links(self, event):
879
        """Update the topology with links related to the NNI interfaces."""
880 1
        interface_a = event.content['interface_a']
881 1
        interface_b = event.content['interface_b']
882
883 1
        try:
884 1
            with self._links_lock:
885 1
                link, created = self._get_link_or_create(interface_a,
886
                                                         interface_b)
887 1
                interface_a.update_link(link)
888 1
                interface_b.update_link(link)
889
890 1
                link.endpoint_a = interface_a
891 1
                link.endpoint_b = interface_b
892
893 1
                interface_a.nni = True
894 1
                interface_b.nni = True
895
896
        except KytosLinkCreationError as err:
897
            log.error(f'Error creating link: {err}.')
898
            return
899
900 1
        if not created:
901
            return
902
903 1
        self.notify_topology_update()
904 1
        if not link.is_active():
905
            return
906
907 1
        metadata = {
908
            'last_status_change': time.time(),
909
            'last_status_is_active': True
910
        }
911 1
        link.extend_metadata(metadata)
912 1
        self.topo_controller.upsert_link(link.id, link.as_dict())
913 1
        self.notify_link_up_if_status(link)
914
915 1
    @listen_to('.*.of_lldp.network_status.updated')
916 1
    def on_lldp_status_updated(self, event):
917
        """Handle of_lldp.network_status.updated from of_lldp."""
918
        self.handle_lldp_status_updated(event)
919
920 1
    @listen_to(".*.topo_controller.upsert_switch")
921 1
    def on_topo_controller_upsert_switch(self, event) -> None:
922
        """Listen to topo_controller_upsert_switch."""
923
        self.handle_topo_controller_upsert_switch(event.content["switch"])
924
925 1
    def handle_topo_controller_upsert_switch(self, switch) -> Optional[dict]:
926
        """Handle topo_controller_upsert_switch."""
927 1
        return self.topo_controller.upsert_switch(switch.id, switch.as_dict())
928
929 1
    def handle_lldp_status_updated(self, event) -> None:
930
        """Handle .*.network_status.updated events from of_lldp."""
931 1
        content = event.content
932 1
        interface_ids = content["interface_ids"]
933 1
        switches = set()
934 1
        for interface_id in interface_ids:
935 1
            dpid = ":".join(interface_id.split(":")[:-1])
936 1
            switch = self.controller.get_switch_by_dpid(dpid)
937 1
            if switch:
938 1
                switches.add(switch)
939
940 1
        name = "kytos/topology.topo_controller.upsert_switch"
941 1
        for switch in switches:
942 1
            event = KytosEvent(name=name, content={"switch": switch})
943 1
            self.controller.buffers.app.put(event)
944
945 1
    def notify_switch_enabled(self, dpid):
946
        """Send an event to notify that a switch is enabled."""
947 1
        name = 'kytos/topology.switch.enabled'
948 1
        event = KytosEvent(name=name, content={'dpid': dpid})
949 1
        self.controller.buffers.app.put(event)
950
951 1
    def notify_switch_disabled(self, dpid):
952
        """Send an event to notify that a switch is disabled."""
953 1
        name = 'kytos/topology.switch.disabled'
954 1
        event = KytosEvent(name=name, content={'dpid': dpid})
955 1
        self.controller.buffers.app.put(event)
956
957 1
    def notify_topology_update(self):
958
        """Send an event to notify about updates on the topology."""
959 1
        name = 'kytos/topology.updated'
960 1
        event = KytosEvent(name=name, content={'topology':
961
                                               self._get_topology()})
962 1
        self.controller.buffers.app.put(event)
963
964 1
    def notify_link_status_change(self, link, reason='not given'):
965
        """Send an event to notify about a status change on a link."""
966 1
        name = 'kytos/topology.'
967 1
        if link.status == EntityStatus.UP:
968
            status = 'link_up'
969
        else:
970 1
            status = 'link_down'
971 1
        event = KytosEvent(
972
            name=name+status,
973
            content={
974
                'link': link,
975
                'reason': reason
976
            })
977 1
        self.controller.buffers.app.put(event)
978
979 1
    def notify_metadata_changes(self, obj, action):
980
        """Send an event to notify about metadata changes."""
981 1
        if isinstance(obj, Switch):
982 1
            entity = 'switch'
983 1
            entities = 'switches'
984 1
        elif isinstance(obj, Interface):
985 1
            entity = 'interface'
986 1
            entities = 'interfaces'
987 1
        elif isinstance(obj, Link):
988 1
            entity = 'link'
989 1
            entities = 'links'
990
        else:
991 1
            raise ValueError(
992
                'Invalid object, supported: Switch, Interface, Link'
993
            )
994
995 1
        name = f'kytos/topology.{entities}.metadata.{action}'
996 1
        content = {entity: obj, 'metadata': obj.metadata.copy()}
997 1
        event = KytosEvent(name=name, content=content)
998 1
        self.controller.buffers.app.put(event)
999 1
        log.debug(f'Metadata from {obj.id} was {action}.')
1000
1001 1
    @listen_to('.*.switch.port.created')
1002 1
    def on_notify_port_created(self, event):
1003
        """Notify when a port is created."""
1004
        self.notify_port_created(event)
1005
1006 1
    def notify_port_created(self, event):
1007
        """Notify when a port is created."""
1008 1
        name = 'kytos/topology.port.created'
1009 1
        event = KytosEvent(name=name, content=event.content)
1010 1
        self.controller.buffers.app.put(event)
1011
1012 1
    @staticmethod
1013 1
    def load_interfaces_available_tags(switch: Switch,
1014
                                       interfaces_details: List[dict]) -> None:
1015
        """Load interfaces available tags (vlans)."""
1016 1
        if not interfaces_details:
1017
            return
1018 1
        for interface_details in interfaces_details:
1019 1
            available_vlans = interface_details["available_vlans"]
1020 1
            if not available_vlans:
1021
                continue
1022 1
            log.debug(f"Interface id {interface_details['id']} loading "
1023
                      f"{len(interface_details['available_vlans'])} "
1024
                      "available tags")
1025 1
            port_number = int(interface_details["id"].split(":")[-1])
1026 1
            interface = switch.interfaces[port_number]
1027 1
            interface.set_available_tags(interface_details['available_vlans'])
1028
1029 1
    @listen_to('kytos/maintenance.start_link')
1030 1
    def on_link_maintenance_start(self, event):
1031
        """Deals with the start of links maintenance."""
1032
        with self._links_lock:
1033
            self.handle_link_maintenance_start(event)
1034
1035 1
    def handle_link_maintenance_start(self, event):
1036
        """Deals with the start of links maintenance."""
1037 1
        notify_links = []
1038 1
        maintenance_links = event.content['links']
1039 1
        for maintenance_link in maintenance_links:
1040 1
            try:
1041 1
                link = self.links[maintenance_link.id]
1042 1
            except KeyError:
1043 1
                continue
1044 1
            notify_links.append(link)
1045 1
        for link in notify_links:
1046 1
            link.disable()
1047 1
            link.deactivate()
1048 1
            link.endpoint_a.deactivate()
1049 1
            link.endpoint_b.deactivate()
1050 1
            link.endpoint_a.disable()
1051 1
            link.endpoint_b.disable()
1052 1
            self.notify_link_status_change(link, reason='maintenance')
1053
1054 1
    @listen_to('kytos/maintenance.end_link')
1055 1
    def on_link_maintenance_end(self, event):
1056
        """Deals with the end of links maintenance."""
1057
        with self._links_lock:
1058
            self.handle_link_maintenance_end(event)
1059
1060 1
    def handle_link_maintenance_end(self, event):
1061
        """Deals with the end of links maintenance."""
1062 1
        notify_links = []
1063 1
        maintenance_links = event.content['links']
1064 1
        for maintenance_link in maintenance_links:
1065 1
            try:
1066 1
                link = self.links[maintenance_link.id]
1067 1
            except KeyError:
1068 1
                continue
1069 1
            notify_links.append(link)
1070 1
        for link in notify_links:
1071 1
            link.enable()
1072 1
            link.activate()
1073 1
            link.endpoint_a.activate()
1074 1
            link.endpoint_b.activate()
1075 1
            link.endpoint_a.enable()
1076 1
            link.endpoint_b.enable()
1077
            self.notify_link_status_change(link, reason='maintenance')
1078