Passed
Pull Request — master (#259)
by Aldo
03:51
created

build.main.Main._load_link()   A

Complexity

Conditions 3

Size

Total Lines 17
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 3.0032

Importance

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