Passed
Pull Request — master (#227)
by Vinicius
03:42
created

build.main.Main.on_link_liveness()   B

Complexity

Conditions 5

Size

Total Lines 21
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 21.2759

Importance

Changes 0
Metric Value
cc 5
eloc 19
nop 2
dl 0
loc 21
ccs 2
cts 15
cp 0.1333
crap 21.2759
rs 8.9833
c 0
b 0
f 0
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
        with self._links_lock:
862 1
            for interface in interfaces:
863 1
                for link in self.links.values():
864 1
                    if any((
865
                        interface.id == link.endpoint_a.id,
866
                        interface.id == link.endpoint_b.id,
867
                    )):
868 1
                        links_found[link.id] = link
869 1
        return links_found
870
871 1
    def handle_link_liveness_disabled(self, interfaces) -> None:
872
        """Handle link liveness disabled."""
873 1
        log.info(f"Link liveness disabled interfaces: {interfaces}")
874
875 1
        key = "liveness_status"
876 1
        links = self.get_links_from_interfaces(interfaces)
877 1
        for link in links.values():
878 1
            link.remove_metadata(key)
879 1
        self.notify_topology_update()
880 1
        for link in links.values():
881 1
            self.notify_link_status_change(link, reason="liveness_disabled")
882
883 1
    @listen_to("kytos/core.interface_tags")
884 1
    def on_interface_tags(self, event):
885
        """Handle on_interface_tags."""
886
        interface = event.content['interface']
887
        with self._intfs_lock[interface.id]:
888
            if (
889
                interface.id in self._intfs_tags_updated_at
890
                and self._intfs_tags_updated_at[interface.id] > event.timestamp
891
            ):
892
                return
893
            self._intfs_tags_updated_at[interface.id] = event.timestamp
894
            self.handle_on_interface_tags(interface)
895
896 1
    def handle_on_interface_tags(self, interface):
897
        """Update interface details"""
898 1
        intf_id = interface.id
899 1
        self.topo_controller.upsert_interface_details(
900
            intf_id, interface.available_tags, interface.tag_ranges,
901
            interface.special_available_tags,
902
            interface.special_tags
903
        )
904
905 1
    @listen_to('.*.switch.(new|reconnected)')
906 1
    def on_new_switch(self, event):
907
        """Create a new Device on the Topology.
908
909
        Handle the event of a new created switch and update the topology with
910
        this new device. Also notify if the switch is enabled.
911
        """
912
        self.handle_new_switch(event)
913
914 1
    def handle_new_switch(self, event):
915
        """Create a new Device on the Topology."""
916 1
        switch = event.content['switch']
917 1
        switch.activate()
918 1
        self.topo_controller.upsert_switch(switch.id, switch.as_dict())
919 1
        log.debug('Switch %s added to the Topology.', switch.id)
920 1
        self.notify_topology_update()
921 1
        if switch.is_enabled():
922 1
            self.notify_switch_enabled(switch.id)
923
924 1
    @listen_to('.*.connection.lost')
925 1
    def on_connection_lost(self, event):
926
        """Remove a Device from the topology.
927
928
        Remove the disconnected Device and every link that has one of its
929
        interfaces.
930
        """
931
        self.handle_connection_lost(event)
932
933 1
    def handle_connection_lost(self, event):
934
        """Remove a Device from the topology."""
935 1
        switch = event.content['source'].switch
936 1
        if switch:
937 1
            switch.deactivate()
938 1
            log.debug('Switch %s removed from the Topology.', switch.id)
939 1
            self.notify_topology_update()
940
941 1
    def handle_interfaces_created(self, event):
942
        """Update the topology based on the interfaces created."""
943 1
        interfaces = event.content["interfaces"]
944 1
        if not interfaces:
945
            return
946 1
        switch = interfaces[0].switch
947 1
        self.topo_controller.upsert_switch(switch.id, switch.as_dict())
948 1
        name = "kytos/topology.switch.interface.created"
949 1
        for interface in interfaces:
950 1
            event = KytosEvent(name=name, content={'interface': interface})
951 1
            self.controller.buffers.app.put(event)
952
953 1
    def handle_interface_created(self, event):
954
        """Update the topology based on an interface created event.
955
956
        It's handled as a link_up in case a switch send a
957
        created event again and it can be belong to a link.
958
        """
959 1
        interface = event.content['interface']
960 1
        if not interface.is_active():
961 1
            self.handle_interface_link_down(interface, event)
962
        else:
963 1
            self.handle_interface_link_up(interface, event)
964
965 1
    @listen_to('.*.topology.switch.interface.created')
966 1
    def on_interface_created(self, event):
967
        """Handle individual interface create event.
968
969
        It's handled as a link_up in case a switch send a
970
        created event it can belong to an existign link.
971
        """
972
        self.handle_interface_created(event)
973
974 1
    @listen_to('.*.switch.interfaces.created')
975 1
    def on_interfaces_created(self, event):
976
        """Update the topology based on a list of created interfaces."""
977
        self.handle_interfaces_created(event)
978
979 1
    def handle_interface_down(self, event):
980
        """Update the topology based on a Port Modify event.
981
982
        The event notifies that an interface was changed to 'down'.
983
        """
984 1
        interface = event.content['interface']
985 1
        with self._intfs_lock[interface.id]:
986 1
            if (
987
                interface.id in self._intfs_updated_at
988
                and self._intfs_updated_at[interface.id] > event.timestamp
989
            ):
990
                return
991 1
            self._intfs_updated_at[interface.id] = event.timestamp
992 1
            interface.deactivate()
993 1
        self.handle_interface_link_down(interface, event)
994
995 1
    @listen_to('.*.switch.interface.deleted')
996 1
    def on_interface_deleted(self, event):
997
        """Update the topology based on a Port Delete event."""
998
        self.handle_interface_deleted(event)
999
1000 1
    def handle_interface_deleted(self, event):
1001
        """Update the topology based on a Port Delete event."""
1002 1
        self.handle_interface_down(event)
1003 1
        interface = event.content['interface']
1004 1
        usage = self.get_intf_usage(interface)
1005 1
        if usage:
1006 1
            log.info(f"Interface {interface.id} could not be safely removed."
1007
                     f" Reason: {usage}")
1008
        else:
1009 1
            self._delete_interface(interface)
1010
1011 1
    def get_intf_usage(self, interface: Interface) -> Optional[str]:
1012
        """Determines how an interface is used explained in a string,
1013
        returns None if unused."""
1014 1
        if interface.is_enabled() or interface.is_active():
1015 1
            return "It is enabled or active."
1016
1017 1
        link = self._get_link_from_interface(interface)
1018 1
        if link:
1019 1
            return f"It has a link, {link.id}."
1020
1021 1
        flow_id = self.get_flow_id_by_intf(interface)
1022 1
        if flow_id:
1023 1
            return f"There is a flow installed, {flow_id}."
1024
1025 1
        return None
1026
1027 1
    def get_flow_id_by_intf(self, interface: Interface) -> str:
1028
        """Return flow_id from first found flow used by interface."""
1029 1
        flows = self.get_flows_by_switch(interface.switch.id)
1030 1
        port_n = int(interface.id.split(":")[-1])
1031 1
        for flow in flows:
1032 1
            in_port = flow["flow"].get("match", {}).get("in_port")
1033 1
            if in_port == port_n:
1034 1
                return flow["flow_id"]
1035
1036 1
            instructions = flow["flow"].get("instructions", [])
1037 1
            for instruction in instructions:
1038 1
                if instruction["instruction_type"] == "apply_actions":
1039 1
                    actions = instruction["actions"]
1040 1
                    for action in actions:
1041 1
                        if (action["action_type"] == "output"
1042
                                and action.get("port") == port_n):
1043 1
                            return flow["flow_id"]
1044
1045 1
            actions = flow["flow"].get("actions", [])
1046 1
            for action in actions:
1047 1
                if (action["action_type"] == "output"
1048
                        and action.get("port") == port_n):
1049 1
                    return flow["flow_id"]
1050 1
        return None
1051
1052 1
    def _delete_interface(self, interface: Interface):
1053
        """Delete any trace of an interface. Only use this method when
1054
         it was confirmed that the interface is not used."""
1055 1
        switch: Switch = interface.switch
1056 1
        switch.remove_interface(interface)
1057 1
        self.topo_controller.upsert_switch(switch.id, switch.as_dict())
1058 1
        self.topo_controller.delete_interface_from_details(interface.id)
1059
1060 1
    @listen_to('.*.switch.interface.link_up')
1061 1
    def on_interface_link_up(self, event):
1062
        """Update the topology based on a Port Modify event.
1063
1064
        The event notifies that an interface's link was changed to 'up'.
1065
        """
1066
        interface = event.content['interface']
1067
        self.handle_interface_link_up(interface, event)
1068
1069 1
    def handle_interface_link_up(self, interface, event):
1070
        """Update the topology based on a Port Modify event."""
1071 1
        with self._intfs_lock[interface.id]:
1072 1
            if (
1073
                interface.id in self._intfs_updated_at
1074
                and self._intfs_updated_at[interface.id] > event.timestamp
1075
            ):
1076 1
                return
1077 1
            self._intfs_updated_at[interface.id] = event.timestamp
1078 1
            self.handle_link_up(interface)
1079
1080 1
    @tenacity.retry(
1081
        stop=stop_after_attempt(3),
1082
        wait=wait_combine(wait_fixed(3), wait_random(min=2, max=7)),
1083
        before_sleep=before_sleep,
1084
        retry=retry_if_exception_type(httpx.RequestError),
1085
    )
1086 1
    def get_flows_by_switch(self, dpid: str) -> list:
1087
        """Get installed flows by switch from flow_manager."""
1088 1
        endpoint = settings.FLOW_MANAGER_URL +\
1089
            f'/stored_flows?state=installed&dpid={dpid}'
1090 1
        res = httpx.get(endpoint)
1091 1
        if res.is_server_error or res.status_code in (404, 400):
1092 1
            raise httpx.RequestError(res.text)
1093 1
        return res.json().get(dpid, [])
1094
1095 1
    def link_status_hook_link_up_timer(self, link) -> Optional[EntityStatus]:
1096
        """Link status hook link up timer."""
1097 1
        tnow = time.time()
1098 1
        if (
1099
            link.is_active()
1100
            and link.is_enabled()
1101
            and "last_status_change" in link.metadata
1102
            and tnow - link.metadata['last_status_change'] < self.link_up_timer
1103
        ):
1104 1
            return EntityStatus.DOWN
1105 1
        return None
1106
1107 1
    def notify_link_up_if_status(self, link, reason="link up") -> None:
1108
        """Tries to notify link up and topology changes based on its status
1109
1110
        Currently, it needs to wait up to a timer."""
1111 1
        time.sleep(self.link_up_timer)
1112 1
        if link.status != EntityStatus.UP:
1113
            return
1114 1
        with self._links_lock:
1115 1
            notified_at = link.get_metadata("notified_up_at")
1116 1
            if (
1117
                notified_at
1118
                and (now() - notified_at.replace(tzinfo=timezone.utc)).seconds
1119
                < self.link_up_timer
1120
            ):
1121 1
                return
1122 1
            key, notified_at = "notified_up_at", now()
1123 1
            link.update_metadata(key, now())
1124 1
            self.notify_topology_update()
1125 1
            self.notify_link_status_change(link, reason)
1126
1127 1
    def handle_link_up(self, interface):
1128
        """Handle link up for an interface."""
1129 1
        with self._links_lock:
1130 1
            link = self._get_link_from_interface(interface)
1131 1
            if not link:
1132
                self.notify_topology_update()
1133
                return
1134 1
            other_interface = (
1135
                link.endpoint_b if link.endpoint_a == interface
1136
                else link.endpoint_a
1137
            )
1138 1
            if other_interface.is_active() is False:
1139 1
                self.notify_topology_update()
1140 1
                return
1141 1
            metadata = {
1142
                'last_status_change': time.time(),
1143
                'last_status_is_active': True
1144
            }
1145 1
            link.extend_metadata(metadata)
1146 1
            link.activate()
1147 1
            self.notify_topology_update()
1148 1
            event = KytosEvent(
1149
                name="kytos/topology.notify_link_up_if_status",
1150
                content={"reason": "link up", "link": link}
1151
            )
1152 1
            self.controller.buffers.app.put(event)
1153
1154 1
    @listen_to('.*.switch.interface.link_down')
1155 1
    def on_interface_link_down(self, event):
1156
        """Update the topology based on a Port Modify event.
1157
1158
        The event notifies that an interface's link was changed to 'down'.
1159
        """
1160
        interface = event.content['interface']
1161
        self.handle_interface_link_down(interface, event)
1162
1163 1
    def handle_interface_link_down(self, interface, event):
1164
        """Update the topology based on an interface."""
1165 1
        with self._intfs_lock[interface.id]:
1166 1
            if (
1167
                interface.id in self._intfs_updated_at
1168
                and self._intfs_updated_at[interface.id] > event.timestamp
1169
            ):
1170 1
                return
1171 1
            self._intfs_updated_at[interface.id] = event.timestamp
1172 1
            self.handle_link_down(interface)
1173
1174 1
    def handle_link_down(self, interface):
1175
        """Notify a link is down."""
1176 1
        with self._links_lock:
1177 1
            link = self._get_link_from_interface(interface)
1178 1
            if not link or not link.get_metadata("last_status_is_active"):
1179 1
                self.notify_topology_update()
1180 1
                return
1181 1
            link.deactivate()
1182 1
            metadata = {
1183
                "last_status_change": time.time(),
1184
                "last_status_is_active": False,
1185
            }
1186 1
            link.extend_metadata(metadata)
1187 1
            self.notify_link_status_change(link, reason="link down")
1188 1
            self.notify_topology_update()
1189
1190 1
    @listen_to('.*.interface.is.nni')
1191 1
    def on_add_links(self, event):
1192
        """Update the topology with links related to the NNI interfaces."""
1193
        self.add_links(event)
1194
1195 1
    def add_links(self, event):
1196
        """Update the topology with links related to the NNI interfaces."""
1197 1
        interface_a = event.content['interface_a']
1198 1
        interface_b = event.content['interface_b']
1199
1200 1
        try:
1201 1
            with self._links_lock:
1202 1
                link, created = self._get_link_or_create(interface_a,
1203
                                                         interface_b)
1204 1
                interface_a.update_link(link)
1205 1
                interface_b.update_link(link)
1206
1207 1
                link.endpoint_a = interface_a
1208 1
                link.endpoint_b = interface_b
1209
1210 1
                interface_a.nni = True
1211 1
                interface_b.nni = True
1212
1213
        except KytosLinkCreationError as err:
1214
            log.error(f'Error creating link: {err}.')
1215
            return
1216
1217 1
        if not created:
1218
            return
1219
1220 1
        self.notify_topology_update()
1221 1
        if not link.is_active():
1222
            return
1223
1224 1
        metadata = {
1225
            'last_status_change': time.time(),
1226
            'last_status_is_active': True
1227
        }
1228 1
        link.extend_metadata(metadata)
1229 1
        self.topo_controller.upsert_link(link.id, link.as_dict())
1230 1
        self.notify_link_up_if_status(link, "link up")
1231
1232 1
    @listen_to('.*.of_lldp.network_status.updated')
1233 1
    def on_lldp_status_updated(self, event):
1234
        """Handle of_lldp.network_status.updated from of_lldp."""
1235
        self.handle_lldp_status_updated(event)
1236
1237 1
    @listen_to(".*.topo_controller.upsert_switch")
1238 1
    def on_topo_controller_upsert_switch(self, event) -> None:
1239
        """Listen to topo_controller_upsert_switch."""
1240
        self.handle_topo_controller_upsert_switch(event.content["switch"])
1241
1242 1
    def handle_topo_controller_upsert_switch(self, switch) -> Optional[dict]:
1243
        """Handle topo_controller_upsert_switch."""
1244 1
        return self.topo_controller.upsert_switch(switch.id, switch.as_dict())
1245
1246 1
    def handle_lldp_status_updated(self, event) -> None:
1247
        """Handle .*.network_status.updated events from of_lldp."""
1248 1
        content = event.content
1249 1
        interface_ids = content["interface_ids"]
1250 1
        switches = set()
1251 1
        for interface_id in interface_ids:
1252 1
            dpid = ":".join(interface_id.split(":")[:-1])
1253 1
            switch = self.controller.get_switch_by_dpid(dpid)
1254 1
            if switch:
1255 1
                switches.add(switch)
1256
1257 1
        name = "kytos/topology.topo_controller.upsert_switch"
1258 1
        for switch in switches:
1259 1
            event = KytosEvent(name=name, content={"switch": switch})
1260 1
            self.controller.buffers.app.put(event)
1261
1262 1
    def notify_switch_enabled(self, dpid):
1263
        """Send an event to notify that a switch is enabled."""
1264 1
        name = 'kytos/topology.switch.enabled'
1265 1
        event = KytosEvent(name=name, content={'dpid': dpid})
1266 1
        self.controller.buffers.app.put(event)
1267
1268 1
    def notify_switch_links_status(self, switch, reason):
1269
        """Send an event to notify the status of a link in a switch"""
1270 1
        with self._links_lock:
1271 1
            for link in self.links.values():
1272 1
                if switch in (link.endpoint_a.switch, link.endpoint_b.switch):
1273 1
                    if reason == "link enabled":
1274 1
                        name = 'kytos/topology.notify_link_up_if_status'
1275 1
                        content = {'reason': reason, "link": link}
1276 1
                        event = KytosEvent(name=name, content=content)
1277 1
                        self.controller.buffers.app.put(event)
1278
                    else:
1279 1
                        self.notify_link_status_change(link, reason)
1280
1281 1
    def notify_switch_disabled(self, dpid):
1282
        """Send an event to notify that a switch is disabled."""
1283 1
        name = 'kytos/topology.switch.disabled'
1284 1
        event = KytosEvent(name=name, content={'dpid': dpid})
1285 1
        self.controller.buffers.app.put(event)
1286
1287 1
    def notify_topology_update(self):
1288
        """Send an event to notify about updates on the topology."""
1289 1
        name = 'kytos/topology.updated'
1290 1
        event = KytosEvent(name=name, content={'topology':
1291
                                               self._get_topology()})
1292 1
        self.controller.buffers.app.put(event)
1293
1294 1
    def notify_interface_link_status(self, interface, reason):
1295
        """Send an event to notify the status of a link from
1296
        an interface."""
1297 1
        link = self._get_link_from_interface(interface)
1298 1
        if link:
1299 1
            if reason == "link enabled":
1300 1
                name = 'kytos/topology.notify_link_up_if_status'
1301 1
                content = {'reason': reason, "link": link}
1302 1
                event = KytosEvent(name=name, content=content)
1303 1
                self.controller.buffers.app.put(event)
1304
            else:
1305 1
                self.notify_link_status_change(link, reason)
1306
1307 1
    def notify_link_status_change(self, link, reason='not given'):
1308
        """Send an event to notify (up/down) from a status change on
1309
         a link."""
1310 1
        link_id = link.id
1311 1
        with self.link_status_lock:
1312 1
            if (
1313
                (not link.status_reason and link.status == EntityStatus.UP)
1314
                and link_id not in self.link_up
1315
            ):
1316 1
                log.info(f"{link} changed status {link.status}, "
1317
                         f"reason: {reason}")
1318 1
                self.link_up.add(link_id)
1319 1
                event = KytosEvent(
1320
                    name='kytos/topology.link_up',
1321
                    content={
1322
                        'link': link,
1323
                        'reason': reason
1324
                    },
1325
                )
1326 1
            elif (
1327
                (link.status_reason or link.status != EntityStatus.UP)
1328
                and link_id in self.link_up
1329
            ):
1330 1
                log.info(f"{link} changed status {link.status}, "
1331
                         f"reason: {reason}")
1332 1
                self.link_up.remove(link_id)
1333 1
                event = KytosEvent(
1334
                    name='kytos/topology.link_down',
1335
                    content={
1336
                        'link': link,
1337
                        'reason': reason
1338
                    },
1339
                )
1340
            else:
1341 1
                return
1342 1
        self.controller.buffers.app.put(event)
1343
1344 1
    def notify_metadata_changes(self, obj, action):
1345
        """Send an event to notify about metadata changes."""
1346 1
        if isinstance(obj, Switch):
1347 1
            entity = 'switch'
1348 1
            entities = 'switches'
1349 1
        elif isinstance(obj, Interface):
1350 1
            entity = 'interface'
1351 1
            entities = 'interfaces'
1352 1
        elif isinstance(obj, Link):
1353 1
            entity = 'link'
1354 1
            entities = 'links'
1355
        else:
1356 1
            raise ValueError(
1357
                'Invalid object, supported: Switch, Interface, Link'
1358
            )
1359
1360 1
        name = f'kytos/topology.{entities}.metadata.{action}'
1361 1
        content = {entity: obj, 'metadata': obj.metadata.copy()}
1362 1
        event = KytosEvent(name=name, content=content)
1363 1
        self.controller.buffers.app.put(event)
1364 1
        log.debug(f'Metadata from {obj.id} was {action}.')
1365
1366 1
    @listen_to('kytos/topology.notify_link_up_if_status')
1367 1
    def on_notify_link_up_if_status(self, event):
1368
        """Tries to notify link up and topology changes"""
1369
        link = event.content["link"]
1370
        reason = event.content["reason"]
1371
        self.notify_link_up_if_status(link, reason)
1372
1373 1
    @listen_to('.*.switch.port.created')
1374 1
    def on_notify_port_created(self, event):
1375
        """Notify when a port is created."""
1376
        self.notify_port_created(event)
1377
1378 1
    def notify_port_created(self, event):
1379
        """Notify when a port is created."""
1380 1
        name = 'kytos/topology.port.created'
1381 1
        event = KytosEvent(name=name, content=event.content)
1382 1
        self.controller.buffers.app.put(event)
1383
1384 1
    @staticmethod
1385 1
    def load_interfaces_tags_values(switch: Switch,
1386
                                    interfaces_details: List[dict]) -> None:
1387
        """Load interfaces available tags (vlans)."""
1388 1
        if not interfaces_details:
1389
            return
1390 1
        for interface_details in interfaces_details:
1391 1
            available_tags = interface_details['available_tags']
1392 1
            if not available_tags:
1393
                continue
1394 1
            log.debug(f"Interface id {interface_details['id']} loading "
1395
                      f"{len(available_tags)} "
1396
                      "available tags")
1397 1
            port_number = int(interface_details["id"].split(":")[-1])
1398 1
            interface = switch.interfaces[port_number]
1399 1
            interface.set_available_tags_tag_ranges(
1400
                available_tags,
1401
                interface_details['tag_ranges'],
1402
                interface_details['special_available_tags'],
1403
                interface_details['special_tags'],
1404
            )
1405
1406 1
    @listen_to(
1407
        'topology.interruption.(start|end)',
1408
        pool="dynamic_single"
1409
    )
1410 1
    def on_interruption(self, event: KytosEvent):
1411
        """Deals with service interruptions."""
1412
        with self._links_lock:
1413
            _, _, interrupt_type = event.name.rpartition(".")
1414
            if interrupt_type == "start":
1415
                self.handle_interruption_start(event)
1416
            elif interrupt_type == "end":
1417
                self.handle_interruption_end(event)
1418
1419 1 View Code Duplication
    def handle_interruption_start(self, event: KytosEvent):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
1420
        """Deals with the start of service interruption."""
1421 1
        interrupt_type = event.content['type']
1422 1
        switches = event.content.get('switches', [])
1423 1
        interfaces = event.content.get('interfaces', [])
1424 1
        links = event.content.get('links', [])
1425 1
        log.info(
1426
            'Received interruption start of type \'%s\' '
1427
            'affecting switches %s, interfaces %s, links %s',
1428
            interrupt_type,
1429
            switches,
1430
            interfaces,
1431
            links
1432
        )
1433
        # for switch_id in switches:
1434
        #     pass
1435
        # for interface_id in interfaces:
1436
        #     pass
1437 1
        for link_id in links:
1438 1
            link = self.links.get(link_id)
1439 1
            if link is None:
1440
                log.error(
1441
                    "Invalid link id '%s' for interruption of type '%s;",
1442
                    link_id,
1443
                    interrupt_type
1444
                )
1445
            else:
1446 1
                self.notify_link_status_change(link, interrupt_type)
1447 1
        self.notify_topology_update()
1448
1449 1 View Code Duplication
    def handle_interruption_end(self, event: KytosEvent):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
1450
        """Deals with the end of service interruption."""
1451 1
        interrupt_type = event.content['type']
1452 1
        switches = event.content.get('switches', [])
1453 1
        interfaces = event.content.get('interfaces', [])
1454 1
        links = event.content.get('links', [])
1455 1
        log.info(
1456
            'Received interruption end of type \'%s\' '
1457
            'affecting switches %s, interfaces %s, links %s',
1458
            interrupt_type,
1459
            switches,
1460
            interfaces,
1461
            links
1462
        )
1463
        # for switch_id in switches:
1464
        #     pass
1465
        # for interface_id in interfaces:
1466
        #     pass
1467 1
        for link_id in links:
1468 1
            link = self.links.get(link_id)
1469 1
            if link is None:
1470
                log.error(
1471
                    "Invalid link id '%s' for interruption of type '%s;",
1472
                    link_id,
1473
                    interrupt_type
1474
                )
1475
            else:
1476 1
                self.notify_link_status_change(link, interrupt_type)
1477
        self.notify_topology_update()
1478