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