Test Failed
Pull Request — master (#160)
by
unknown
02:40
created

build.main   F

Complexity

Total Complexity 231

Size/Duplication

Total Lines 1234
Duplicated Lines 9.72 %

Test Coverage

Coverage 91.59%

Importance

Changes 0
Metric Value
eloc 900
dl 120
loc 1234
ccs 675
cts 737
cp 0.9159
rs 1.7
c 0
b 0
f 0
wmc 231

84 Methods

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