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