1 | """Main module of kytos/topology Kytos Network Application. |
||
2 | |||
3 | Manage the network topology |
||
4 | """ |
||
5 | 1 | # pylint: disable=wrong-import-order |
|
6 | 1 | ||
7 | import time |
||
8 | 1 | from threading import Lock |
|
9 | 1 | from typing import List |
|
10 | |||
11 | 1 | from flask import jsonify, request |
|
12 | 1 | from werkzeug.exceptions import BadRequest, UnsupportedMediaType |
|
13 | 1 | ||
14 | 1 | from kytos.core import KytosEvent, KytosNApp, log, rest |
|
15 | 1 | from kytos.core.exceptions import KytosLinkCreationError |
|
16 | 1 | from kytos.core.helpers import listen_to |
|
17 | 1 | from kytos.core.interface import Interface |
|
18 | 1 | from kytos.core.link import Link |
|
19 | 1 | from kytos.core.switch import Switch |
|
20 | 1 | from napps.kytos.topology import settings |
|
21 | from napps.kytos.topology.controllers import TopoController |
||
22 | 1 | from napps.kytos.topology.exceptions import RestoreError |
|
23 | from napps.kytos.topology.models import Topology |
||
24 | |||
25 | 1 | DEFAULT_LINK_UP_TIMER = 10 |
|
26 | |||
27 | |||
28 | class Main(KytosNApp): # pylint: disable=too-many-public-methods |
||
29 | """Main class of kytos/topology NApp. |
||
30 | |||
31 | 1 | This class is the entry point for this napp. |
|
32 | """ |
||
33 | 1 | ||
34 | 1 | def setup(self): |
|
35 | 1 | """Initialize the NApp's links list.""" |
|
36 | 1 | self.links = {} |
|
37 | self.store_items = {} |
||
38 | self.intf_available_tags = {} |
||
39 | 1 | self.link_up_timer = getattr(settings, 'LINK_UP_TIMER', |
|
40 | 1 | DEFAULT_LINK_UP_TIMER) |
|
41 | 1 | ||
42 | self._lock = Lock() |
||
43 | 1 | self._links_lock = Lock() |
|
44 | self.topo_controller = self.get_topo_controller() |
||
45 | 1 | self.topo_controller.bootstrap_indexes() |
|
46 | 1 | self.load_topology() |
|
47 | |||
48 | @staticmethod |
||
49 | 1 | def get_topo_controller() -> TopoController: |
|
50 | 1 | """Get TopoController.""" |
|
51 | return TopoController() |
||
52 | |||
53 | def execute(self): |
||
54 | """Execute once when the napp is running.""" |
||
55 | 1 | pass |
|
56 | |||
57 | def shutdown(self): |
||
58 | """Do nothing.""" |
||
59 | 1 | log.info('NApp kytos/topology shutting down.') |
|
60 | |||
61 | @staticmethod |
||
62 | 1 | def _get_metadata(): |
|
63 | 1 | """Return a JSON with metadata.""" |
|
64 | 1 | try: |
|
65 | 1 | metadata = request.get_json() |
|
66 | 1 | content_type = request.content_type |
|
67 | 1 | except BadRequest as err: |
|
68 | 1 | result = 'The request body is not a well-formed JSON.' |
|
69 | raise BadRequest(result) from err |
||
70 | if content_type is None: |
||
71 | 1 | result = 'The request body is empty.' |
|
72 | 1 | raise BadRequest(result) |
|
73 | if metadata is None: |
||
74 | if content_type != 'application/json': |
||
75 | result = ('The content type must be application/json ' |
||
76 | 1 | f'(received {content_type}).') |
|
77 | 1 | else: |
|
78 | 1 | result = 'Metadata is empty.' |
|
79 | raise UnsupportedMediaType(result) |
||
80 | 1 | return metadata |
|
81 | |||
82 | def _get_link_or_create(self, endpoint_a, endpoint_b): |
||
83 | """Get an existing link or create a new one. |
||
84 | |||
85 | Returns: |
||
86 | 1 | Tuple(Link, bool): Link and a boolean whether it has been created. |
|
87 | """ |
||
88 | 1 | new_link = Link(endpoint_a, endpoint_b) |
|
89 | 1 | ||
90 | 1 | for link in self.links.values(): |
|
91 | if new_link == link: |
||
92 | 1 | return (link, False) |
|
93 | 1 | ||
94 | self.links[new_link.id] = new_link |
||
95 | 1 | return (new_link, True) |
|
96 | |||
97 | 1 | def _get_switches_dict(self): |
|
98 | 1 | """Return a dictionary with the known switches.""" |
|
99 | 1 | switches = {'switches': {}} |
|
100 | 1 | for idx, switch in enumerate(self.controller.switches.values()): |
|
101 | switch_data = switch.as_dict() |
||
102 | if not all(key in switch_data['metadata'] |
||
103 | for key in ('lat', 'lng')): |
||
104 | # Switches are initialized somewhere in the ocean |
||
105 | 1 | switch_data['metadata']['lat'] = str(0.0) |
|
106 | 1 | switch_data['metadata']['lng'] = str(-30.0+idx*10.0) |
|
107 | switches['switches'][switch.id] = switch_data |
||
108 | 1 | return switches |
|
109 | |||
110 | 1 | def _get_links_dict(self): |
|
111 | """Return a dictionary with the known links.""" |
||
112 | return {'links': {link.id: link.as_dict() for link in |
||
113 | 1 | self.links.values()}} |
|
114 | |||
115 | 1 | def _get_topology_dict(self): |
|
116 | 1 | """Return a dictionary with the known topology.""" |
|
117 | return {'topology': {**self._get_switches_dict(), |
||
118 | **self._get_links_dict()}} |
||
119 | |||
120 | def _get_topology(self): |
||
121 | """Return an object representing the topology.""" |
||
122 | return Topology(self.controller.switches, self.links) |
||
123 | |||
124 | def _get_link_from_interface(self, interface): |
||
125 | """Return the link of the interface, or None if it does not exist.""" |
||
126 | 1 | for link in self.links.values(): |
|
127 | if interface in (link.endpoint_a, link.endpoint_b): |
||
128 | 1 | return link |
|
129 | return None |
||
130 | 1 | ||
131 | def _load_link(self, link_att): |
||
132 | endpoint_a = link_att['endpoint_a']['id'] |
||
133 | 1 | endpoint_b = link_att['endpoint_b']['id'] |
|
134 | link_str = link_att['id'] |
||
135 | 1 | log.info(f"Loading link: {link_str}") |
|
136 | interface_a = self.controller.get_interface_by_id(endpoint_a) |
||
137 | 1 | interface_b = self.controller.get_interface_by_id(endpoint_b) |
|
138 | |||
139 | 1 | error = f"Fail to load endpoints for link {link_str}. " |
|
140 | 1 | if not interface_a: |
|
141 | 1 | raise RestoreError(f"{error}, endpoint_a {endpoint_a} not found") |
|
142 | 1 | if not interface_b: |
|
143 | raise RestoreError(f"{error}, endpoint_b {endpoint_b} not found") |
||
144 | 1 | ||
145 | with self._links_lock: |
||
146 | link, _ = self._get_link_or_create(interface_a, interface_b) |
||
147 | 1 | ||
148 | 1 | if link_att['enabled']: |
|
149 | 1 | link.enable() |
|
150 | 1 | else: |
|
151 | link.disable() |
||
152 | 1 | ||
153 | 1 | link.extend_metadata(link_att["metadata"]) |
|
154 | 1 | interface_a.update_link(link) |
|
155 | 1 | interface_b.update_link(link) |
|
156 | 1 | interface_a.nni = True |
|
157 | 1 | interface_b.nni = True |
|
158 | 1 | ||
159 | def _load_switch(self, switch_id, switch_att): |
||
160 | 1 | log.info(f'Loading switch dpid: {switch_id}') |
|
161 | 1 | switch = self.controller.get_switch_or_create(switch_id) |
|
162 | 1 | if switch_att['enabled']: |
|
163 | 1 | switch.enable() |
|
164 | 1 | else: |
|
165 | 1 | switch.disable() |
|
166 | 1 | switch.description['manufacturer'] = switch_att.get('manufacturer', '') |
|
167 | 1 | switch.description['hardware'] = switch_att.get('hardware', '') |
|
168 | switch.description['software'] = switch_att.get('software') |
||
169 | 1 | switch.description['serial'] = switch_att.get('serial', '') |
|
170 | 1 | switch.description['data_path'] = switch_att.get('data_path', '') |
|
171 | switch.extend_metadata(switch_att["metadata"]) |
||
172 | 1 | ||
173 | 1 | for iface_id, iface_att in switch_att.get('interfaces', {}).items(): |
|
174 | log.info(f'Loading interface iface_id={iface_id}') |
||
175 | 1 | interface = switch.update_or_create_interface( |
|
176 | port_no=iface_att['port_number'], |
||
177 | 1 | name=iface_att['name'], |
|
178 | 1 | address=iface_att.get('mac', None), |
|
179 | 1 | speed=iface_att.get('speed', None)) |
|
180 | 1 | if iface_att['enabled']: |
|
181 | 1 | interface.enable() |
|
182 | else: |
||
183 | interface.disable() |
||
184 | interface.lldp = iface_att['lldp'] |
||
185 | 1 | interface.extend_metadata(iface_att["metadata"]) |
|
186 | 1 | name = 'kytos/topology.port.created' |
|
187 | event = KytosEvent(name=name, content={ |
||
188 | 'switch': switch_id, |
||
189 | 'port': interface.port_number, |
||
190 | 1 | 'port_description': { |
|
191 | 'alias': interface.name, |
||
192 | 1 | 'mac': interface.address, |
|
193 | 1 | 'state': interface.state |
|
194 | 1 | } |
|
195 | 1 | }) |
|
196 | 1 | self.controller.buffers.app.put(event) |
|
197 | |||
198 | 1 | intf_ids = [v["id"] for v in switch_att.get("interfaces", {}).values()] |
|
199 | 1 | intf_details = self.topo_controller.get_interfaces_details(intf_ids) |
|
200 | 1 | with self._links_lock: |
|
201 | 1 | self.load_interfaces_available_tags(switch, intf_details) |
|
202 | 1 | ||
203 | 1 | # pylint: disable=attribute-defined-outside-init |
|
204 | 1 | def load_topology(self): |
|
205 | """Load network topology from DB.""" |
||
206 | 1 | topology = self.topo_controller.get_topology() |
|
207 | 1 | switches = topology["topology"]["switches"] |
|
208 | 1 | links = topology["topology"]["links"] |
|
209 | |||
210 | failed_switches = {} |
||
211 | log.debug(f"_load_network_status switches={switches}") |
||
212 | for switch_id, switch_att in switches.items(): |
||
213 | 1 | try: |
|
214 | 1 | self._load_switch(switch_id, switch_att) |
|
215 | # pylint: disable=broad-except |
||
216 | 1 | except Exception as err: |
|
217 | 1 | failed_switches[switch_id] = err |
|
218 | 1 | log.error(f'Error loading switch: {err}') |
|
219 | 1 | ||
220 | 1 | failed_links = {} |
|
221 | log.debug(f"_load_network_status links={links}") |
||
222 | for link_id, link_att in links.items(): |
||
223 | try: |
||
224 | self._load_link(link_att) |
||
225 | # pylint: disable=broad-except |
||
226 | except Exception as err: |
||
227 | failed_links[link_id] = err |
||
228 | log.error(f'Error loading link {link_id}: {err}') |
||
229 | 1 | ||
230 | name = 'kytos/topology.topology_loaded' |
||
231 | event = KytosEvent( |
||
232 | 1 | name=name, |
|
233 | content={ |
||
234 | 1 | 'topology': self._get_topology(), |
|
235 | 1 | 'failed_switches': failed_switches, |
|
236 | 1 | 'failed_links': failed_links |
|
237 | 1 | }) |
|
238 | 1 | self.controller.buffers.app.put(event) |
|
239 | |||
240 | 1 | @rest('v3/') |
|
241 | 1 | def get_topology(self): |
|
242 | 1 | """Return the latest known topology. |
|
243 | |||
244 | 1 | This topology is updated when there are network events. |
|
245 | 1 | """ |
|
246 | return jsonify(self._get_topology_dict()) |
||
247 | 1 | ||
248 | 1 | # Switch related methods |
|
249 | 1 | @rest('v3/switches') |
|
250 | 1 | def get_switches(self): |
|
251 | 1 | """Return a json with all the switches in the topology.""" |
|
252 | return jsonify(self._get_switches_dict()) |
||
253 | 1 | ||
254 | 1 | @rest('v3/switches/<dpid>/enable', methods=['POST']) |
|
255 | 1 | def enable_switch(self, dpid): |
|
256 | """Administratively enable a switch in the topology.""" |
||
257 | 1 | try: |
|
258 | 1 | switch = self.controller.switches[dpid] |
|
259 | 1 | self.topo_controller.enable_switch(dpid) |
|
260 | 1 | switch.enable() |
|
261 | 1 | except KeyError: |
|
262 | return jsonify("Switch not found"), 404 |
||
263 | 1 | ||
264 | 1 | self.notify_switch_enabled(dpid) |
|
265 | 1 | self.notify_topology_update() |
|
266 | return jsonify("Operation successful"), 201 |
||
267 | 1 | ||
268 | 1 | @rest('v3/switches/<dpid>/disable', methods=['POST']) |
|
269 | def disable_switch(self, dpid): |
||
270 | """Administratively disable a switch in the topology.""" |
||
271 | try: |
||
272 | switch = self.controller.switches[dpid] |
||
273 | self.topo_controller.disable_switch(dpid) |
||
274 | switch.disable() |
||
275 | 1 | except KeyError: |
|
276 | return jsonify("Switch not found"), 404 |
||
277 | 1 | ||
278 | self.notify_switch_disabled(dpid) |
||
279 | self.notify_topology_update() |
||
280 | return jsonify("Operation successful"), 201 |
||
281 | |||
282 | @rest('v3/switches/<dpid>/metadata') |
||
283 | 1 | def get_switch_metadata(self, dpid): |
|
284 | """Get metadata from a switch.""" |
||
285 | try: |
||
286 | 1 | return jsonify({"metadata": |
|
287 | self.controller.switches[dpid].metadata}), 200 |
||
288 | except KeyError: |
||
289 | return jsonify("Switch not found"), 404 |
||
290 | |||
291 | 1 | @rest('v3/switches/<dpid>/metadata', methods=['POST']) |
|
292 | def add_switch_metadata(self, dpid): |
||
293 | """Add metadata to a switch.""" |
||
294 | 1 | metadata = self._get_metadata() |
|
295 | 1 | ||
296 | 1 | try: |
|
297 | 1 | switch = self.controller.switches[dpid] |
|
298 | except KeyError: |
||
299 | 1 | return jsonify("Switch not found"), 404 |
|
300 | |||
301 | 1 | self.topo_controller.add_switch_metadata(dpid, metadata) |
|
302 | 1 | switch.extend_metadata(metadata) |
|
303 | 1 | self.notify_metadata_changes(switch, 'added') |
|
304 | 1 | return jsonify("Operation successful"), 201 |
|
305 | |||
306 | 1 | @rest('v3/switches/<dpid>/metadata/<key>', methods=['DELETE']) |
|
307 | def delete_switch_metadata(self, dpid, key): |
||
308 | """Delete metadata from a switch.""" |
||
309 | 1 | try: |
|
310 | 1 | switch = self.controller.switches[dpid] |
|
311 | 1 | except KeyError: |
|
312 | 1 | return jsonify("Switch not found"), 404 |
|
313 | |||
314 | 1 | try: |
|
315 | _ = switch.metadata[key] |
||
316 | 1 | except KeyError: |
|
317 | 1 | return jsonify("Metadata not found"), 404 |
|
318 | 1 | ||
319 | 1 | self.topo_controller.delete_switch_metadata_key(dpid, key) |
|
320 | switch.remove_metadata(key) |
||
321 | 1 | self.notify_metadata_changes(switch, 'removed') |
|
322 | return jsonify("Operation successful"), 200 |
||
323 | |||
324 | 1 | # Interface related methods |
|
325 | 1 | @rest('v3/interfaces') |
|
326 | def get_interfaces(self): |
||
327 | 1 | """Return a json with all the interfaces in the topology.""" |
|
328 | 1 | interfaces = {} |
|
329 | switches = self._get_switches_dict() |
||
330 | 1 | for switch in switches['switches'].values(): |
|
331 | for interface_id, interface in switch['interfaces'].items(): |
||
332 | interfaces[interface_id] = interface |
||
333 | 1 | ||
334 | return jsonify({'interfaces': interfaces}) |
||
335 | 1 | ||
336 | 1 | View Code Duplication | @rest('v3/interfaces/switch/<dpid>/enable', methods=['POST']) |
0 ignored issues
–
show
Duplication
introduced
by
![]() |
|||
337 | 1 | @rest('v3/interfaces/<interface_enable_id>/enable', methods=['POST']) |
|
338 | 1 | def enable_interface(self, interface_enable_id=None, dpid=None): |
|
339 | """Administratively enable interfaces in the topology.""" |
||
340 | 1 | if dpid is None: |
|
341 | 1 | dpid = ":".join(interface_enable_id.split(":")[:-1]) |
|
342 | 1 | try: |
|
343 | switch = self.controller.switches[dpid] |
||
344 | 1 | except KeyError as exc: |
|
345 | return jsonify(f"Switch not found: {exc}"), 404 |
||
346 | |||
347 | 1 | if interface_enable_id: |
|
348 | 1 | interface_number = int(interface_enable_id.split(":")[-1]) |
|
349 | 1 | ||
350 | 1 | try: |
|
351 | interface = switch.interfaces[interface_number] |
||
352 | 1 | self.topo_controller.enable_interface(interface.id) |
|
353 | 1 | interface.enable() |
|
354 | 1 | except KeyError: |
|
355 | msg = f"Switch {dpid} interface {interface_number} not found" |
||
356 | return jsonify(msg), 404 |
||
357 | 1 | else: |
|
358 | for interface in switch.interfaces.values(): |
||
359 | interface.enable() |
||
360 | self.topo_controller.upsert_switch(switch.id, switch.as_dict()) |
||
361 | self.notify_topology_update() |
||
362 | return jsonify("Operation successful"), 200 |
||
363 | |||
364 | View Code Duplication | @rest('v3/interfaces/switch/<dpid>/disable', methods=['POST']) |
|
0 ignored issues
–
show
|
|||
365 | @rest('v3/interfaces/<interface_disable_id>/disable', methods=['POST']) |
||
366 | def disable_interface(self, interface_disable_id=None, dpid=None): |
||
367 | """Administratively disable interfaces in the topology.""" |
||
368 | 1 | if dpid is None: |
|
369 | 1 | dpid = ":".join(interface_disable_id.split(":")[:-1]) |
|
370 | 1 | try: |
|
371 | switch = self.controller.switches[dpid] |
||
372 | 1 | except KeyError as exc: |
|
373 | 1 | return jsonify(f"Switch not found: {exc}"), 404 |
|
374 | 1 | ||
375 | 1 | if interface_disable_id: |
|
376 | 1 | interface_number = int(interface_disable_id.split(":")[-1]) |
|
377 | 1 | ||
378 | try: |
||
379 | 1 | interface = switch.interfaces[interface_number] |
|
380 | 1 | self.topo_controller.disable_interface(interface.id) |
|
381 | interface.disable() |
||
382 | 1 | except KeyError: |
|
383 | 1 | msg = f"Switch {dpid} interface {interface_number} not found" |
|
384 | 1 | return jsonify(msg), 404 |
|
385 | 1 | else: |
|
386 | 1 | for interface in switch.interfaces.values(): |
|
387 | interface.disable() |
||
388 | 1 | self.topo_controller.upsert_switch(switch.id, switch.as_dict()) |
|
389 | 1 | self.notify_topology_update() |
|
390 | 1 | return jsonify("Operation successful"), 200 |
|
391 | 1 | ||
392 | 1 | @rest('v3/interfaces/<interface_id>/metadata') |
|
393 | 1 | def get_interface_metadata(self, interface_id): |
|
394 | """Get metadata from an interface.""" |
||
395 | 1 | switch_id = ":".join(interface_id.split(":")[:-1]) |
|
396 | 1 | interface_number = int(interface_id.split(":")[-1]) |
|
397 | 1 | try: |
|
398 | switch = self.controller.switches[switch_id] |
||
399 | 1 | except KeyError: |
|
400 | 1 | return jsonify("Switch not found"), 404 |
|
401 | 1 | ||
402 | 1 | try: |
|
403 | 1 | interface = switch.interfaces[interface_number] |
|
404 | 1 | except KeyError: |
|
405 | return jsonify("Interface not found"), 404 |
||
406 | 1 | ||
407 | 1 | return jsonify({"metadata": interface.metadata}), 200 |
|
408 | |||
409 | 1 | @rest('v3/interfaces/<interface_id>/metadata', methods=['POST']) |
|
410 | 1 | def add_interface_metadata(self, interface_id): |
|
411 | 1 | """Add metadata to an interface.""" |
|
412 | 1 | metadata = self._get_metadata() |
|
413 | 1 | switch_id = ":".join(interface_id.split(":")[:-1]) |
|
414 | interface_number = int(interface_id.split(":")[-1]) |
||
415 | 1 | try: |
|
416 | 1 | switch = self.controller.switches[switch_id] |
|
417 | 1 | except KeyError: |
|
418 | 1 | return jsonify("Switch not found"), 404 |
|
419 | 1 | ||
420 | 1 | try: |
|
421 | interface = switch.interfaces[interface_number] |
||
422 | 1 | self.topo_controller.add_interface_metadata(interface.id, metadata) |
|
423 | except KeyError: |
||
424 | return jsonify("Interface not found"), 404 |
||
425 | 1 | ||
426 | 1 | interface.extend_metadata(metadata) |
|
427 | 1 | self.notify_metadata_changes(interface, 'added') |
|
428 | 1 | return jsonify("Operation successful"), 201 |
|
429 | 1 | ||
430 | 1 | @rest('v3/interfaces/<interface_id>/metadata/<key>', methods=['DELETE']) |
|
431 | def delete_interface_metadata(self, interface_id, key): |
||
432 | 1 | """Delete metadata from an interface.""" |
|
433 | 1 | switch_id = ":".join(interface_id.split(":")[:-1]) |
|
434 | 1 | interface_number = int(interface_id.split(":")[-1]) |
|
435 | 1 | ||
436 | try: |
||
437 | 1 | switch = self.controller.switches[switch_id] |
|
438 | except KeyError: |
||
439 | 1 | return jsonify("Switch not found"), 404 |
|
440 | |||
441 | try: |
||
442 | 1 | interface = switch.interfaces[interface_number] |
|
443 | 1 | except KeyError: |
|
444 | 1 | return jsonify("Interface not found"), 404 |
|
445 | 1 | ||
446 | 1 | try: |
|
447 | 1 | _ = interface.metadata[key] |
|
448 | 1 | except KeyError: |
|
449 | return jsonify("Metadata not found"), 404 |
||
450 | 1 | ||
451 | 1 | self.topo_controller.delete_interface_metadata_key(interface.id, key) |
|
452 | 1 | interface.remove_metadata(key) |
|
453 | 1 | self.notify_metadata_changes(interface, 'removed') |
|
454 | return jsonify("Operation successful"), 200 |
||
455 | 1 | ||
456 | 1 | # Link related methods |
|
457 | 1 | @rest('v3/links') |
|
458 | def get_links(self): |
||
459 | 1 | """Return a json with all the links in the topology. |
|
460 | |||
461 | Links are connections between interfaces. |
||
462 | 1 | """ |
|
463 | 1 | return jsonify(self._get_links_dict()), 200 |
|
464 | |||
465 | 1 | @rest('v3/links/<link_id>/enable', methods=['POST']) |
|
466 | 1 | def enable_link(self, link_id): |
|
467 | 1 | """Administratively enable a link in the topology.""" |
|
468 | 1 | try: |
|
469 | with self._links_lock: |
||
470 | 1 | link = self.links[link_id] |
|
471 | 1 | self.topo_controller.enable_link(link_id) |
|
472 | 1 | link.enable() |
|
473 | 1 | except KeyError: |
|
474 | return jsonify("Link not found"), 404 |
||
475 | 1 | self.notify_link_status_change( |
|
476 | 1 | self.links[link_id], |
|
477 | reason='link enabled' |
||
478 | 1 | ) |
|
479 | 1 | self.notify_topology_update() |
|
480 | return jsonify("Operation successful"), 201 |
||
481 | |||
482 | 1 | @rest('v3/links/<link_id>/disable', methods=['POST']) |
|
483 | def disable_link(self, link_id): |
||
484 | """Administratively disable a link in the topology.""" |
||
485 | try: |
||
486 | with self._links_lock: |
||
487 | link = self.links[link_id] |
||
488 | self.topo_controller.disable_link(link_id) |
||
489 | link.disable() |
||
490 | 1 | except KeyError: |
|
491 | return jsonify("Link not found"), 404 |
||
492 | self.notify_link_status_change( |
||
493 | 1 | self.links[link_id], |
|
494 | 1 | reason='link disabled' |
|
495 | 1 | ) |
|
496 | 1 | self.notify_topology_update() |
|
497 | 1 | return jsonify("Operation successful"), 201 |
|
498 | 1 | ||
499 | 1 | @rest('v3/links/<link_id>/metadata') |
|
500 | def get_link_metadata(self, link_id): |
||
501 | """Get metadata from a link.""" |
||
502 | try: |
||
503 | 1 | return jsonify({"metadata": self.links[link_id].metadata}), 200 |
|
504 | 1 | except KeyError: |
|
505 | return jsonify("Link not found"), 404 |
||
506 | 1 | ||
507 | @rest('v3/links/<link_id>/metadata', methods=['POST']) |
||
508 | def add_link_metadata(self, link_id): |
||
509 | 1 | """Add metadata to a link.""" |
|
510 | 1 | metadata = self._get_metadata() |
|
511 | 1 | try: |
|
512 | 1 | link = self.links[link_id] |
|
513 | 1 | except KeyError: |
|
514 | 1 | return jsonify("Link not found"), 404 |
|
515 | 1 | ||
516 | self.topo_controller.add_link_metadata(link_id, metadata) |
||
517 | link.extend_metadata(metadata) |
||
518 | self.notify_metadata_changes(link, 'added') |
||
519 | 1 | return jsonify("Operation successful"), 201 |
|
520 | 1 | ||
521 | @rest('v3/links/<link_id>/metadata/<key>', methods=['DELETE']) |
||
522 | 1 | def delete_link_metadata(self, link_id, key): |
|
523 | """Delete metadata from a link.""" |
||
524 | try: |
||
525 | 1 | link = self.links[link_id] |
|
526 | 1 | except KeyError: |
|
527 | 1 | return jsonify("Link not found"), 404 |
|
528 | 1 | ||
529 | try: |
||
530 | 1 | _ = link.metadata[key] |
|
531 | except KeyError: |
||
532 | return jsonify("Metadata not found"), 404 |
||
533 | 1 | ||
534 | 1 | self.topo_controller.delete_link_metadata_key(link.id, key) |
|
535 | 1 | link.remove_metadata(key) |
|
536 | 1 | self.notify_metadata_changes(link, 'removed') |
|
537 | 1 | return jsonify("Operation successful"), 200 |
|
538 | |||
539 | 1 | @listen_to("kytos/.*.link_available_tags") |
|
540 | 1 | def on_link_available_tags(self, event): |
|
541 | 1 | """Handle on_link_available_tags.""" |
|
542 | with self._links_lock: |
||
543 | 1 | self.handle_on_link_available_tags(event.content.get("link")) |
|
544 | |||
545 | def handle_on_link_available_tags(self, link): |
||
546 | 1 | """Handle on_link_available_tags.""" |
|
547 | 1 | if link.id not in self.links: |
|
548 | 1 | return |
|
549 | 1 | endpoint_a = self.links[link.id].endpoint_a |
|
550 | endpoint_b = self.links[link.id].endpoint_b |
||
551 | 1 | values_a = [tag.value for tag in endpoint_a.available_tags] |
|
552 | 1 | values_b = [tag.value for tag in endpoint_b.available_tags] |
|
553 | ids_details = [ |
||
554 | 1 | (endpoint_a.id, {"_id": endpoint_a.id, |
|
555 | 1 | "available_vlans": values_a}), |
|
556 | (endpoint_b.id, {"_id": endpoint_b.id, |
||
557 | 1 | "available_vlans": values_b}) |
|
558 | ] |
||
559 | self.topo_controller.bulk_upsert_interface_details(ids_details) |
||
560 | |||
561 | @listen_to('.*.switch.(new|reconnected)') |
||
562 | def on_new_switch(self, event): |
||
563 | 1 | """Create a new Device on the Topology. |
|
564 | |||
565 | Handle the event of a new created switch and update the topology with |
||
566 | this new device. Also notify if the switch is enabled. |
||
567 | """ |
||
568 | self.handle_new_switch(event) |
||
569 | |||
570 | def handle_new_switch(self, event): |
||
571 | """Create a new Device on the Topology.""" |
||
572 | switch = event.content['switch'] |
||
573 | switch.activate() |
||
574 | self.topo_controller.upsert_switch(switch.id, switch.as_dict()) |
||
575 | log.debug('Switch %s added to the Topology.', switch.id) |
||
576 | 1 | self.notify_topology_update() |
|
577 | if switch.is_enabled(): |
||
578 | self.notify_switch_enabled(switch.id) |
||
579 | |||
580 | @listen_to('.*.connection.lost') |
||
581 | def on_connection_lost(self, event): |
||
582 | """Remove a Device from the topology. |
||
583 | |||
584 | Remove the disconnected Device and every link that has one of its |
||
585 | 1 | interfaces. |
|
586 | """ |
||
587 | 1 | self.handle_connection_lost(event) |
|
588 | 1 | ||
589 | 1 | def handle_connection_lost(self, event): |
|
590 | 1 | """Remove a Device from the topology.""" |
|
591 | 1 | switch = event.content['source'].switch |
|
592 | 1 | if switch: |
|
593 | 1 | switch.deactivate() |
|
594 | self.topo_controller.deactivate_switch(switch.id) |
||
595 | 1 | log.debug('Switch %s removed from the Topology.', switch.id) |
|
596 | self.notify_topology_update() |
||
597 | |||
598 | def handle_interfaces_created(self, event): |
||
599 | """Update the topology based on the interfaces created.""" |
||
600 | interfaces = event.content["interfaces"] |
||
601 | if not interfaces: |
||
602 | return |
||
603 | switch = interfaces[0].switch |
||
604 | 1 | self.topo_controller.upsert_switch(switch.id, switch.as_dict()) |
|
605 | name = "kytos/topology.switch.interface.created" |
||
606 | 1 | for interface in interfaces: |
|
607 | 1 | event = KytosEvent(name=name, content={'interface': interface}) |
|
608 | 1 | self.controller.buffers.app.put(event) |
|
609 | 1 | ||
610 | 1 | def handle_interface_created(self, event): |
|
611 | """Update the topology based on an interface created event. |
||
612 | 1 | ||
613 | It's handled as a link_up in case a switch send a |
||
614 | created event again and it can be belong to a link. |
||
615 | """ |
||
616 | interface = event.content['interface'] |
||
617 | self.handle_interface_link_up(interface) |
||
618 | 1 | ||
619 | @listen_to('.*.topology.switch.interface.created') |
||
620 | 1 | def on_interface_created(self, event): |
|
621 | 1 | """Handle individual interface create event. |
|
622 | 1 | ||
623 | 1 | It's handled as a link_up in case a switch send a |
|
624 | 1 | created event it can belong to an existign link. |
|
625 | 1 | """ |
|
626 | self.handle_interface_created(event) |
||
627 | |||
628 | @listen_to('.*.switch.interfaces.created') |
||
629 | def on_interfaces_created(self, event): |
||
630 | 1 | """Update the topology based on a list of created interfaces.""" |
|
631 | 1 | self.handle_interfaces_created(event) |
|
632 | |||
633 | 1 | def handle_interface_down(self, event): |
|
634 | """Update the topology based on a Port Modify event. |
||
635 | |||
636 | The event notifies that an interface was changed to 'down'. |
||
637 | """ |
||
638 | interface = event.content['interface'] |
||
639 | interface.deactivate() |
||
640 | self.topo_controller.deactivate_interface(interface.id) |
||
641 | self.handle_interface_link_down(interface) |
||
642 | 1 | ||
643 | @listen_to('.*.switch.interface.deleted') |
||
644 | def on_interface_deleted(self, event): |
||
645 | """Update the topology based on a Port Delete event.""" |
||
646 | self.handle_interface_deleted(event) |
||
647 | 1 | ||
648 | 1 | def handle_interface_deleted(self, event): |
|
649 | 1 | """Update the topology based on a Port Delete event.""" |
|
650 | self.handle_interface_down(event) |
||
651 | 1 | ||
652 | @listen_to('.*.switch.interface.link_up') |
||
653 | def on_interface_link_up(self, event): |
||
654 | """Update the topology based on a Port Modify event. |
||
655 | |||
656 | 1 | The event notifies that an interface's link was changed to 'up'. |
|
657 | """ |
||
658 | 1 | interface = event.content['interface'] |
|
659 | self.handle_interface_link_up(interface) |
||
660 | 1 | ||
661 | def handle_interface_link_up(self, interface): |
||
662 | """Update the topology based on a Port Modify event.""" |
||
663 | self.handle_link_up(interface) |
||
664 | |||
665 | @listen_to('kytos/maintenance.end_switch') |
||
666 | def on_switch_maintenance_end(self, event): |
||
667 | """Handle the end of the maintenance of a switch.""" |
||
668 | self.handle_switch_maintenance_end(event) |
||
669 | 1 | ||
670 | def handle_switch_maintenance_end(self, event): |
||
671 | 1 | """Handle the end of the maintenance of a switch.""" |
|
672 | switches = event.content['switches'] |
||
673 | 1 | for switch in switches: |
|
674 | switch.enable() |
||
675 | switch.activate() |
||
676 | for interface in switch.interfaces.values(): |
||
677 | interface.enable() |
||
678 | 1 | self.handle_link_up(interface) |
|
679 | |||
680 | 1 | def handle_link_up(self, interface): |
|
681 | 1 | """Notify a link is up.""" |
|
682 | 1 | interface.activate() |
|
683 | 1 | self.topo_controller.activate_interface(interface.id) |
|
684 | 1 | self.notify_topology_update() |
|
685 | 1 | with self._links_lock: |
|
686 | 1 | link = self._get_link_from_interface(interface) |
|
687 | if not link: |
||
688 | 1 | return |
|
689 | if link.endpoint_a == interface: |
||
690 | 1 | other_interface = link.endpoint_b |
|
691 | 1 | else: |
|
692 | 1 | other_interface = link.endpoint_a |
|
693 | 1 | if other_interface.is_active() is False: |
|
694 | 1 | return |
|
695 | if link.is_active() is False: |
||
696 | 1 | link.update_metadata('last_status_change', time.time()) |
|
697 | 1 | link.activate() |
|
698 | |||
699 | 1 | # As each run of this method uses a different thread, |
|
700 | 1 | # there is no risk this sleep will lock the NApp. |
|
701 | 1 | time.sleep(self.link_up_timer) |
|
702 | 1 | ||
703 | 1 | last_status_change = link.get_metadata('last_status_change') |
|
704 | 1 | now = time.time() |
|
705 | if link.is_active() and \ |
||
706 | now - last_status_change >= self.link_up_timer: |
||
707 | link.update_metadata('last_status_is_active', True) |
||
708 | 1 | self.topo_controller._update_link( |
|
709 | link.id, |
||
710 | 1 | { |
|
711 | 1 | "$set": { |
|
712 | 1 | "metadata.last_status_change": last_status_change, |
|
713 | "metadata.last_status_is_active": True, |
||
714 | 1 | "active": True, |
|
715 | 1 | } |
|
716 | 1 | }, |
|
717 | ) |
||
718 | 1 | self.notify_topology_update() |
|
719 | 1 | self.notify_link_status_change(link, reason='link up') |
|
720 | 1 | else: |
|
721 | 1 | last_status_change = time.time() |
|
722 | 1 | metadata = {'last_status_change': last_status_change, |
|
723 | 'last_status_is_active': True} |
||
724 | 1 | link.extend_metadata(metadata) |
|
725 | self.topo_controller.add_link_metadata(link.id, metadata) |
||
726 | self.topo_controller._update_link( |
||
727 | link.id, |
||
728 | { |
||
729 | "$set": { |
||
730 | "metadata.last_status_change": last_status_change, |
||
731 | "metadata.last_status_is_active": True, |
||
732 | "active": True, |
||
733 | 1 | } |
|
734 | }, |
||
735 | 1 | ) |
|
736 | self.notify_topology_update() |
||
737 | 1 | self.notify_link_status_change(link, reason='link up') |
|
738 | |||
739 | @listen_to('.*.switch.interface.link_down') |
||
740 | def on_interface_link_down(self, event): |
||
741 | """Update the topology based on a Port Modify event. |
||
742 | 1 | ||
743 | The event notifies that an interface's link was changed to 'down'. |
||
744 | 1 | """ |
|
745 | 1 | interface = event.content['interface'] |
|
746 | 1 | self.handle_interface_link_down(interface) |
|
747 | 1 | ||
748 | 1 | def handle_interface_link_down(self, interface): |
|
749 | 1 | """Update the topology based on an interface.""" |
|
750 | 1 | self.handle_link_down(interface) |
|
751 | 1 | ||
752 | @listen_to('kytos/maintenance.start_switch') |
||
753 | 1 | def on_switch_maintenance_start(self, event): |
|
754 | """Handle the start of the maintenance of a switch.""" |
||
755 | 1 | self.handle_switch_maintenance_start(event) |
|
756 | 1 | ||
757 | 1 | def handle_switch_maintenance_start(self, event): |
|
758 | 1 | """Handle the start of the maintenance of a switch.""" |
|
759 | 1 | switches = event.content['switches'] |
|
760 | 1 | for switch in switches: |
|
761 | 1 | switch.disable() |
|
762 | 1 | switch.deactivate() |
|
763 | 1 | for interface in switch.interfaces.values(): |
|
764 | 1 | interface.disable() |
|
765 | 1 | if interface.is_active(): |
|
766 | 1 | self.handle_link_down(interface) |
|
767 | 1 | ||
768 | 1 | def handle_link_down(self, interface): |
|
769 | 1 | """Notify a link is down.""" |
|
770 | link = self._get_link_from_interface(interface) |
||
771 | 1 | if link and link.is_active(): |
|
772 | link.deactivate() |
||
773 | last_status_change = time.time() |
||
774 | metadata = { |
||
775 | "last_status_change": last_status_change, |
||
776 | 1 | "last_status_is_active": False, |
|
777 | } |
||
778 | 1 | link.extend_metadata(metadata) |
|
779 | 1 | update_expr = { |
|
780 | "$set": { |
||
781 | 1 | "active": False, |
|
782 | 1 | "metadata.last_status_change": last_status_change, |
|
783 | 1 | "metadata.last_status_is_active": False, |
|
784 | } |
||
785 | 1 | } |
|
786 | 1 | self.topo_controller._update_link(link.id, update_expr) |
|
787 | self.notify_link_status_change(link, reason="link down") |
||
788 | 1 | if link and not link.is_active(): |
|
789 | 1 | with self._links_lock: |
|
790 | last_status = link.get_metadata('last_status_is_active') |
||
791 | 1 | last_status_change = link.get_metadata('last_status_change') |
|
792 | 1 | metadata = { |
|
793 | "last_status_change": last_status_change, |
||
794 | "last_status_is_active": last_status, |
||
795 | } |
||
796 | if last_status: |
||
797 | link.extend_metadata(metadata) |
||
798 | 1 | update_expr = { |
|
799 | 1 | "$set": { |
|
800 | 1 | "active": False, |
|
801 | 1 | "metadata.last_status_change": last_status_change, |
|
802 | 1 | "metadata.last_status_is_active": last_status, |
|
803 | } |
||
804 | } |
||
805 | self.topo_controller._update_link(link.id, update_expr) |
||
806 | self.notify_link_status_change(link, reason='link down') |
||
807 | interface.deactivate() |
||
808 | self.topo_controller.deactivate_interface(interface.id) |
||
809 | self.notify_topology_update() |
||
810 | |||
811 | @listen_to('.*.interface.is.nni') |
||
812 | def on_add_links(self, event): |
||
813 | """Update the topology with links related to the NNI interfaces.""" |
||
814 | self.add_links(event) |
||
815 | |||
816 | def add_links(self, event): |
||
817 | """Update the topology with links related to the NNI interfaces.""" |
||
818 | interface_a = event.content['interface_a'] |
||
819 | interface_b = event.content['interface_b'] |
||
820 | |||
821 | 1 | try: |
|
822 | with self._links_lock: |
||
823 | link, created = self._get_link_or_create(interface_a, |
||
824 | interface_b) |
||
825 | interface_a.update_link(link) |
||
826 | interface_b.update_link(link) |
||
827 | |||
828 | link.endpoint_a = interface_a |
||
829 | link.endpoint_b = interface_b |
||
830 | |||
831 | 1 | interface_a.nni = True |
|
832 | interface_b.nni = True |
||
833 | 1 | ||
834 | except KytosLinkCreationError as err: |
||
835 | 1 | log.error(f'Error creating link: {err}.') |
|
836 | return |
||
837 | 1 | ||
838 | 1 | if created: |
|
839 | 1 | link.update_metadata('last_status_is_active', True) |
|
840 | 1 | self.notify_link_status_change(link, reason='link up') |
|
841 | 1 | self.notify_topology_update() |
|
842 | self.topo_controller.upsert_link(link.id, link.as_dict()) |
||
843 | 1 | ||
844 | @listen_to('.*.of_lldp.network_status.updated') |
||
845 | 1 | def on_lldp_status_updated(self, event): |
|
846 | 1 | """Handle of_lldp.network_status.updated from of_lldp.""" |
|
847 | 1 | self.handle_lldp_status_updated(event) |
|
848 | |||
849 | 1 | def handle_lldp_status_updated(self, event) -> None: |
|
850 | """Handle .*.network_status.updated events from of_lldp.""" |
||
851 | 1 | content = event.content |
|
852 | 1 | interface_ids = content["interface_ids"] |
|
853 | 1 | for interface_id in interface_ids: |
|
854 | if content["state"] == "disabled": |
||
855 | 1 | self.topo_controller.disable_interface_lldp(interface_id) |
|
856 | elif content["state"] == "enabled": |
||
857 | 1 | self.topo_controller.enable_interface_lldp(interface_id) |
|
858 | 1 | ||
859 | def notify_switch_enabled(self, dpid): |
||
860 | 1 | """Send an event to notify that a switch is enabled.""" |
|
861 | name = 'kytos/topology.switch.enabled' |
||
862 | 1 | event = KytosEvent(name=name, content={'dpid': dpid}) |
|
863 | self.controller.buffers.app.put(event) |
||
864 | 1 | ||
865 | 1 | def notify_switch_disabled(self, dpid): |
|
866 | 1 | """Send an event to notify that a switch is disabled.""" |
|
867 | name = 'kytos/topology.switch.disabled' |
||
868 | event = KytosEvent(name=name, content={'dpid': dpid}) |
||
869 | 1 | self.controller.buffers.app.put(event) |
|
870 | |||
871 | def notify_topology_update(self): |
||
872 | """Send an event to notify about updates on the topology.""" |
||
873 | name = 'kytos/topology.updated' |
||
874 | event = KytosEvent(name=name, content={'topology': |
||
875 | 1 | self._get_topology()}) |
|
876 | self.controller.buffers.app.put(event) |
||
877 | 1 | ||
878 | def notify_link_status_change(self, link, reason='not given'): |
||
879 | 1 | """Send an event to notify about a status change on a link.""" |
|
880 | 1 | name = 'kytos/topology.' |
|
881 | 1 | if link.is_active() and link.is_enabled(): |
|
882 | 1 | status = 'link_up' |
|
883 | 1 | else: |
|
884 | 1 | status = 'link_down' |
|
885 | 1 | event = KytosEvent( |
|
886 | 1 | name=name+status, |
|
887 | 1 | content={ |
|
888 | 'link': link, |
||
889 | 1 | 'reason': reason |
|
890 | }) |
||
891 | self.controller.buffers.app.put(event) |
||
892 | |||
893 | 1 | def notify_metadata_changes(self, obj, action): |
|
894 | """Send an event to notify about metadata changes.""" |
||
895 | 1 | if isinstance(obj, Switch): |
|
896 | 1 | entity = 'switch' |
|
897 | entities = 'switches' |
||
898 | 1 | elif isinstance(obj, Interface): |
|
899 | 1 | entity = 'interface' |
|
900 | entities = 'interfaces' |
||
901 | 1 | elif isinstance(obj, Link): |
|
902 | entity = 'link' |
||
903 | entities = 'links' |
||
904 | else: |
||
905 | raise ValueError( |
||
906 | 1 | 'Invalid object, supported: Switch, Interface, Link' |
|
907 | ) |
||
908 | 1 | ||
909 | 1 | name = f'kytos/topology.{entities}.metadata.{action}' |
|
910 | 1 | event = KytosEvent(name=name, content={entity: obj, |
|
911 | 'metadata': obj.metadata}) |
||
912 | 1 | self.controller.buffers.app.put(event) |
|
913 | log.debug(f'Metadata from {obj.id} was {action}.') |
||
914 | 1 | ||
915 | 1 | @listen_to('.*.switch.port.created') |
|
916 | 1 | def on_notify_port_created(self, event): |
|
917 | """Notify when a port is created.""" |
||
918 | 1 | self.notify_port_created(event) |
|
919 | 1 | ||
920 | def notify_port_created(self, event): |
||
921 | """Notify when a port is created.""" |
||
922 | name = 'kytos/topology.port.created' |
||
923 | event = KytosEvent(name=name, content=event.content) |
||
924 | 1 | self.controller.buffers.app.put(event) |
|
925 | 1 | ||
926 | @staticmethod |
||
927 | 1 | def load_interfaces_available_tags(switch: Switch, |
|
928 | interfaces_details: List[dict]) -> None: |
||
929 | """Load interfaces available tags (vlans).""" |
||
930 | if not interfaces_details: |
||
931 | return |
||
932 | for interface_details in interfaces_details: |
||
933 | available_vlans = interface_details["available_vlans"] |
||
934 | if not available_vlans: |
||
935 | continue |
||
936 | 1 | log.debug(f"Interface id {interface_details['id']} loading " |
|
937 | f"{len(interface_details['available_vlans'])} " |
||
938 | 1 | "available tags") |
|
939 | 1 | port_number = int(interface_details["id"].split(":")[-1]) |
|
940 | interface = switch.interfaces[port_number] |
||
941 | 1 | interface.set_available_tags(interface_details['available_vlans']) |
|
942 | 1 | ||
943 | 1 | @listen_to('kytos/maintenance.start_link') |
|
944 | def on_link_maintenance_start(self, event): |
||
945 | 1 | """Deals with the start of links maintenance.""" |
|
946 | with self._links_lock: |
||
947 | 1 | self.handle_link_maintenance_start(event) |
|
948 | 1 | ||
949 | def handle_link_maintenance_start(self, event): |
||
950 | """Deals with the start of links maintenance.""" |
||
951 | notify_links = [] |
||
952 | 1 | maintenance_links = event.content['links'] |
|
953 | 1 | for maintenance_link in maintenance_links: |
|
954 | 1 | try: |
|
955 | link = self.links[maintenance_link.id] |
||
956 | 1 | except KeyError: |
|
957 | 1 | continue |
|
958 | 1 | notify_links.append(link) |
|
959 | for link in notify_links: |
||
960 | 1 | link.disable() |
|
961 | 1 | link.deactivate() |
|
962 | 1 | link.endpoint_a.deactivate() |
|
963 | link.endpoint_b.deactivate() |
||
964 | 1 | link.endpoint_a.disable() |
|
965 | link.endpoint_b.disable() |
||
966 | self.notify_link_status_change(link, reason='maintenance') |
||
967 | |||
968 | @listen_to('kytos/maintenance.end_link') |
||
969 | def on_link_maintenance_end(self, event): |
||
970 | """Deals with the end of links maintenance.""" |
||
971 | with self._links_lock: |
||
972 | self.handle_link_maintenance_end(event) |
||
973 | 1 | ||
974 | def handle_link_maintenance_end(self, event): |
||
975 | 1 | """Deals with the end of links maintenance.""" |
|
976 | 1 | notify_links = [] |
|
977 | 1 | maintenance_links = event.content['links'] |
|
978 | 1 | for maintenance_link in maintenance_links: |
|
979 | try: |
||
980 | 1 | link = self.links[maintenance_link.id] |
|
981 | 1 | except KeyError: |
|
982 | 1 | continue |
|
983 | 1 | notify_links.append(link) |
|
984 | 1 | for link in notify_links: |
|
985 | 1 | link.enable() |
|
986 | 1 | link.activate() |
|
987 | link.endpoint_a.activate() |
||
988 | 1 | link.endpoint_b.activate() |
|
989 | link.endpoint_a.enable() |
||
990 | link.endpoint_b.enable() |
||
991 | self.notify_link_status_change(link, reason='maintenance') |
||
992 |