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