Passed
Pull Request — master (#181)
by
unknown
07:14
created

build.main   F

Complexity

Total Complexity 261

Size/Duplication

Total Lines 1352
Duplicated Lines 10.28 %

Test Coverage

Coverage 91.68%

Importance

Changes 0
Metric Value
eloc 1001
dl 139
loc 1352
ccs 815
cts 889
cp 0.9168
rs 1.596
c 0
b 0
f 0
wmc 261

88 Methods

Rating   Name   Duplication   Size   Complexity  
A Main.enable_switch() 0 15 2
B Main.load_topology() 0 35 5
A Main.get_switches() 0 4 1
A Main.setup() 0 21 1
A Main._get_link_or_create() 0 14 3
A Main._get_link_from_interface() 0 6 3
A Main.on_notify_port_created() 0 4 1
A Main.get_links_from_interfaces() 0 12 5
A Main.notify_port_created() 0 5 1
A Main.disable_switch() 0 18 5
A Main.on_connection_lost() 0 8 1
A Main.get_tag_ranges_by_intf() 0 18 2
A Main.on_interface_link_down() 0 8 1
A Main.on_interruption_end() 0 5 2
A Main.disable_link() 19 19 4
B Main.delete_link() 0 34 8
D Main.enable_interface() 22 39 13
A Main.link_status_hook_link_up_timer() 0 11 5
A Main.notify_link_status() 0 7 1
A Main.add_switch_metadata() 0 14 2
A Main.on_notify_link_up_if_status() 0 6 1
A Main._get_switches_dict() 0 12 3
A Main.get_interfaces() 0 10 3
B Main.delete_interface_metadata() 0 31 5
A Main.add_interface_metadata() 0 21 3
A Main.on_link_liveness_status() 0 11 2
A Main.get_all_tag_ranges() 0 15 3
A Main.on_interfaces_created() 0 4 1
A Main.handle_topo_controller_upsert_switch() 0 3 1
B Main.notify_link_status_change() 0 32 8
A Main.handle_interface_down() 0 15 4
A Main.on_interface_created() 0 8 1
A Main.handle_interface_link_up() 0 10 4
A Main.on_interface_tags() 0 12 4
A Main.on_interface_link_up() 0 8 1
B Main.handle_link_up() 0 22 5
A Main.notify_switch_enabled() 0 5 1
A Main.handle_interface_created() 0 10 2
A Main.delete_tag_range() 0 16 3
A Main.get_interface_metadata() 0 17 3
A Main.on_interruption_start() 0 5 2
A Main.handle_lldp_status_updated() 0 15 4
A Main.delete_link_metadata() 0 20 3
A Main.on_lldp_status_updated() 0 4 1
A Main.shutdown() 0 3 1
A Main.handle_interruption_start() 29 29 3
A Main.notify_topology_update() 0 6 1
A Main.on_interface_deleted() 0 4 1
A Main.notify_link_up_if_status() 0 19 5
B Main.enable_link() 20 20 6
A Main.handle_link_down() 0 15 4
A Main.notify_interface_link_status() 0 12 3
A Main.on_new_switch() 0 8 1
A Main.handle_new_switch() 0 9 2
A Main.execute() 0 3 1
A Main.load_interfaces_tags_values() 0 20 4
B Main._load_switch() 0 44 5
A Main.get_switch_metadata() 0 9 2
A Main._get_metadata() 0 7 2
A Main.handle_connection_lost() 0 7 2
A Main.set_tag_range() 0 21 4
A Main.handle_on_interface_tags() 0 7 1
C Main.disable_interface() 20 35 10
A Main.get_links() 0 7 1
A Main.get_topology() 0 7 1
A Main.handle_interface_link_down() 0 10 4
A Main._get_links_dict() 0 4 1
A Main.handle_interfaces_created() 0 11 3
A Main.handle_link_liveness_status() 0 11 5
A Main.notify_switch_disabled() 0 5 1
B Main.add_links() 0 36 5
A Main.on_link_liveness_disabled() 0 5 1
A Main.handle_interface_deleted() 0 3 1
A Main.set_special_tags() 0 18 3
A Main.on_topo_controller_upsert_switch() 0 4 1
A Main.add_link_metadata() 0 15 2
A Main.notify_metadata_changes() 0 21 4
A Main.notify_switch_links_status() 0 12 5
B Main._load_link() 0 35 6
A Main.delete_switch_metadata() 0 19 3
A Main.get_topo_controller() 0 4 1
A Main._get_topology_dict() 0 4 1
C Main.delete_switch() 0 41 10
A Main.handle_link_liveness_disabled() 0 13 3
A Main.on_add_links() 0 4 1
A Main.get_link_metadata() 0 8 2
A Main._get_topology() 0 3 1
A Main.handle_interruption_end() 29 29 3

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complexity

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

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