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

build.main   F

Complexity

Total Complexity 232

Size/Duplication

Total Lines 1231
Duplicated Lines 8.45 %

Test Coverage

Coverage 91.36%

Importance

Changes 0
Metric Value
eloc 900
dl 104
loc 1231
ccs 751
cts 822
cp 0.9136
rs 1.7
c 0
b 0
f 0
wmc 232

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