Passed
Pull Request — master (#136)
by
unknown
02:51
created

build.main   F

Complexity

Total Complexity 231

Size/Duplication

Total Lines 1229
Duplicated Lines 8.46 %

Test Coverage

Coverage 91.34%

Importance

Changes 0
Metric Value
eloc 898
dl 104
loc 1229
ccs 749
cts 820
cp 0.9134
rs 1.702
c 0
b 0
f 0
wmc 231

90 Methods

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