Issues (26)

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