Test Failed
Pull Request — master (#181)
by
unknown
03:41 queued 30s
created

build.main.Main.delete_switch()   C

Complexity

Conditions 10

Size

Total Lines 39
Code Lines 34

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 30
CRAP Score 10.0244

Importance

Changes 0
Metric Value
cc 10
eloc 34
nop 2
dl 0
loc 39
ccs 30
cts 32
cp 0.9375
crap 10.0244
rs 5.9999
c 0
b 0
f 0

How to fix   Complexity   

Complexity

Complex classes like build.main.Main.delete_switch() often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

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