Passed
Push — master ( ace346...f3e720 )
by
unknown
03:25 queued 01:20
created
1
"""Main module of kytos/topology Kytos Network Application.
2
3
Manage the network topology
4
"""
5
# pylint: disable=wrong-import-order
6 1
import pathlib
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
import httpx
14 1
import tenacity
15 1
from tenacity import (retry_if_exception_type, stop_after_attempt,
16
                      wait_combine, wait_fixed, wait_random)
17
18 1
from kytos.core import KytosEvent, KytosNApp, log, rest
19 1
from kytos.core.common import EntityStatus
20 1
from kytos.core.exceptions import (KytosInvalidTagRanges,
21
                                   KytosLinkCreationError, KytosTagError)
22 1
from kytos.core.helpers import listen_to, load_spec, now, validate_openapi
23 1
from kytos.core.interface import Interface
24 1
from kytos.core.link import Link
25 1
from kytos.core.rest_api import (HTTPException, JSONResponse, Request,
26
                                 content_type_json_or_415, get_json_or_400)
27 1
from kytos.core.retry import before_sleep
28 1
from kytos.core.switch import Switch
29 1
from kytos.core.tag_ranges import get_tag_ranges
30 1
from napps.kytos.topology import settings
31
32 1
from .controllers import TopoController
33 1
from .exceptions import RestoreError
34 1
from .models import Topology
35
36 1
DEFAULT_LINK_UP_TIMER = 10
37
38
39 1
class Main(KytosNApp):  # pylint: disable=too-many-public-methods
40
    """Main class of kytos/topology NApp.
41
42
    This class is the entry point for this napp.
43
    """
44
45 1
    spec = load_spec(pathlib.Path(__file__).parent / "openapi.yml")
46
47 1
    def setup(self):
48
        """Initialize the NApp's links list."""
49 1
        self.links: dict[str, Link] = {}
50 1
        self.intf_available_tags = {}
51 1
        self.link_up_timer = getattr(settings, 'LINK_UP_TIMER',
52
                                     DEFAULT_LINK_UP_TIMER)
53
54 1
        self._links_lock = Lock()
55
        # to keep track of potential unorded scheduled interface events
56 1
        self._intfs_lock = defaultdict(Lock)
57 1
        self._intfs_updated_at = {}
58 1
        self._intfs_tags_updated_at = {}
59 1
        self.link_up = set()
60 1
        self.link_status_lock = Lock()
61 1
        self._switch_lock = defaultdict(Lock)
62 1
        self.topo_controller = self.get_topo_controller()
63 1
        Link.register_status_func(f"{self.napp_id}_link_up_timer",
64
                                  self.link_status_hook_link_up_timer)
65 1
        self.topo_controller.bootstrap_indexes()
66 1
        self.load_topology()
67
68 1
    @staticmethod
69 1
    def get_topo_controller() -> TopoController:
70
        """Get TopoController."""
71
        return TopoController()
72
73 1
    def execute(self):
74
        """Execute once when the napp is running."""
75
        pass
76
77 1
    def shutdown(self):
78
        """Do nothing."""
79
        log.info('NApp kytos/topology shutting down.')
80
81 1
    def _get_metadata(self, request: Request) -> dict:
82
        """Return a JSON with metadata."""
83 1
        content_type_json_or_415(request)
84 1
        metadata = get_json_or_400(request, self.controller.loop)
85 1
        if not isinstance(metadata, dict):
86 1
            raise HTTPException(400, "Invalid metadata value: {metadata}")
87 1
        return metadata
88
89 1
    def _get_link_or_create(self, endpoint_a, endpoint_b):
90
        """Get an existing link or create a new one.
91
92
        Returns:
93
            Tuple(Link, bool): Link and a boolean whether it has been created.
94
        """
95 1
        new_link = Link(endpoint_a, endpoint_b)
96
97 1
        if new_link.id in self.links:
98 1
            return (self.links[new_link.id], False)
99
100 1
        self.links[new_link.id] = new_link
101 1
        return (new_link, True)
102
103 1
    def _get_switches_dict(self):
104
        """Return a dictionary with the known switches."""
105 1
        switches = {'switches': {}}
106 1
        for idx, switch in enumerate(self.controller.switches.copy().values()):
107 1
            switch_data = switch.as_dict()
108 1
            if not all(key in switch_data['metadata']
109
                       for key in ('lat', 'lng')):
110
                # Switches are initialized somewhere in the ocean
111
                switch_data['metadata']['lat'] = str(0.0)
112
                switch_data['metadata']['lng'] = str(-30.0+idx*10.0)
113 1
            switches['switches'][switch.id] = switch_data
114 1
        return switches
115
116 1
    def _get_links_dict(self):
117
        """Return a dictionary with the known links."""
118 1
        return {'links': {link.id: link.as_dict() for link in
119
                          self.links.copy().values()}}
120
121 1
    def _get_topology_dict(self):
122
        """Return a dictionary with the known topology."""
123 1
        return {'topology': {**self._get_switches_dict(),
124
                             **self._get_links_dict()}}
125
126 1
    def _get_topology(self):
127
        """Return an object representing the topology."""
128 1
        return Topology(self.controller.switches.copy(), self.links.copy())
129
130 1
    def _get_link_from_interface(self, interface: Interface):
131
        """Return the link of the interface, or None if it does not exist."""
