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