Passed
Pull Request — master (#173)
by Vinicius
07:23
created

build.main.Main._load_link()   B

Complexity

Conditions 6

Size

Total Lines 35
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 23
CRAP Score 6.0026

Importance

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