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