132 1
        for link in list(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
        # These ones are just runtime active southbound protocol data
160
        # It won't be stored in the future, only kept in the runtime.
161
        # Also network operators can follow logs to track this state changes
162 1
        for key in (
163
            "last_status_is_active", "last_status_change", "notified_up_at"
164
        ):
165 1
            link_att["metadata"].pop(key, None)
166
167 1
        link.extend_metadata(link_att["metadata"])
168 1
        interface_a.update_link(link)
169 1
        interface_b.update_link(link)
170 1
        interface_a.nni = True
171 1
        interface_b.nni = True
172
173 1
    def _load_switch(self, switch_id, switch_att):
174 1
        log.info(f'Loading switch dpid: {switch_id}')
175 1
        switch = self.controller.get_switch_or_create(switch_id)
176 1
        if switch_att['enabled']:
177 1
            switch.enable()
178
        else:
179 1
            switch.disable()
180 1
        switch.description['manufacturer'] = switch_att.get('manufacturer', '')
181 1
        switch.description['hardware'] = switch_att.get('hardware', '')
182 1
        switch.description['software'] = switch_att.get('software')
183 1
        switch.description['serial'] = switch_att.get('serial', '')
184 1
        switch.description['data_path'] = switch_att.get('data_path', '')
185 1
        switch.extend_metadata(switch_att["metadata"])
186
187 1
        for iface_id, iface_att in switch_att.get('interfaces', {}).items():
188 1
            log.info(f'Loading interface iface_id={iface_id}')
189 1
            interface = switch.update_or_create_interface(
190
                            port_no=iface_att['port_number'],
191
                            name=iface_att['name'],
192
                            address=iface_att.get('mac', None),
193
                            speed=iface_att.get('speed', None))
194 1
            if iface_att['enabled']:
195 1
                interface.enable()
196
            else:
197 1
                interface.disable()
198 1
            interface.lldp = iface_att['lldp']
199 1
            interface.extend_metadata(iface_att["metadata"])
200 1
            interface.deactivate()
201 1
            name = 'kytos/topology.port.created'
202 1
            event = KytosEvent(name=name, content={
203
                                              'switch': switch_id,
204
                                              'port': interface.port_number,
205
                                              'port_description': {
206
                                                  'alias': interface.name,
207
                                                  'mac': interface.address,
208
                                                  'state': interface.state
209
                                                  }
210
                                              })
211 1
            self.controller.buffers.app.put(event, timeout=1)
212
213 1
        intf_ids = [v["id"] for v in switch_att.get("interfaces", {}).values()]
214 1
        intf_details = self.topo_controller.get_interfaces_details(intf_ids)
215 1
        with self._links_lock:
216 1
            self.load_interfaces_tags_values(switch, intf_details)
217
218
    # pylint: disable=attribute-defined-outside-init
219 1
    def load_topology(self):
220
        """Load network topology from DB."""
221 1
        topology = self.topo_controller.get_topology()
222 1
        switches = topology["topology"]["switches"]
223 1
        links = topology["topology"]["links"]
224
225 1
        failed_switches = {}
226 1
        log.debug(f"_load_network_status switches={switches}")
227 1
        for switch_id, switch_att in switches.items():
228 1
            try:
229 1
                self._load_switch(switch_id, switch_att)
230 1
            except (KeyError, AttributeError, TypeError) as err:
231 1
                failed_switches[switch_id] = err
232 1
                log.error(f'Error loading switch: {err}')
233
234 1
        failed_links = {}
235 1
        log.debug(f"_load_network_status links={links}")
236 1
        for link_id, link_att in links.items():
237 1
            try:
238 1
                self._load_link(link_att)
239 1
            except (KeyError, AttributeError, TypeError) as err:
240 1
                failed_links[link_id] = err
241 1
                log.error(f'Error loading link {link_id}: {err}')
242
243 1
        name = 'kytos/topology.topology_loaded'
244 1
        event = KytosEvent(
245
            name=name,
246
            content={
247
                'topology': self._get_topology(),
248
                'failed_switches': failed_switches,
249
                'failed_links': failed_links
250
            })
251 1
        self.controller.buffers.app.put(event, timeout=1)
252
253 1
    @rest('v3/')
254 1
    def get_topology(self, _request: Request) -> JSONResponse:
255
        """Return the latest known topology.
256
257
        This topology is updated when there are network events.
258
        """
259 1
        return JSONResponse(self._get_topology_dict())
260
261
    # Switch related methods
262 1
    @rest('v3/switches')
263 1
    def get_switches(self, _request: Request) -> JSONResponse:
264
        """Return a json with all the switches in the topology."""
265
        return JSONResponse(self._get_switches_dict())
266
267 1
    @rest('v3/switches/{dpid}/enable', methods=['POST'])
268 1
    def enable_switch(self, request: Request) -> JSONResponse:
269
        """Administratively enable a switch in the topology."""
270 1
        dpid = request.path_params["dpid"]
271 1
        try:
272 1
            switch = self.controller.switches[dpid]
273 1
            self.topo_controller.enable_switch(dpid)
274 1
            switch.enable()
275 1
        except KeyError:
276 1
            raise HTTPException(404, detail="Switch not found")
277
278 1
        self.notify_topology_update()
279 1
        self.notify_switch_enabled(dpid)
280 1
        self.notify_switch_links_status(switch, "link enabled")
281 1
        return JSONResponse("Operation successful", status_code=201)
282
283 1
    @rest('v3/switches/{dpid}/disable', methods=['POST'])
284 1
    def disable_switch(self, request: Request) -> JSONResponse:
285
        """Administratively disable a switch in the topology."""
286 1
        dpid = request.path_params["dpid"]
287 1
        try:
288 1
            switch = self.controller.switches[dpid]
289 1
            link_ids = set()
290 1
            for _, interface in switch.interfaces.copy().items():
291 1
                if (interface.link and interface.link.is_enabled()):
292 1
                    link_ids.add(interface.link.id)
293 1
                    interface.link.disable()
294 1
                    self.notify_link_enabled_state(interface.link, "disabled")
295 1
            self.topo_controller.bulk_disable_links(link_ids)
296 1
            self.topo_controller.disable_switch(dpid)
297 1
            switch.disable()
298 1
        except KeyError:
299 1
            raise HTTPException(404, detail="Switch not found")
300
301 1
        self.notify_topology_update()
302 1
        self.notify_switch_disabled(dpid)
303 1
        self.notify_switch_links_status(switch, "link disabled")
304 1
        return JSONResponse("Operation successful", status_code=201)
305
306 1
    @rest('v3/switches/{dpid}', methods=['DELETE'])
307 1
    def delete_switch(self, request: Request) -> JSONResponse:
308
        """Delete a switch.
309
310
        Requirements:
311
            - There should not be installed flows related to switch.
312
            - The switch should be disabled.
313
            - All tags from switch interfaces should be available.
314
            - The switch should not have links.
315
        """
316 1
        dpid = request.path_params["dpid"]
317 1
        try:
318 1
            switch: Switch = self.controller.switches[dpid]
319 1
            with self._switch_lock[dpid]:
320 1
                if switch.status != EntityStatus.DISABLED:
321 1
                    raise HTTPException(
322
                        409, detail="Switch should be disabled."
323
                    )
324 1
                for intf_id, interface in switch.interfaces.copy().items():
325 1
                    if not interface.all_tags_available():
326 1
                        detail = f"Interface {intf_id} vlans are being used."\
327
                                 " Delete any service using vlans."
328 1
                        raise HTTPException(409, detail=detail)
329 1
                with self._links_lock:
330 1
                    for link_id, link in self.links.items():
331 1
                        if (dpid in
332
                                (link.endpoint_a.switch.dpid,
333
                                 link.endpoint_b.switch.dpid)):
334 1
                            raise HTTPException(
335
                                409, detail=f"Switch should not have links. "
336
                                            f"Link found {link_id}."
337
                            )
338 1
                try:
339 1
                    flows = self.get_flows_by_switch(dpid)
340
                except tenacity.RetryError as err:
341
                    detail = "Error while getting flows: "\
342
                             f"{err.last_attempt.exception()}."
343
                    raise HTTPException(409, detail=detail)
344 1
                if flows:
345
                    raise HTTPException(409, detail="Switch has flows. Verify"
346
                                                    " if a switch is used.")
347 1
                switch = self.controller.switches.pop(dpid)
348 1
                self.topo_controller.delete_switch_data(dpid)
349 1
        except KeyError:
350 1
            raise HTTPException(404, detail="Switch not found.")
351 1
        name = 'kytos/topology.switch.deleted'
352 1
        event = KytosEvent(name=name, content={'switch': switch})
353 1
        self.controller.buffers.app.put(event)
354 1
        self.notify_topology_update()
355 1
        return JSONResponse("Operation successful")
356
357 1
    @rest('v3/switches/{dpid}/metadata')
358 1
    def get_switch_metadata(self, request: Request) -> JSONResponse:
359
        """Get metadata from a switch."""
360 1
        dpid = request.path_params["dpid"]
361 1
        try:
362 1
            metadata = self.controller.switches[dpid].metadata
363 1
            return JSONResponse({"metadata": metadata})
364 1
        except KeyError:
365 1
            raise HTTPException(404, detail="Switch not found")
366
367 1
    @rest('v3/switches/{dpid}/metadata', methods=['POST'])
368 1
    def add_switch_metadata(self, request: Request) -> JSONResponse:
369
        """Add metadata to a switch."""
370 1
        dpid = request.path_params["dpid"]
371 1
        metadata = self._get_metadata(request)
372 1
        try:
373 1
            switch = self.controller.switches[dpid]
374 1
        except KeyError:
375 1
            raise HTTPException(404, detail="Switch not found")
376
377 1
        self.topo_controller.add_switch_metadata(dpid, metadata)
378 1
        switch.extend_metadata(metadata)
379 1
        self.notify_metadata_changes(switch, 'added')
380 1
        return JSONResponse("Operation successful", status_code=201)
381
382 1
    @rest('v3/switches/{dpid}/metadata/{key}', methods=['DELETE'])
383 1
    def delete_switch_metadata(self, request: Request) -> JSONResponse:
384
        """Delete metadata from a switch."""
385 1
        dpid = request.path_params["dpid"]
386 1
        key = request.path_params["key"]
387 1
        try:
388 1
            switch = self.controller.switches[dpid]
389 1
        except KeyError:
390 1
            raise HTTPException(404, detail="Switch not found")
391
392 1
        try:
393 1
            _ = switch.metadata[key]
394 1
        except KeyError:
395 1
            raise HTTPException(404, "Metadata not found")
396
397 1
        self.topo_controller.delete_switch_metadata_key(dpid, key)
398 1
        switch.remove_metadata(key)
399 1
        self.notify_metadata_changes(switch, 'removed')
400 1
        return JSONResponse("Operation successful")
401
402
    # Interface related methods
403 1
    @rest('v3/interfaces')
404 1
    def get_interfaces(self, _request: Request) -> JSONResponse:
405
        """Return a json with all the interfaces in the topology."""
406 1
        interfaces = {}
407 1
        switches = self._get_switches_dict()
408 1
        for switch in switches['switches'].values():
409 1
            for interface_id, interface in switch['interfaces'].items():
410 1
                interfaces[interface_id] = interface
411
412 1
        return JSONResponse({'interfaces': interfaces})
413
414 1
    @rest('v3/interfaces/switch/{dpid}/enable', methods=['POST'])
415 1
    @rest('v3/interfaces/{interface_enable_id}/enable', methods=['POST'])
416 1
    def enable_interface(self, request: Request) -> JSONResponse:
417
        """Administratively enable interfaces in the topology."""
418 1
        interface_enable_id = request.path_params.get("interface_enable_id")
419 1
        dpid = request.path_params.get("dpid")
420 1
        if dpid is None:
421 1
            dpid = ":".join(interface_enable_id.split(":")[:-1])
422 1
        try:
423 1
            switch = self.controller.switches[dpid]
424 1
            if not switch.is_enabled():
425 1
                raise HTTPException(409, detail="Enable Switch first")
426 1
        except KeyError:
427 1
            raise HTTPException(404, detail="Switch not found")
428
429 1
        if interface_enable_id:
430 1
            interface_number = int(interface_enable_id.split(":")[-1])
431
432 1
            try:
433 1
                interface = switch.interfaces[interface_number]
434 1
                self.topo_controller.enable_interface(interface.id)
435 1
                interface.enable()
436 1
                self.notify_interface_link_status(interface, "link enabled")
437 1
            except KeyError:
438 1
                msg = f"Switch {dpid} interface {interface_number} not found"
439 1
                raise HTTPException(404, detail=msg)
440
        else:
441 1
            for interface in switch.interfaces.copy().values():
442 1
                interface.enable()
443 1
                self.notify_interface_link_status(interface, "link enabled")
444 1
            self.topo_controller.upsert_switch(switch.id, switch.as_dict())
445 1
        self.notify_topology_update()
446 1
        return JSONResponse("Operation successful")
447
448 1
    @rest('v3/interfaces/switch/{dpid}/disable', methods=['POST'])
449 1
    @rest('v3/interfaces/{interface_disable_id}/disable', methods=['POST'])
450 1
    def disable_interface(self, request: Request) -> JSONResponse:
451
        """Administratively disable interfaces in the topology."""
452 1
        interface_disable_id = request.path_params.get("interface_disable_id")
453 1
        dpid = request.path_params.get("dpid")
454 1
        if dpid is None:
455 1
            dpid = ":".join(interface_disable_id.split(":")[:-1])
456 1
        try:
457 1
            switch = self.controller.switches[dpid]
458 1
        except KeyError:
459 1
            raise HTTPException(404, detail="Switch not found")
460
461 1
        if interface_disable_id:
462 1
            interface_number = int(interface_disable_id.split(":")[-1])
463
464 1
            try:
465 1
                interface = switch.interfaces[interface_number]
466 1
                self.topo_controller.disable_interface(interface.id)
467 1
                if interface.link and interface.link.is_enabled():
468 1
                    self.topo_controller.disable_link(interface.link.id)
469 1
                    interface.link.disable()
470 1
                    self.notify_link_enabled_state(interface.link, "disabled")
471 1
                interface.disable()
472 1
                self.notify_interface_link_status(interface, "link disabled")
473 1
            except KeyError:
474 1
                msg = f"Switch {dpid} interface {interface_number} not found"
475 1
                raise HTTPException(404, detail=msg)
476
        else:
477 1
            link_ids = set()
478 1
            for interface in switch.interfaces.copy().values():
479 1
                if interface.link and interface.link.is_enabled():
480 1
                    link_ids.add(interface.link.id)
481 1
                    interface.link.disable()
482 1
                    self.notify_link_enabled_state(interface.link, "disabled")
483 1
                interface.disable()
484 1
                self.notify_interface_link_status(interface, "link disabled")
485 1
            self.topo_controller.bulk_disable_links(link_ids)
486 1
            self.topo_controller.upsert_switch(switch.id, switch.as_dict())
487 1
        self.notify_topology_update()
488 1
        return JSONResponse("Operation successful")
489
490 1
    @rest('v3/interfaces/{interface_id}/metadata')
491 1
    def get_interface_metadata(self, request: Request) -> JSONResponse:
492
        """Get metadata from an interface."""
493 1
        interface_id = request.path_params["interface_id"]
494 1
        switch_id = ":".join(interface_id.split(":")[:-1])
495 1
        interface_number = int(interface_id.split(":")[-1])
496 1
        try:
497 1
            switch = self.controller.switches[switch_id]
498 1
        except KeyError:
499 1
            raise HTTPException(404, detail="Switch not found")
500
501 1
        try:
502 1
            interface = switch.interfaces[interface_number]
503 1
        except KeyError:
504 1
            raise HTTPException(404, detail="Interface not found")
505
506 1
        return JSONResponse({"metadata": interface.metadata})
507
508 1
    @rest('v3/interfaces/{interface_id}/metadata', methods=['POST'])
509 1
    def add_interface_metadata(self, request: Request) -> JSONResponse:
510
        """Add metadata to an interface."""
511 1
        interface_id = request.path_params["interface_id"]
512 1
        metadata = self._get_metadata(request)
513 1
        switch_id = ":".join(interface_id.split(":")[:-1])
514 1
        interface_number = int(interface_id.split(":")[-1])
515 1
        try:
516 1
            switch = self.controller.switches[switch_id]
517 1
        except KeyError:
518 1
            raise HTTPException(404, detail="Switch not found")
519
520 1
        try:
521 1
            interface = switch.interfaces[interface_number]
522 1
            self.topo_controller.add_interface_metadata(interface.id, metadata)
523 1
        except KeyError:
524 1
            raise HTTPException(404, detail="Interface not found")
525
526 1
        interface.extend_metadata(metadata)
527 1
        self.notify_metadata_changes(interface, 'added')
528 1
        return JSONResponse("Operation successful", status_code=201)
529
530 1
    @rest('v3/interfaces/{interface_id}/metadata/{key}', methods=['DELETE'])
531 1
    def delete_interface_metadata(self, request: Request) -> JSONResponse:
532
        """Delete metadata from an interface."""
533 1
        interface_id = request.path_params["interface_id"]
534 1
        key = request.path_params["key"]
535 1
        switch_id = ":".join(interface_id.split(":")[:-1])
536 1
        try:
537 1
            interface_number = int(interface_id.split(":")[-1])
538
        except ValueError:
539
            detail = f"Invalid interface_id {interface_id}"
540
            raise HTTPException(400, detail=detail)
541
542 1
        try:
543 1
            switch = self.controller.switches[switch_id]
544 1
        except KeyError:
545 1
            raise HTTPException(404, detail="Switch not found")
546
547 1
        try:
548 1
            interface = switch.interfaces[interface_number]
549 1
        except KeyError:
550 1
            raise HTTPException(404, detail="Interface not found")
551
552 1
        try:
553 1
            _ = interface.metadata[key]
554 1
        except KeyError:
555 1
            raise HTTPException(404, detail="Metadata not found")
556
557 1
        self.topo_controller.delete_interface_metadata_key(interface.id, key)
558 1
        interface.remove_metadata(key)
559 1
        self.notify_metadata_changes(interface, 'removed')
560 1
        return JSONResponse("Operation successful")
561
562 1
    @rest('v3/interfaces/{interface_id}/tag_ranges', methods=['POST'])
563 1
    @validate_openapi(spec)
564 1
    def set_tag_range(self, request: Request) -> JSONResponse:
565
        """Set tag range"""
566 1
        content_type_json_or_415(request)
567 1
        content = get_json_or_400(request, self.controller.loop)
568 1
        tag_type = content.get("tag_type")
569 1
        try:
570 1
            ranges = get_tag_ranges(content["tag_ranges"])
571
        except KytosInvalidTagRanges as err:
572
            raise HTTPException(400, detail=str(err))
573 1
        interface_id = request.path_params["interface_id"]
574 1
        interface = self.controller.get_interface_by_id(interface_id)
575 1
        if not interface:
576 1
            raise HTTPException(404, detail="Interface not found")
577 1
        try:
578 1
            interface.set_tag_ranges(ranges, tag_type)
579 1
            self.handle_on_interface_tags(interface)
580 1
        except KytosTagError as err:
581 1
            raise HTTPException(400, detail=str(err))
582 1
        return JSONResponse("Operation Successful", status_code=200)
583
584 1
    @rest('v3/interfaces/{interface_id}/tag_ranges', methods=['DELETE'])
585 1
    @validate_openapi(spec)
586 1
    def delete_tag_range(self, request: Request) -> JSONResponse:
587
        """Set tag_range from tag_type to default value [1, 4095]"""
588 1
        interface_id = request.path_params["interface_id"]
589 1
        params = request.query_params
590 1
        tag_type = params.get("tag_type", 'vlan')
591 1
        interface = self.controller.get_interface_by_id(interface_id)
592 1
        if not interface:
593 1
            raise HTTPException(404, detail="Interface not found")
594 1
        try:
595 1
            interface.remove_tag_ranges(tag_type)
596 1
            self.handle_on_interface_tags(interface)
597 1
        except KytosTagError as err:
598 1
            raise HTTPException(400, detail=str(err))
599 1
        return JSONResponse("Operation Successful", status_code=200)
600
601 1
    @rest('v3/interfaces/{interface_id}/special_tags', methods=['POST'])
602 1
    @validate_openapi(spec)
603 1
    def set_special_tags(self, request: Request) -> JSONResponse:
604
        """Set special_tags"""
605 1
        content_type_json_or_415(request)
606 1
        content = get_json_or_400(request, self.controller.loop)
607 1
        tag_type = content.get("tag_type")
608 1
        special_tags = content["special_tags"]
609 1
        interface_id = request.path_params["interface_id"]
610 1
        interface = self.controller.get_interface_by_id(interface_id)
611 1
        if not interface:
612 1
            raise HTTPException(404, detail="Interface not found")
613 1
        try:
614 1
            interface.set_special_tags(tag_type, special_tags)
615 1
            self.handle_on_interface_tags(interface)
616 1
        except KytosTagError as err:
617 1
            raise HTTPException(400, detail=str(err))
618 1
        return JSONResponse("Operation Successful", status_code=200)
619
620 1
    @rest('v3/interfaces/tag_ranges', methods=['GET'])
621 1
    @validate_openapi(spec)
622 1
    def get_all_tag_ranges(self, _: Request) -> JSONResponse:
623
        """Get all tag_ranges, available_tags, special_tags
624
         and special_available_tags from interfaces"""
625 1
        result = {}
626 1
        for switch in self.controller.switches.copy().values():
627 1
            for interface in switch.interfaces.copy().values():
628 1
                result[interface.id] = {
629
                    "available_tags": interface.available_tags,
630
                    "tag_ranges": interface.tag_ranges,
631
                    "special_tags": interface.special_tags,
632
                    "special_available_tags": interface.special_available_tags
633
                }
634 1
        return JSONResponse(result, status_code=200)
635
636 1
    @rest('v3/interfaces/{interface_id}/tag_ranges', methods=['GET'])
637 1
    @validate_openapi(spec)
638 1
    def get_tag_ranges_by_intf(self, request: Request) -> JSONResponse:
639
        """Get tag_ranges, available_tags, special_tags
640
         and special_available_tags from an interface"""
641 1
        interface_id = request.path_params["interface_id"]
642 1
        interface = self.controller.get_interface_by_id(interface_id)
643 1
        if not interface:
644 1
            raise HTTPException(404, detail="Interface not found")
645 1
        result = {
646
            interface_id: {
647
                "available_tags": interface.available_tags,
648
                "tag_ranges": interface.tag_ranges,
649
                "special_tags": interface.special_tags,
650
                "special_available_tags": interface.special_available_tags
651
            }
652
        }
653 1
        return JSONResponse(result, status_code=200)
654
655
    # Link related methods
656 1
    @rest('v3/links')
657 1
    def get_links(self, _request: Request) -> JSONResponse:
658
        """Return a json with all the links in the topology.
659
660
        Links are connections between interfaces.
661
        """
662
        return JSONResponse(self._get_links_dict())
663
664 1
    @rest('v3/links/{link_id}/enable', methods=['POST'])
665 1
    def enable_link(self, request: Request) -> JSONResponse:
666
        """Administratively enable a link in the topology."""
667 1
        link_id = request.path_params["link_id"]
668 1
        try:
669 1
            with self._links_lock:
670 1
                link = self.links[link_id]
671 1
                if not link.endpoint_a.is_enabled():
672 1
                    detail = f"{link.endpoint_a.id} needs enabling."
673 1
                    raise HTTPException(409, detail=detail)
674 1
                if not link.endpoint_b.is_enabled():
675 1
                    detail = f"{link.endpoint_b.id} needs enabling."
676 1
                    raise HTTPException(409, detail=detail)
677 1
                if not link.is_enabled():
678 1
                    self.topo_controller.enable_link(link.id)
679 1
                    link.enable()
680 1
                    self.notify_link_enabled_state(link, "enabled")
681 1
        except KeyError:
682 1
            raise HTTPException(404, detail="Link not found")
683 1
        self.notify_link_status_change(
684
            self.links[link_id],
685
            reason='link enabled'
686
        )
687 1
        self.notify_topology_update()
688 1
        return JSONResponse("Operation successful", status_code=201)
689
690 1
    @rest('v3/links/{link_id}/disable', methods=['POST'])
691 1
    def disable_link(self, request: Request) -> JSONResponse:
692
        """Administratively disable a link in the topology."""
693 1
        link_id = request.path_params["link_id"]
694 1
        try:
695 1
            with self._links_lock:
696 1
                link = self.links[link_id]
697 1
                if link.is_enabled():
698 1
                    self.topo_controller.disable_link(link.id)
699 1
                    link.disable()
700 1
                    self.notify_link_enabled_state(link, "disabled")
701 1
        except KeyError:
702 1
            raise HTTPException(404, detail="Link not found")
703 1
        self.notify_link_status_change(
704
            self.links[link_id],
705
            reason='link disabled'
706
        )
707 1
        self.notify_topology_update()
708 1
        return JSONResponse("Operation successful", status_code=201)
709
710 1
    def notify_link_enabled_state(self, link: Link, action: str):
711
        """Send a KytosEvent whether a link status (enabled/disabled)
712
         has changed its status."""
713 1
        name = f'kytos/topology.link.{action}'
714 1
        content = {'link': link}
715 1
        event = KytosEvent(name=name, content=content)
716 1
        self.controller.buffers.app.put(event)
717
718 1
    @rest('v3/links/{link_id}/metadata')
719 1
    def get_link_metadata(self, request: Request) -> JSONResponse:
720
        """Get metadata from a link."""
721 1
        link_id = request.path_params["link_id"]
722 1
        try:
723 1
            return JSONResponse({"metadata": self.links[link_id].metadata})
724 1
        except KeyError:
725 1
            raise HTTPException(404, detail="Link not found")
726
727 1
    @rest('v3/links/{link_id}/metadata', methods=['POST'])
728 1
    def add_link_metadata(self, request: Request) -> JSONResponse:
729
        """Add metadata to a link."""
730 1
        link_id = request.path_params["link_id"]
731 1
        metadata = self._get_metadata(request)
732 1
        try:
733 1
            link = self.links[link_id]
734 1
        except KeyError:
735 1
            raise HTTPException(404, detail="Link not found")
736
737 1
        self.topo_controller.add_link_metadata(link_id, metadata)
738 1
        link.extend_metadata(metadata)
739 1
        self.notify_metadata_changes(link, 'added')
740 1
        self.notify_topology_update()
741 1
        return JSONResponse("Operation successful", status_code=201)
742
743 1
    @rest('v3/links/{link_id}/metadata/{key}', methods=['DELETE'])
744 1
    def delete_link_metadata(self, request: Request) -> JSONResponse:
745
        """Delete metadata from a link."""
746 1
        link_id = request.path_params["link_id"]
747 1
        key = request.path_params["key"]
748 1
        try:
749 1
            link = self.links[link_id]
750 1
        except KeyError:
751 1
            raise HTTPException(404, detail="Link not found")
752
753 1
        try:
754 1
            _ = link.metadata[key]
755 1
        except KeyError:
756 1
            raise HTTPException(404, detail="Metadata not found")
757
758 1
        self.topo_controller.delete_link_metadata_key(link.id, key)
759 1
        link.remove_metadata(key)
760 1
        self.notify_metadata_changes(link, 'removed')
761 1
        self.notify_topology_update()
762 1
        return JSONResponse("Operation successful")
763
764 1
    @rest('v3/links/{link_id}', methods=['DELETE'])
765 1
    def delete_link(self, request: Request) -> JSONResponse:
766
        """Delete a disabled link from topology.
767
         It won't work for link with other statuses.
768
        """
769 1
        link_id = request.path_params["link_id"]
770 1
        try:
771 1
            with self._links_lock:
772 1
                link = self.links[link_id]
773 1
                if link.status != EntityStatus.DISABLED:
774 1
                    raise HTTPException(409, detail="Link is not disabled.")
775 1
                if link.endpoint_a.link and link == link.endpoint_a.link:
776 1
                    switch = link.endpoint_a.switch
777 1
                    link.endpoint_a.link = None
778 1
                    link.endpoint_a.nni = False
779 1
                    self.topo_controller.upsert_switch(
780
                        switch.id, switch.as_dict()
781
                    )
782 1
                if link.endpoint_b.link and link == link.endpoint_b.link:
783 1
                    switch = link.endpoint_b.switch
784 1
                    link.endpoint_b.link = None
785 1
                    link.endpoint_b.nni = False
786 1
                    self.topo_controller.upsert_switch(
787
                        switch.id, switch.as_dict()
788
                    )
789 1
                self.topo_controller.delete_link(link_id)
790 1
                link = self.links.pop(link_id)
791 1
        except KeyError:
792 1
            raise HTTPException(404, detail="Link not found.")
793 1
        self.notify_topology_update()
794 1
        name = 'kytos/topology.link.deleted'
795 1
        event = KytosEvent(name=name, content={'link': link})
796 1
        self.controller.buffers.app.put(event)
797 1
        return JSONResponse("Operation successful")
798
799 1
    @rest('v3/interfaces/{intf_id}', methods=['DELETE'])
800 1
    def delete_interface(self, request: Request) -> JSONResponse:
801
        """Delete an interface only if it is not used."""
802 1
        intf_id = request.path_params.get("intf_id")
803 1
        intf_split = intf_id.split(":")
804 1
        switch_id = ":".join(intf_split[:-1])
805 1
        try:
806 1
            intf_port = int(intf_split[-1])
807 1
        except ValueError:
808 1
            raise HTTPException(400, detail="Invalid interface id.")
809 1
        try:
810 1
            switch = self.controller.switches[switch_id]
811 1
        except KeyError:
812 1
            raise HTTPException(404, detail="Switch not found.")
813 1
        try:
814 1
            interface = switch.interfaces[intf_port]
815 1
        except KeyError:
816 1
            raise HTTPException(404, detail="Interface not found.")
817
818 1
        usage = self.get_intf_usage(interface)
819 1
        if usage:
820 1
            raise HTTPException(409, detail=f"Interface could not be "
821
                                            f"deleted. Reason: {usage}")
822 1
        self._delete_interface(interface)
823 1
        return JSONResponse("Operation Successful", status_code=200)
824
825 1
    @listen_to(
826
        "kytos/.*.liveness.(up|down|disabled)",
827
        pool="dynamic_single"
828
    )
829 1
    def on_link_liveness(self, event) -> None:
830
        """Handle link liveness up|down|disabled event."""
831
        with self._links_lock:
832
            liveness_status = event.name.split(".")[-1]
833
            if liveness_status == "disabled":
834
                interfaces = event.content["interfaces"]
835
                self.handle_link_liveness_disabled(interfaces)
836
            elif liveness_status in ("up", "down"):
837
                link = Link(event.content["interface_a"],
838
                            event.content["interface_b"])
839
                try:
840
                    link = self.links[link.id]
841
                except KeyError:
842
                    log.error(f"Link id {link.id} not found, {link}")
843
                    return
844
                self.handle_link_liveness_status(self.links[link.id],
845
                                                 liveness_status)
846
847 1
    def handle_link_liveness_status(self, link, liveness_status) -> None:
848
        """Handle link liveness."""
849 1
        metadata = {"liveness_status": liveness_status}
850 1
        log.info(f"Link liveness {liveness_status}: {link}")
851 1
        link.extend_metadata(metadata)
852 1
        self.notify_topology_update()
853 1
        if link.status == EntityStatus.UP and liveness_status == "up":
854 1
            self.notify_link_status_change(link, reason="liveness_up")
855 1
        if link.status == EntityStatus.DOWN and liveness_status == "down":
856 1
            self.notify_link_status_change(link, reason="liveness_down")
857
858 1
    def get_links_from_interfaces(self, interfaces) -> dict:
859
        """Get links from interfaces."""
860 1
        links_found = {}
861 1
        for interface in interfaces:
862 1
            for link in list(self.links.values()):
863 1
                if any((
864
                    interface.id == link.endpoint_a.id,
865
                    interface.id == link.endpoint_b.id,
866
                )):
867 1
                    links_found[link.id] = link
868 1
        return links_found
869
870 1
    def handle_link_liveness_disabled(self, interfaces) -> None:
871
        """Handle link liveness disabled."""
872 1
        log.info(f"Link liveness disabled interfaces: {interfaces}")
873
874 1
        key = "liveness_status"
875 1
        links = self.get_links_from_interfaces(interfaces)
876 1
        for link in links.values():
877 1
            link.remove_metadata(key)
878 1
        self.notify_topology_update()
879 1
        for link in links.values():
880 1
            self.notify_link_status_change(link, reason="liveness_disabled")
881
882 1
    @listen_to("kytos/core.interface_tags")
883 1
    def on_interface_tags(self, event):
884
        """Handle on_interface_tags."""
885
        interface = event.content['interface']
886
        with self._intfs_lock[interface.id]:
887
            if (
888
                interface.id in self._intfs_tags_updated_at
889
                and self._intfs_tags_updated_at[interface.id] > event.timestamp
890
            ):
891
                return
892
            self._intfs_tags_updated_at[interface.id] = event.timestamp
893
            self.handle_on_interface_tags(interface)
894
895 1
    def handle_on_interface_tags(self, interface):
896
        """Update interface details"""
897 1
        intf_id = interface.id
898 1
        self.topo_controller.upsert_interface_details(
899
            intf_id, interface.available_tags, interface.tag_ranges,
900
            interface.special_available_tags,
901
            interface.special_tags
902
        )
903
904 1
    @listen_to('.*.switch.(new|reconnected)')
905 1
    def on_new_switch(self, event):
906
        """Create a new Device on the Topology.
907
908
        Handle the event of a new created switch and update the topology with
909
        this new device. Also notify if the switch is enabled.
910
        """
911
        self.handle_new_switch(event)
912
913 1
    def handle_new_switch(self, event):
914
        """Create a new Device on the Topology."""
915 1
        switch = event.content['switch']
916 1
        switch.activate()
917 1
        self.topo_controller.upsert_switch(switch.id, switch.as_dict())
918 1
        log.debug('Switch %s added to the Topology.', switch.id)
919 1
        self.notify_topology_update()
920 1
        if switch.is_enabled():
921 1
            self.notify_switch_enabled(switch.id)
922
923 1
    @listen_to('.*.connection.lost')
924 1
    def on_connection_lost(self, event):
925
        """Remove a Device from the topology.
926
927
        Remove the disconnected Device and every link that has one of its
928
        interfaces.
929
        """
930
        self.handle_connection_lost(event)
931
932 1
    def handle_connection_lost(self, event):
933
        """Remove a Device from the topology."""
934 1
        switch = event.content['source'].switch
935 1
        if switch:
936 1
            switch.deactivate()
937 1
            log.debug('Switch %s removed from the Topology.', switch.id)
938 1
            self.notify_topology_update()
939
940 1
    def handle_interfaces_created(self, event):
941
        """Update the topology based on the interfaces created."""
942 1
        interfaces = event.content["interfaces"]
943 1
        if not interfaces:
944
            return
945 1
        switch = interfaces[0].switch
946 1
        self.topo_controller.upsert_switch(switch.id, switch.as_dict())
947 1
        name = "kytos/topology.switch.interface.created"
948 1
        for interface in interfaces:
949 1
            event = KytosEvent(name=name, content={'interface': interface})
950 1
            self.controller.buffers.app.put(event)
951
952 1
    def handle_interface_created(self, event):
953
        """Update the topology based on an interface created event.
954
955
        It's handled as a link_up in case a switch send a
956
        created event again and it can be belong to a link.
957
        """
958 1
        interface = event.content['interface']
959 1
        if not interface.is_active():
960 1
            self.handle_interface_link_down(interface, event)
961
        else:
962 1
            self.handle_interface_link_up(interface, event)
963
964 1
    @listen_to('.*.topology.switch.interface.created')
965 1
    def on_interface_created(self, event):
966
        """Handle individual interface create event.
967
968
        It's handled as a link_up in case a switch send a
969
        created event it can belong to an existign link.
970
        """
971
        self.handle_interface_created(event)
972
973 1
    @listen_to('.*.switch.interfaces.created')
974 1
    def on_interfaces_created(self, event):
975
        """Update the topology based on a list of created interfaces."""
976
        self.handle_interfaces_created(event)
977
978 1
    def handle_interface_down(self, event):
979
        """Update the topology based on a Port Modify event.
980
981
        The event notifies that an interface was changed to 'down'.
982
        """
983 1
        interface = event.content['interface']
984 1
        with self._intfs_lock[interface.id]:
985 1
            if (
986
                interface.id in self._intfs_updated_at
987
                and self._intfs_updated_at[interface.id] > event.timestamp
988
            ):
989
                return
990 1
            self._intfs_updated_at[interface.id] = event.timestamp
991 1
            interface.deactivate()
992 1
        self.handle_interface_link_down(interface, event)
993
994 1
    @listen_to('.*.switch.interface.deleted')
995 1
    def on_interface_deleted(self, event):
996
        """Update the topology based on a Port Delete event."""
997
        self.handle_interface_deleted(event)
998
999 1
    def handle_interface_deleted(self, event):
1000
        """Update the topology based on a Port Delete event."""
1001 1
        self.handle_interface_down(event)
1002 1
        interface = event.content['interface']
1003 1
        usage = self.get_intf_usage(interface)
1004 1
        if usage:
1005 1
            log.info(f"Interface {interface.id} could not be safely removed."
1006
                     f" Reason: {usage}")
1007
        else:
1008 1
            self._delete_interface(interface)
1009
1010 1
    def get_intf_usage(self, interface: Interface) -> Optional[str]:
1011
        """Determines how an interface is used explained in a string,
1012
        returns None if unused."""
1013 1
        if interface.is_enabled() or interface.is_active():
1014 1
            return "It is enabled or active."
1015
1016 1
        link = self._get_link_from_interface(interface)
1017 1
        if link:
1018 1
            return f"It has a link, {link.id}."
1019
1020 1
        flow_id = self.get_flow_id_by_intf(interface)
1021 1
        if flow_id:
1022 1
            return f"There is a flow installed, {flow_id}."
1023
1024 1
        return None
1025
1026 1
    def get_flow_id_by_intf(self, interface: Interface) -> str:
1027
        """Return flow_id from first found flow used by interface."""
1028 1
        flows = self.get_flows_by_switch(interface.switch.id)
1029 1
        port_n = int(interface.id.split(":")[-1])
1030 1
        for flow in flows:
1031 1
            in_port = flow["flow"].get("match", {}).get("in_port")
1032 1
            if in_port == port_n:
1033 1
                return flow["flow_id"]
1034
1035 1
            instructions = flow["flow"].get("instructions", [])
1036 1
            for instruction in instructions:
1037 1
                if instruction["instruction_type"] == "apply_actions":
1038 1
                    actions = instruction["actions"]
1039 1
                    for action in actions:
1040 1
                        if (action["action_type"] == "output"
1041
                                and action.get("port") == port_n):
1042 1
                            return flow["flow_id"]
1043
1044 1
            actions = flow["flow"].get("actions", [])
1045 1
            for action in actions:
1046 1
                if (action["action_type"] == "output"
1047
                        and action.get("port") == port_n):
1048 1
                    return flow["flow_id"]
1049 1
        return None
1050
1051 1
    def _delete_interface(self, interface: Interface):
1052
        """Delete any trace of an interface. Only use this method when
1053
         it was confirmed that the interface is not used."""
1054 1
        switch: Switch = interface.switch
1055 1
        switch.remove_interface(interface)
1056 1
        self.topo_controller.upsert_switch(switch.id, switch.as_dict())
1057 1
        self.topo_controller.delete_interface_from_details(interface.id)
1058
1059 1
    @listen_to('.*.switch.interface.link_up')
1060 1
    def on_interface_link_up(self, event):
1061
        """Update the topology based on a Port Modify event.
1062
1063
        The event notifies that an interface's link was changed to 'up'.
1064
        """
1065
        interface = event.content['interface']
1066
        self.handle_interface_link_up(interface, event)
1067
1068 1
    def handle_interface_link_up(self, interface, event):
1069
        """Update the topology based on a Port Modify event."""
1070 1
        with self._intfs_lock[interface.id]:
1071 1
            if (
1072
                interface.id in self._intfs_updated_at
1073
                and self._intfs_updated_at[interface.id] > event.timestamp
1074
            ):
1075 1
                return
1076 1
            self._intfs_updated_at[interface.id] = event.timestamp
1077 1
            self.handle_link_up(interface)
1078
1079 1
    @tenacity.retry(
1080
        stop=stop_after_attempt(3),
1081
        wait=wait_combine(wait_fixed(3), wait_random(min=2, max=7)),
1082
        before_sleep=before_sleep,
1083
        retry=retry_if_exception_type(httpx.RequestError),
1084
    )
1085 1
    def get_flows_by_switch(self, dpid: str) -> list:
1086
        """Get installed flows by switch from flow_manager."""
1087 1
        endpoint = settings.FLOW_MANAGER_URL +\
1088
            f'/stored_flows?state=installed&dpid={dpid}'
1089 1
        res = httpx.get(endpoint)
1090 1
        if res.is_server_error or res.status_code in (404, 400):
1091 1
            raise httpx.RequestError(res.text)
1092 1
        return res.json().get(dpid, [])
1093
1094 1
    def link_status_hook_link_up_timer(self, link) -> Optional[EntityStatus]:
1095
        """Link status hook link up timer."""
1096 1
        tnow = time.time()
1097 1
        if (
1098
            link.is_active()
1099
            and link.is_enabled()
1100
            and "last_status_change" in link.metadata
1101
            and tnow - link.metadata['last_status_change'] < self.link_up_timer
1102
        ):
1103 1
            return EntityStatus.DOWN
1104 1
        return None
1105
1106 1
    def notify_link_up_if_status(self, link, reason="link up") -> None:
1107
        """Tries to notify link up and topology changes based on its status
1108
1109
        Currently, it needs to wait up to a timer."""
1110 1
        time.sleep(self.link_up_timer)
1111 1
        if link.status != EntityStatus.UP:
1112
            return
1113 1
        with self._links_lock:
1114 1
            notified_at = link.get_metadata("notified_up_at")
1115 1
            if (
1116
                notified_at
1117
                and (now() - notified_at.replace(tzinfo=timezone.utc)).seconds
1118
                < self.link_up_timer
1119
            ):
1120 1
                return
1121 1
            key, notified_at = "notified_up_at", now()
1122 1
            link.update_metadata(key, now())
1123 1
            self.notify_topology_update()
1124 1
            self.notify_link_status_change(link, reason)
1125
1126 1
    def handle_link_up(self, interface):
1127
        """Handle link up for an interface."""
1128 1
        with self._links_lock:
1129 1
            link = self._get_link_from_interface(interface)
1130 1
            if not link:
1131
                self.notify_topology_update()
1132
                return
1133 1
            other_interface = (
1134
                link.endpoint_b if link.endpoint_a == interface
1135
                else link.endpoint_a
1136
            )
1137 1
            if other_interface.is_active() is False:
1138 1
                self.notify_topology_update()
1139 1
                return
1140 1
            metadata = {
1141
                'last_status_change': time.time(),
1142
                'last_status_is_active': True
1143
            }
1144 1
            link.extend_metadata(metadata)
1145 1
            link.activate()
1146 1
            self.notify_topology_update()
1147 1
            event = KytosEvent(
1148
                name="kytos/topology.notify_link_up_if_status",
1149
                content={"reason": "link up", "link": link}
1150
            )
1151 1
            self.controller.buffers.app.put(event)
1152
1153 1
    @listen_to('.*.switch.interface.link_down')
1154 1
    def on_interface_link_down(self, event):
1155
        """Update the topology based on a Port Modify event.
1156
1157
        The event notifies that an interface's link was changed to 'down'.
1158
        """
1159
        interface = event.content['interface']
1160
        self.handle_interface_link_down(interface, event)
1161
1162 1
    def handle_interface_link_down(self, interface, event):
1163
        """Update the topology based on an interface."""
1164 1
        with self._intfs_lock[interface.id]:
1165 1
            if (
1166
                interface.id in self._intfs_updated_at
1167
                and self._intfs_updated_at[interface.id] > event.timestamp
1168
            ):
1169 1
                return
1170 1
            self._intfs_updated_at[interface.id] = event.timestamp
1171 1
            self.handle_link_down(interface)
1172
1173 1
    def handle_link_down(self, interface):
1174
        """Notify a link is down."""
1175 1
        with self._links_lock:
1176 1
            link = self._get_link_from_interface(interface)
1177 1
            if not link or not link.get_metadata("last_status_is_active"):
1178 1
                self.notify_topology_update()
1179 1
                return
1180 1
            link.deactivate()
1181 1
            metadata = {
1182
                "last_status_change": time.time(),
1183
                "last_status_is_active": False,
1184
            }
1185 1
            link.extend_metadata(metadata)
1186 1
            self.notify_link_status_change(link, reason="link down")
1187 1
            self.notify_topology_update()
1188
1189 1
    @listen_to('.*.interface.is.nni')
1190 1
    def on_add_links(self, event):
1191
        """Update the topology with links related to the NNI interfaces."""
1192
        self.add_links(event)
1193
1194 1
    def add_links(self, event):
1195
        """Update the topology with links related to the NNI interfaces."""
1196 1
        interface_a = event.content['interface_a']
1197 1
        interface_b = event.content['interface_b']
1198
1199 1
        try:
1200 1
            with self._links_lock:
1201 1
                link, created = self._get_link_or_create(interface_a,
1202
                                                         interface_b)
1203 1
                interface_a.update_link(link)
1204 1
                interface_b.update_link(link)
1205
1206 1
                link.endpoint_a = interface_a
1207 1
                link.endpoint_b = interface_b
1208
1209 1
                interface_a.nni = True
1210 1
                interface_b.nni = True
1211
1212
        except KytosLinkCreationError as err:
1213
            log.error(f'Error creating link: {err}.')
1214
            return
1215
1216 1
        if not created:
1217
            return
1218
1219 1
        self.notify_topology_update()
1220 1
        if not link.is_active():
1221
            return
1222
1223 1
        metadata = {
1224
            'last_status_change': time.time(),
1225
            'last_status_is_active': True
1226
        }
1227 1
        link.extend_metadata(metadata)
1228 1
        self.topo_controller.upsert_link(link.id, link.as_dict())
1229 1
        self.notify_link_up_if_status(link, "link up")
1230
1231 1
    @listen_to('.*.of_lldp.network_status.updated')
1232 1
    def on_lldp_status_updated(self, event):
1233
        """Handle of_lldp.network_status.updated from of_lldp."""
1234
        self.handle_lldp_status_updated(event)
1235
1236 1
    @listen_to(".*.topo_controller.upsert_switch")
1237 1
    def on_topo_controller_upsert_switch(self, event) -> None:
1238
        """Listen to topo_controller_upsert_switch."""
1239
        self.handle_topo_controller_upsert_switch(event.content["switch"])
1240
1241 1
    def handle_topo_controller_upsert_switch(self, switch) -> Optional[dict]:
1242
        """Handle topo_controller_upsert_switch."""
1243 1
        return self.topo_controller.upsert_switch(switch.id, switch.as_dict())
1244
1245 1
    def handle_lldp_status_updated(self, event) -> None:
1246
        """Handle .*.network_status.updated events from of_lldp."""
1247 1
        content = event.content
1248 1
        interface_ids = content["interface_ids"]
1249 1
        switches = set()
1250 1
        for interface_id in interface_ids:
1251 1
            dpid = ":".join(interface_id.split(":")[:-1])
1252 1
            switch = self.controller.get_switch_by_dpid(dpid)
1253 1
            if switch:
1254 1
                switches.add(switch)
1255
1256 1
        name = "kytos/topology.topo_controller.upsert_switch"
1257 1
        for switch in switches:
1258 1
            event = KytosEvent(name=name, content={"switch": switch})
1259 1
            self.controller.buffers.app.put(event)
1260
1261 1
    def notify_switch_enabled(self, dpid):
1262
        """Send an event to notify that a switch is enabled."""
1263 1
        name = 'kytos/topology.switch.enabled'
1264 1
        event = KytosEvent(name=name, content={'dpid': dpid})
1265 1
        self.controller.buffers.app.put(event)
1266
1267 1
    def notify_switch_links_status(self, switch, reason):
1268
        """Send an event to notify the status of a link in a switch"""
1269 1
        with self._links_lock:
1270 1
            for link in self.links.values():
1271 1
                if switch in (link.endpoint_a.switch, link.endpoint_b.switch):
1272 1
                    if reason == "link enabled":
1273 1
                        name = 'kytos/topology.notify_link_up_if_status'
1274 1
                        content = {'reason': reason, "link": link}
1275 1
                        event = KytosEvent(name=name, content=content)
1276 1
                        self.controller.buffers.app.put(event)
1277
                    else:
1278 1
                        self.notify_link_status_change(link, reason)
1279
1280 1
    def notify_switch_disabled(self, dpid):
1281
        """Send an event to notify that a switch is disabled."""
1282 1
        name = 'kytos/topology.switch.disabled'
1283 1
        event = KytosEvent(name=name, content={'dpid': dpid})
1284 1
        self.controller.buffers.app.put(event)
1285
1286 1
    def notify_topology_update(self):
1287
        """Send an event to notify about updates on the topology."""
1288 1
        name = 'kytos/topology.updated'
1289 1
        event = KytosEvent(name=name, content={'topology':
1290
                                               self._get_topology()})
1291 1
        self.controller.buffers.app.put(event)
1292
1293 1
    def notify_interface_link_status(self, interface, reason):
1294
        """Send an event to notify the status of a link from
1295
        an interface."""
1296 1
        link = self._get_link_from_interface(interface)
1297 1
        if link:
1298 1
            if reason == "link enabled":
1299 1
                name = 'kytos/topology.notify_link_up_if_status'
1300 1
                content = {'reason': reason, "link": link}
1301 1
                event = KytosEvent(name=name, content=content)
1302 1
                self.controller.buffers.app.put(event)
1303
            else:
1304 1
                self.notify_link_status_change(link, reason)
1305
1306 1
    def notify_link_status_change(self, link, reason='not given'):
1307
        """Send an event to notify (up/down) from a status change on
1308
         a link."""
1309 1
        link_id = link.id
1310 1
        with self.link_status_lock:
1311 1
            if (
1312
                (not link.status_reason and link.status == EntityStatus.UP)
1313
                and link_id not in self.link_up
1314
            ):
1315 1
                log.info(f"{link} changed status {link.status}, "
1316
                         f"reason: {reason}")
1317 1
                self.link_up.add(link_id)
1318 1
                event = KytosEvent(
1319
                    name='kytos/topology.link_up',
1320
                    content={
1321
                        'link': link,
1322
                        'reason': reason
1323
                    },
1324
                )
1325 1
            elif (
1326
                (link.status_reason or link.status != EntityStatus.UP)
1327
                and link_id in self.link_up
1328
            ):
1329 1
                log.info(f"{link} changed status {link.status}, "
1330
                         f"reason: {reason}")
1331 1
                self.link_up.remove(link_id)
1332 1
                event = KytosEvent(
1333
                    name='kytos/topology.link_down',
1334
                    content={
1335
                        'link': link,
1336
                        'reason': reason
1337
                    },
1338
                )
1339
            else:
1340 1
                return
1341 1
        self.controller.buffers.app.put(event)
1342
1343 1
    def notify_metadata_changes(self, obj, action):
1344
        """Send an event to notify about metadata changes."""
1345 1
        if isinstance(obj, Switch):
1346 1
            entity = 'switch'
1347 1
            entities = 'switches'
1348 1
        elif isinstance(obj, Interface):
1349 1
            entity = 'interface'
1350 1
            entities = 'interfaces'
1351 1
        elif isinstance(obj, Link):
1352 1
            entity = 'link'
1353 1
            entities = 'links'
1354
        else:
1355 1
            raise ValueError(
1356
                'Invalid object, supported: Switch, Interface, Link'
1357
            )
1358
1359 1
        name = f'kytos/topology.{entities}.metadata.{action}'
1360 1
        content = {entity: obj, 'metadata': obj.metadata.copy()}
1361 1
        event = KytosEvent(name=name, content=content)
1362 1
        self.controller.buffers.app.put(event)
1363 1
        log.debug(f'Metadata from {obj.id} was {action}.')
1364
1365 1
    @listen_to('kytos/topology.notify_link_up_if_status')
1366 1
    def on_notify_link_up_if_status(self, event):
1367
        """Tries to notify link up and topology changes"""
1368
        link = event.content["link"]
1369
        reason = event.content["reason"]
1370
        self.notify_link_up_if_status(link, reason)
1371
1372 1
    @listen_to('.*.switch.port.created')
1373 1
    def on_notify_port_created(self, event):
1374
        """Notify when a port is created."""
1375
        self.notify_port_created(event)
1376
1377 1
    def notify_port_created(self, event):
1378
        """Notify when a port is created."""
1379 1
        name = 'kytos/topology.port.created'
1380 1
        event = KytosEvent(name=name, content=event.content)
1381 1
        self.controller.buffers.app.put(event)
1382
1383 1
    @staticmethod
1384 1
    def load_interfaces_tags_values(switch: Switch,
1385
                                    interfaces_details: List[dict]) -> None:
1386
        """Load interfaces available tags (vlans)."""
1387 1
        if not interfaces_details:
1388
            return
1389 1
        for interface_details in interfaces_details:
1390 1
            available_tags = interface_details['available_tags']
1391 1
            if not available_tags:
1392
                continue
1393 1
            log.debug(f"Interface id {interface_details['id']} loading "
1394
                      f"{len(available_tags)} "
1395
                      "available tags")
1396 1
            port_number = int(interface_details["id"].split(":")[-1])
1397 1
            interface = switch.interfaces[port_number]
1398 1
            interface.set_available_tags_tag_ranges(
1399
                available_tags,
1400
                interface_details['tag_ranges'],
1401
                interface_details['special_available_tags'],
1402
                interface_details['special_tags'],
1403
            )
1404
1405 1
    @listen_to(
1406
        'topology.interruption.(start|end)',
1407
        pool="dynamic_single"
1408
    )
1409 1
    def on_interruption(self, event: KytosEvent):
1410
        """Deals with service interruptions."""
1411
        with self._links_lock:
1412
            _, _, interrupt_type = event.name.rpartition(".")
1413
            if interrupt_type == "start":
1414
                self.handle_interruption_start(event)
1415
            elif interrupt_type == "end":
1416
                self.handle_interruption_end(event)
1417
1418 1 View Code Duplication
    def handle_interruption_start(self, event: KytosEvent):
0 ignored issues
show
This code seems to be duplicated in your project.
Loading history...
1419
        """Deals with the start of service interruption."""
1420 1
        interrupt_type = event.content['type']
1421 1
        switches = event.content.get('switches', [])
1422 1
        interfaces = event.content.get('interfaces', [])
1423 1
        links = event.content.get('links', [])
1424 1
        log.info(
1425
            'Received interruption start of type \'%s\' '
1426
            'affecting switches %s, interfaces %s, links %s',
1427
            interrupt_type,
1428
            switches,
1429
            interfaces,
1430
            links
1431
        )
1432
        # for switch_id in switches:
1433
        #     pass
1434
        # for interface_id in interfaces:
1435
        #     pass
1436 1
        for link_id in links:
1437 1
            link = self.links.get(link_id)
1438 1
            if link is None:
1439
                log.error(
1440
                    "Invalid link id '%s' for interruption of type '%s;",
1441
                    link_id,
1442
                    interrupt_type
1443
                )
1444
            else:
1445 1
                self.notify_link_status_change(link, interrupt_type)
1446 1
        self.notify_topology_update()
1447
1448 1 View Code Duplication
    def handle_interruption_end(self, event: KytosEvent):
0 ignored issues
show
This code seems to be duplicated in your project.
Loading history...
1449
        """Deals with the end of service interruption."""
1450 1
        interrupt_type = event.content['type']
1451 1
        switches = event.content.get('switches', [])
1452 1
        interfaces = event.content.get('interfaces', [])
1453 1
        links = event.content.get('links', [])
1454 1
        log.info(
1455
            'Received interruption end of type \'%s\' '
1456
            'affecting switches %s, interfaces %s, links %s',
1457
            interrupt_type,
1458
            switches,
1459
            interfaces,
1460
            links
1461
        )
1462
        # for switch_id in switches:
1463
        #     pass
1464
        # for interface_id in interfaces:
1465
        #     pass
1466 1
        for link_id in links:
1467 1
            link = self.links.get(link_id)
1468 1
            if link is None:
1469
                log.error(
1470
                    "Invalid link id '%s' for interruption of type '%s;",
1471
                    link_id,
1472
                    interrupt_type
1473
                )
1474
            else:
1475 1
                self.notify_link_status_change(link, interrupt_type)
1476
        self.notify_topology_update()
1477