Passed
Push — master ( 98d456...fe0679 )
by Vinicius
02:00 queued 13s
created

build.main   F

Complexity

Total Complexity 208

Size/Duplication

Total Lines 1140
Duplicated Lines 10.53 %

Test Coverage

Coverage 91.59%

Importance

Changes 0
Metric Value
eloc 824
dl 120
loc 1140
ccs 675
cts 737
cp 0.9159
rs 1.7759
c 0
b 0
f 0
wmc 208

80 Methods

Rating   Name   Duplication   Size   Complexity  
A Main._get_switches_dict() 0 12 3
A Main._get_links_dict() 0 4 1
A Main._get_link_or_create() 0 14 3
A Main._get_link_from_interface() 0 6 3
A Main._get_topology_dict() 0 4 1
A Main._get_topology() 0 3 1
A Main.on_notify_port_created() 0 4 1
A Main.notify_port_created() 0 5 1
A Main.on_notify_link_up_if_status() 0 6 1
A Main.notify_metadata_changes() 0 21 4
A Main.load_interfaces_available_tags() 0 16 4
A Main.on_interfaces_created() 0 4 1
A Main.on_interface_created() 0 8 1
A Main.handle_interface_created() 0 10 2
A Main.handle_interfaces_created() 0 11 3
A Main.shutdown() 0 3 1
A Main.setup() 0 19 1
A Main.execute() 0 3 1
A Main._get_metadata() 0 7 2
A Main.get_topo_controller() 0 4 1
A Main.disable_switch() 0 15 2
A Main.disable_link() 0 17 3
A Main.enable_switch() 0 15 2
B Main.enable_interface() 31 31 6
B Main.load_topology() 0 35 5
A Main.add_switch_metadata() 0 14 2
A Main.get_interfaces() 0 10 3
B Main.delete_interface_metadata() 0 31 5
A Main.add_interface_metadata() 0 21 3
A Main.get_switches() 0 4 1
A Main.get_interface_metadata() 0 17 3
A Main.enable_link() 0 17 3
B Main._load_switch() 0 44 5
A Main.get_switch_metadata() 0 9 2
B Main.disable_interface() 31 31 6
A Main.get_links() 0 7 1
A Main.get_topology() 0 7 1
B Main._load_link() 0 35 6
A Main.delete_switch_metadata() 0 19 3
A Main.get_link_metadata() 0 8 2
A Main.handle_topo_controller_upsert_switch() 0 3 1
A Main.notify_switch_enabled() 0 5 1
B Main.add_links() 0 36 5
A Main.get_links_from_interfaces() 0 12 5
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.on_link_available_tags() 0 5 2
A Main.link_status_hook_link_up_timer() 0 11 5
A Main.on_link_liveness_status() 0 11 2
B Main.notify_link_status_change() 0 31 8
A Main.handle_interface_down() 0 15 4
A Main.handle_interface_link_up() 0 10 4
A Main.on_interface_link_up() 0 8 1
B Main.handle_link_up() 0 22 5
A Main.on_interruption_start() 0 5 2
A Main.handle_lldp_status_updated() 0 15 4
A Main.delete_link_metadata() 0 20 3
A Main.on_lldp_status_updated() 0 4 1
A Main.handle_interruption_start() 29 29 3
A Main.notify_topology_update() 0 6 1
A Main.on_interface_deleted() 0 4 1
A Main.notify_link_up_if_status() 0 19 5
A Main.handle_link_down() 0 15 4
A Main.notify_interface_link_status() 0 12 3
A Main.on_new_switch() 0 8 1
A Main.handle_new_switch() 0 9 2
A Main.handle_connection_lost() 0 7 2
A Main.handle_on_link_available_tags() 0 15 2
A Main.handle_interface_link_down() 0 10 4
A Main.handle_link_liveness_status() 0 11 5
A Main.notify_switch_disabled() 0 5 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.add_link_metadata() 0 15 2
A Main.notify_switch_links_status() 0 12 5
A Main.handle_link_liveness_disabled() 0 13 3
A Main.on_add_links() 0 4 1
A Main.handle_interruption_end() 29 29 3

How to fix   Duplicated Code    Complexity   

Duplicated Code

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

Common duplication problems, and corresponding solutions are:

Complexity

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

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

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

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