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