Passed
Push — master ( 0615ef...a9f662 )
by Aldo
05:18 queued 02:41
created

build.main.Main.handle_interruption_start()   B

Complexity

Conditions 6

Size

Total Lines 32
Code Lines 25

Duplication

Lines 32
Ratio 100 %

Code Coverage

Tests 16
CRAP Score 6.0073

Importance

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