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