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

build.main.Main.check_non_range()   A

Complexity

Conditions 3

Size

Total Lines 9
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 3

Importance

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