Passed
Pull Request — master (#175)
by
unknown
07:19
created

build.main.Main.handle_link_liveness_status()   A

Complexity

Conditions 5

Size

Total Lines 11
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 5

Importance

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