Total Complexity | 150 |
Total Lines | 825 |
Duplicated Lines | 7.03 % |
Coverage | 88.64% |
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 | 1 | import time |
|
6 | |||
7 | 1 | from flask import jsonify, request |
|
8 | |||
9 | 1 | from kytos.core import KytosEvent, KytosNApp, log, rest |
|
10 | 1 | from kytos.core.helpers import listen_to |
|
11 | 1 | from kytos.core.interface import Interface |
|
12 | 1 | from kytos.core.link import Link |
|
13 | 1 | from kytos.core.switch import Switch |
|
14 | 1 | from napps.kytos.topology import settings |
|
15 | 1 | from napps.kytos.topology.models import Topology |
|
16 | 1 | from napps.kytos.topology.storehouse import StoreHouse |
|
17 | |||
18 | 1 | DEFAULT_LINK_UP_TIMER = 10 |
|
19 | |||
20 | |||
21 | 1 | class Main(KytosNApp): # pylint: disable=too-many-public-methods |
|
22 | """Main class of kytos/topology NApp. |
||
23 | |||
24 | This class is the entry point for this napp. |
||
25 | """ |
||
26 | |||
27 | 1 | def setup(self): |
|
28 | """Initialize the NApp's links list.""" |
||
29 | 1 | self.links = {} |
|
30 | 1 | self.store_items = {} |
|
31 | 1 | self.switches_state = {} |
|
32 | 1 | self.interfaces_state = {} |
|
33 | 1 | self.links_state = {} |
|
34 | 1 | self.link_up_timer = getattr(settings, 'LINK_UP_TIMER', |
|
35 | DEFAULT_LINK_UP_TIMER) |
||
36 | |||
37 | 1 | self.verify_storehouse('switches') |
|
38 | 1 | self.verify_storehouse('interfaces') |
|
39 | 1 | self.verify_storehouse('links') |
|
40 | |||
41 | 1 | self.storehouse = StoreHouse(self.controller) |
|
42 | |||
43 | 1 | def execute(self): |
|
44 | """Do nothing.""" |
||
45 | |||
46 | 1 | def shutdown(self): |
|
47 | """Do nothing.""" |
||
48 | log.info('NApp kytos/topology shutting down.') |
||
49 | |||
50 | 1 | def _get_link_or_create(self, endpoint_a, endpoint_b): |
|
51 | 1 | try: |
|
52 | 1 | new_link = Link(endpoint_a, endpoint_b) |
|
53 | except ValueError: |
||
54 | return None |
||
55 | |||
56 | 1 | for link in self.links.values(): |
|
57 | 1 | if new_link == link: |
|
58 | 1 | return link |
|
59 | |||
60 | 1 | self.links[new_link.id] = new_link |
|
61 | 1 | return new_link |
|
62 | |||
63 | 1 | def _get_switches_dict(self): |
|
64 | """Return a dictionary with the known switches.""" |
||
65 | 1 | switches = {'switches': {}} |
|
66 | 1 | for idx, switch in enumerate(self.controller.switches.values()): |
|
67 | 1 | switch_data = switch.as_dict() |
|
68 | 1 | if not all(key in switch_data['metadata'] |
|
69 | for key in ('lat', 'lng')): |
||
70 | # Switches are initialized somewhere in the ocean |
||
71 | switch_data['metadata']['lat'] = str(0.0) |
||
72 | switch_data['metadata']['lng'] = str(-30.0+idx*10.0) |
||
73 | 1 | switches['switches'][switch.id] = switch_data |
|
74 | 1 | return switches |
|
75 | |||
76 | 1 | def _get_links_dict(self): |
|
77 | """Return a dictionary with the known links.""" |
||
78 | 1 | return {'links': {l.id: l.as_dict() for l in |
|
79 | self.links.values()}} |
||
80 | |||
81 | 1 | def _get_topology_dict(self): |
|
82 | """Return a dictionary with the known topology.""" |
||
83 | 1 | return {'topology': {**self._get_switches_dict(), |
|
84 | **self._get_links_dict()}} |
||
85 | |||
86 | 1 | def _get_topology(self): |
|
87 | """Return an object representing the topology.""" |
||
88 | 1 | return Topology(self.controller.switches, self.links) |
|
89 | |||
90 | 1 | def _get_link_from_interface(self, interface): |
|
91 | """Return the link of the interface, or None if it does not exist.""" |
||
92 | 1 | for link in self.links.values(): |
|
93 | 1 | if interface in (link.endpoint_a, link.endpoint_b): |
|
94 | 1 | return link |
|
95 | 1 | return None |
|
96 | |||
97 | 1 | def _restore_links(self): |
|
98 | """Restore link saved in StoreHouse.""" |
||
99 | 1 | for link_id, state, in self.links_state.items(): |
|
100 | 1 | dpid_a = state['endpoint_a']['switch'] |
|
101 | 1 | iface_id_a = int(state['endpoint_a']['id'][-1]) |
|
102 | 1 | dpid_b = state['endpoint_b']['switch'] |
|
103 | 1 | iface_id_b = int(state['endpoint_b']['id'][-1]) |
|
104 | 1 | try: |
|
105 | 1 | endpoint_a = self.controller.switches[dpid_a].interfaces[ |
|
106 | iface_id_a] |
||
107 | 1 | endpoint_b = self.controller.switches[dpid_b].interfaces[ |
|
108 | iface_id_b] |
||
109 | except KeyError as error: |
||
110 | error_msg = (f"Error restoring link endpoint: {error}") |
||
111 | raise KeyError(error_msg) |
||
112 | |||
113 | 1 | link = self._get_link_or_create(endpoint_a, endpoint_b) |
|
114 | 1 | endpoint_a.update_link(link) |
|
115 | 1 | endpoint_b.update_link(link) |
|
116 | |||
117 | 1 | endpoint_a.nni = True |
|
118 | 1 | endpoint_b.nni = True |
|
119 | |||
120 | 1 | self.notify_topology_update() |
|
121 | |||
122 | 1 | try: |
|
123 | 1 | if state['enabled']: |
|
124 | 1 | self.links[link_id].enable() |
|
125 | else: |
||
126 | 1 | self.links[link_id].disable() |
|
127 | except KeyError: |
||
128 | error = ('Error restoring link status.' |
||
129 | f'The link {link} does not exist.') |
||
130 | raise KeyError(error) |
||
131 | |||
132 | 1 | def _restore_status(self): |
|
133 | """Restore the network administrative status saved in StoreHouse.""" |
||
134 | # restore Switches |
||
135 | 1 | for switch_id, state in self.switches_state.items(): |
|
136 | 1 | try: |
|
137 | 1 | if state: |
|
138 | 1 | self.controller.switches[switch_id].enable() |
|
139 | else: |
||
140 | 1 | self.controller.switches[switch_id].disable() |
|
141 | except KeyError: |
||
142 | error = ('Error while restoring switches status. The ' |
||
143 | f'{switch_id} does not exist.') |
||
144 | raise KeyError(error) |
||
145 | # restore interfaces |
||
146 | 1 | for interface_id, state in self.interfaces_state.items(): |
|
147 | 1 | switch_id = ":".join(interface_id.split(":")[:-1]) |
|
148 | 1 | interface_number = int(interface_id.split(":")[-1]) |
|
149 | 1 | interface_status, lldp_status = state |
|
150 | 1 | try: |
|
151 | 1 | switch = self.controller.switches[switch_id] |
|
152 | 1 | if interface_status: |
|
153 | 1 | switch.interfaces[interface_number].enable() |
|
154 | else: |
||
155 | 1 | switch.interfaces[interface_number].disable() |
|
156 | 1 | switch.interfaces[interface_number].lldp = lldp_status |
|
157 | except KeyError: |
||
158 | error = ('Error while restoring interface status. The ' |
||
159 | f'interface {interface_id} does not exist.') |
||
160 | raise KeyError(error) |
||
161 | # restore links |
||
162 | 1 | self._restore_links() |
|
163 | |||
164 | # pylint: disable=attribute-defined-outside-init |
||
165 | 1 | def _load_network_status(self): |
|
166 | """Load network status saved in storehouse.""" |
||
167 | 1 | status = self.storehouse.get_data() |
|
168 | 1 | if status: |
|
169 | 1 | switches = status['network_status']['switches'] |
|
170 | 1 | self.links_state = status['network_status']['links'] |
|
171 | |||
172 | 1 | for switch, switch_attributes in switches.items(): |
|
173 | # get swicthes status |
||
174 | 1 | self.switches_state[switch] = switch_attributes['enabled'] |
|
175 | 1 | interfaces = switch_attributes['interfaces'] |
|
176 | # get interface status |
||
177 | 1 | for interface, interface_attributes in interfaces.items(): |
|
178 | 1 | enabled_value = interface_attributes['enabled'] |
|
179 | 1 | lldp_value = interface_attributes['lldp'] |
|
180 | 1 | self.interfaces_state[interface] = (enabled_value, |
|
181 | lldp_value) |
||
182 | |||
183 | else: |
||
184 | 1 | error = 'There is no status saved to restore.' |
|
185 | 1 | log.info(error) |
|
186 | 1 | raise FileNotFoundError(error) |
|
187 | |||
188 | 1 | @rest('v3/') |
|
189 | def get_topology(self): |
||
190 | """Return the latest known topology. |
||
191 | |||
192 | This topology is updated when there are network events. |
||
193 | """ |
||
194 | 1 | return jsonify(self._get_topology_dict()) |
|
195 | |||
196 | 1 | @rest('v3/restore') |
|
197 | def restore_network_status(self): |
||
198 | """Restore the network administrative status saved in StoreHouse.""" |
||
199 | 1 | try: |
|
200 | 1 | self._load_network_status() |
|
201 | 1 | self._restore_status() |
|
202 | 1 | except (KeyError, FileNotFoundError) as exc: |
|
203 | 1 | return jsonify(f'{str(exc)}'), 404 |
|
204 | 1 | log.info('Network status restored.') |
|
205 | 1 | return jsonify('Administrative status restored.'), 200 |
|
206 | |||
207 | # Switch related methods |
||
208 | 1 | @rest('v3/switches') |
|
209 | def get_switches(self): |
||
210 | """Return a json with all the switches in the topology.""" |
||
211 | return jsonify(self._get_switches_dict()) |
||
212 | |||
213 | 1 | @rest('v3/switches/<dpid>/enable', methods=['POST']) |
|
214 | def enable_switch(self, dpid): |
||
215 | """Administratively enable a switch in the topology.""" |
||
216 | 1 | try: |
|
217 | 1 | self.controller.switches[dpid].enable() |
|
218 | 1 | log.info(f"Storing administrative state from switch {dpid}" |
|
219 | " to enabled.") |
||
220 | 1 | self.save_status_on_storehouse() |
|
221 | 1 | return jsonify("Operation successful"), 201 |
|
222 | 1 | except KeyError: |
|
223 | 1 | return jsonify("Switch not found"), 404 |
|
224 | |||
225 | 1 | @rest('v3/switches/<dpid>/disable', methods=['POST']) |
|
226 | def disable_switch(self, dpid): |
||
227 | """Administratively disable a switch in the topology.""" |
||
228 | 1 | try: |
|
229 | 1 | self.controller.switches[dpid].disable() |
|
230 | 1 | log.info(f"Storing administrative state from switch {dpid}" |
|
231 | " to disabled.") |
||
232 | 1 | self.save_status_on_storehouse() |
|
233 | 1 | return jsonify("Operation successful"), 201 |
|
234 | 1 | except KeyError: |
|
235 | 1 | return jsonify("Switch not found"), 404 |
|
236 | |||
237 | 1 | @rest('v3/switches/<dpid>/metadata') |
|
238 | def get_switch_metadata(self, dpid): |
||
239 | """Get metadata from a switch.""" |
||
240 | 1 | try: |
|
241 | 1 | return jsonify({"metadata": |
|
242 | self.controller.switches[dpid].metadata}), 200 |
||
243 | 1 | except KeyError: |
|
244 | 1 | return jsonify("Switch not found"), 404 |
|
245 | |||
246 | 1 | @rest('v3/switches/<dpid>/metadata', methods=['POST']) |
|
247 | def add_switch_metadata(self, dpid): |
||
248 | """Add metadata to a switch.""" |
||
249 | 1 | metadata = request.get_json() |
|
250 | 1 | try: |
|
251 | 1 | switch = self.controller.switches[dpid] |
|
252 | 1 | except KeyError: |
|
253 | 1 | return jsonify("Switch not found"), 404 |
|
254 | |||
255 | 1 | switch.extend_metadata(metadata) |
|
256 | 1 | self.notify_metadata_changes(switch, 'added') |
|
257 | 1 | return jsonify("Operation successful"), 201 |
|
258 | |||
259 | 1 | @rest('v3/switches/<dpid>/metadata/<key>', methods=['DELETE']) |
|
260 | def delete_switch_metadata(self, dpid, key): |
||
261 | """Delete metadata from a switch.""" |
||
262 | 1 | try: |
|
263 | 1 | switch = self.controller.switches[dpid] |
|
264 | 1 | except KeyError: |
|
265 | 1 | return jsonify("Switch not found"), 404 |
|
266 | |||
267 | 1 | switch.remove_metadata(key) |
|
268 | 1 | self.notify_metadata_changes(switch, 'removed') |
|
269 | 1 | return jsonify("Operation successful"), 200 |
|
270 | |||
271 | # Interface related methods |
||
272 | 1 | @rest('v3/interfaces') |
|
273 | def get_interfaces(self): |
||
274 | """Return a json with all the interfaces in the topology.""" |
||
275 | interfaces = {} |
||
276 | switches = self._get_switches_dict() |
||
277 | for switch in switches['switches'].values(): |
||
278 | for interface_id, interface in switch['interfaces'].items(): |
||
279 | interfaces[interface_id] = interface |
||
280 | |||
281 | return jsonify({'interfaces': interfaces}) |
||
282 | |||
283 | 1 | View Code Duplication | @rest('v3/interfaces/switch/<dpid>/enable', methods=['POST']) |
|
|||
284 | 1 | @rest('v3/interfaces/<interface_enable_id>/enable', methods=['POST']) |
|
285 | 1 | def enable_interface(self, interface_enable_id=None, dpid=None): |
|
286 | """Administratively enable interfaces in the topology.""" |
||
287 | 1 | error_list = [] # List of interfaces that were not activated. |
|
288 | 1 | msg_error = "Some interfaces couldn't be found and activated: " |
|
289 | 1 | if dpid is None: |
|
290 | 1 | dpid = ":".join(interface_enable_id.split(":")[:-1]) |
|
291 | 1 | try: |
|
292 | 1 | switch = self.controller.switches[dpid] |
|
293 | 1 | except KeyError as exc: |
|
294 | 1 | return jsonify(f"Switch not found: {exc}"), 404 |
|
295 | |||
296 | 1 | if interface_enable_id: |
|
297 | 1 | interface_number = int(interface_enable_id.split(":")[-1]) |
|
298 | |||
299 | 1 | try: |
|
300 | 1 | switch.interfaces[interface_number].enable() |
|
301 | 1 | except KeyError as exc: |
|
302 | 1 | error_list.append(f"Switch {dpid} Interface {exc}") |
|
303 | else: |
||
304 | 1 | for interface in switch.interfaces.values(): |
|
305 | 1 | interface.enable() |
|
306 | 1 | if not error_list: |
|
307 | 1 | log.info(f"Storing administrative state for enabled interfaces.") |
|
308 | 1 | self.save_status_on_storehouse() |
|
309 | 1 | return jsonify("Operation successful"), 200 |
|
310 | 1 | return jsonify({msg_error: |
|
311 | error_list}), 409 |
||
312 | |||
313 | 1 | View Code Duplication | @rest('v3/interfaces/switch/<dpid>/disable', methods=['POST']) |
314 | 1 | @rest('v3/interfaces/<interface_disable_id>/disable', methods=['POST']) |
|
315 | 1 | def disable_interface(self, interface_disable_id=None, dpid=None): |
|
316 | """Administratively disable interfaces in the topology.""" |
||
317 | 1 | error_list = [] # List of interfaces that were not deactivated. |
|
318 | 1 | msg_error = "Some interfaces couldn't be found and deactivated: " |
|
319 | 1 | if dpid is None: |
|
320 | 1 | dpid = ":".join(interface_disable_id.split(":")[:-1]) |
|
321 | 1 | try: |
|
322 | 1 | switch = self.controller.switches[dpid] |
|
323 | 1 | except KeyError as exc: |
|
324 | 1 | return jsonify(f"Switch not found: {exc}"), 404 |
|
325 | |||
326 | 1 | if interface_disable_id: |
|
327 | 1 | interface_number = int(interface_disable_id.split(":")[-1]) |
|
328 | |||
329 | 1 | try: |
|
330 | 1 | switch.interfaces[interface_number].disable() |
|
331 | 1 | except KeyError as exc: |
|
332 | 1 | error_list.append(f"Switch {dpid} Interface {exc}") |
|
333 | else: |
||
334 | 1 | for interface in switch.interfaces.values(): |
|
335 | 1 | interface.disable() |
|
336 | 1 | if not error_list: |
|
337 | 1 | log.info(f"Storing administrative state for disabled interfaces.") |
|
338 | 1 | self.save_status_on_storehouse() |
|
339 | 1 | return jsonify("Operation successful"), 200 |
|
340 | 1 | return jsonify({msg_error: |
|
341 | error_list}), 409 |
||
342 | |||
343 | 1 | @rest('v3/interfaces/<interface_id>/metadata') |
|
344 | def get_interface_metadata(self, interface_id): |
||
345 | """Get metadata from an interface.""" |
||
346 | 1 | switch_id = ":".join(interface_id.split(":")[:-1]) |
|
347 | 1 | interface_number = int(interface_id.split(":")[-1]) |
|
348 | 1 | try: |
|
349 | 1 | switch = self.controller.switches[switch_id] |
|
350 | 1 | except KeyError: |
|
351 | 1 | return jsonify("Switch not found"), 404 |
|
352 | |||
353 | 1 | try: |
|
354 | 1 | interface = switch.interfaces[interface_number] |
|
355 | 1 | except KeyError: |
|
356 | 1 | return jsonify("Interface not found"), 404 |
|
357 | |||
358 | 1 | return jsonify({"metadata": interface.metadata}), 200 |
|
359 | |||
360 | 1 | @rest('v3/interfaces/<interface_id>/metadata', methods=['POST']) |
|
361 | def add_interface_metadata(self, interface_id): |
||
362 | """Add metadata to an interface.""" |
||
363 | 1 | metadata = request.get_json() |
|
364 | |||
365 | 1 | switch_id = ":".join(interface_id.split(":")[:-1]) |
|
366 | 1 | interface_number = int(interface_id.split(":")[-1]) |
|
367 | 1 | try: |
|
368 | 1 | switch = self.controller.switches[switch_id] |
|
369 | 1 | except KeyError: |
|
370 | 1 | return jsonify("Switch not found"), 404 |
|
371 | |||
372 | 1 | try: |
|
373 | 1 | interface = switch.interfaces[interface_number] |
|
374 | 1 | except KeyError: |
|
375 | 1 | return jsonify("Interface not found"), 404 |
|
376 | |||
377 | 1 | interface.extend_metadata(metadata) |
|
378 | 1 | self.notify_metadata_changes(interface, 'added') |
|
379 | 1 | return jsonify("Operation successful"), 201 |
|
380 | |||
381 | 1 | @rest('v3/interfaces/<interface_id>/metadata/<key>', methods=['DELETE']) |
|
382 | def delete_interface_metadata(self, interface_id, key): |
||
383 | """Delete metadata from an interface.""" |
||
384 | 1 | switch_id = ":".join(interface_id.split(":")[:-1]) |
|
385 | 1 | interface_number = int(interface_id.split(":")[-1]) |
|
386 | |||
387 | 1 | try: |
|
388 | 1 | switch = self.controller.switches[switch_id] |
|
389 | 1 | except KeyError: |
|
390 | 1 | return jsonify("Switch not found"), 404 |
|
391 | |||
392 | 1 | try: |
|
393 | 1 | interface = switch.interfaces[interface_number] |
|
394 | 1 | except KeyError: |
|
395 | 1 | return jsonify("Interface not found"), 404 |
|
396 | |||
397 | 1 | if interface.remove_metadata(key) is False: |
|
398 | 1 | return jsonify("Metadata not found"), 404 |
|
399 | |||
400 | 1 | self.notify_metadata_changes(interface, 'removed') |
|
401 | 1 | return jsonify("Operation successful"), 200 |
|
402 | |||
403 | # Link related methods |
||
404 | 1 | @rest('v3/links') |
|
405 | def get_links(self): |
||
406 | """Return a json with all the links in the topology. |
||
407 | |||
408 | Links are connections between interfaces. |
||
409 | """ |
||
410 | return jsonify(self._get_links_dict()), 200 |
||
411 | |||
412 | 1 | @rest('v3/links/<link_id>/enable', methods=['POST']) |
|
413 | def enable_link(self, link_id): |
||
414 | """Administratively enable a link in the topology.""" |
||
415 | 1 | try: |
|
416 | 1 | self.links[link_id].enable() |
|
417 | 1 | except KeyError: |
|
418 | 1 | return jsonify("Link not found"), 404 |
|
419 | 1 | self.save_status_on_storehouse() |
|
420 | 1 | return jsonify("Operation successful"), 201 |
|
421 | |||
422 | 1 | @rest('v3/links/<link_id>/disable', methods=['POST']) |
|
423 | def disable_link(self, link_id): |
||
424 | """Administratively disable a link in the topology.""" |
||
425 | 1 | try: |
|
426 | 1 | self.links[link_id].disable() |
|
427 | 1 | except KeyError: |
|
428 | 1 | return jsonify("Link not found"), 404 |
|
429 | 1 | self.save_status_on_storehouse() |
|
430 | 1 | return jsonify("Operation successful"), 201 |
|
431 | |||
432 | 1 | @rest('v3/links/<link_id>/metadata') |
|
433 | def get_link_metadata(self, link_id): |
||
434 | """Get metadata from a link.""" |
||
435 | 1 | try: |
|
436 | 1 | return jsonify({"metadata": self.links[link_id].metadata}), 200 |
|
437 | 1 | except KeyError: |
|
438 | 1 | return jsonify("Link not found"), 404 |
|
439 | |||
440 | 1 | @rest('v3/links/<link_id>/metadata', methods=['POST']) |
|
441 | def add_link_metadata(self, link_id): |
||
442 | """Add metadata to a link.""" |
||
443 | 1 | metadata = request.get_json() |
|
444 | 1 | try: |
|
445 | 1 | link = self.links[link_id] |
|
446 | 1 | except KeyError: |
|
447 | 1 | return jsonify("Link not found"), 404 |
|
448 | |||
449 | 1 | link.extend_metadata(metadata) |
|
450 | 1 | self.notify_metadata_changes(link, 'added') |
|
451 | 1 | return jsonify("Operation successful"), 201 |
|
452 | |||
453 | 1 | @rest('v3/links/<link_id>/metadata/<key>', methods=['DELETE']) |
|
454 | def delete_link_metadata(self, link_id, key): |
||
455 | """Delete metadata from a link.""" |
||
456 | 1 | try: |
|
457 | 1 | link = self.links[link_id] |
|
458 | 1 | except KeyError: |
|
459 | 1 | return jsonify("Link not found"), 404 |
|
460 | |||
461 | 1 | if link.remove_metadata(key) is False: |
|
462 | 1 | return jsonify("Metadata not found"), 404 |
|
463 | |||
464 | 1 | self.notify_metadata_changes(link, 'removed') |
|
465 | 1 | return jsonify("Operation successful"), 200 |
|
466 | |||
467 | 1 | @listen_to('.*.switch.(new|reconnected)') |
|
468 | def handle_new_switch(self, event): |
||
469 | """Create a new Device on the Topology. |
||
470 | |||
471 | Handle the event of a new created switch and update the topology with |
||
472 | this new device. |
||
473 | """ |
||
474 | 1 | switch = event.content['switch'] |
|
475 | 1 | switch.activate() |
|
476 | 1 | log.debug('Switch %s added to the Topology.', switch.id) |
|
477 | 1 | self.notify_topology_update() |
|
478 | 1 | self.update_instance_metadata(switch) |
|
479 | |||
480 | 1 | @listen_to('.*.connection.lost') |
|
481 | def handle_connection_lost(self, event): |
||
482 | """Remove a Device from the topology. |
||
483 | |||
484 | Remove the disconnected Device and every link that has one of its |
||
485 | interfaces. |
||
486 | """ |
||
487 | 1 | switch = event.content['source'].switch |
|
488 | 1 | if switch: |
|
489 | 1 | switch.deactivate() |
|
490 | 1 | log.debug('Switch %s removed from the Topology.', switch.id) |
|
491 | 1 | self.notify_topology_update() |
|
492 | |||
493 | 1 | def handle_interface_up(self, event): |
|
494 | """Update the topology based on a Port Modify event. |
||
495 | |||
496 | The event notifies that an interface was changed to 'up'. |
||
497 | """ |
||
498 | 1 | interface = event.content['interface'] |
|
499 | 1 | interface.activate() |
|
500 | 1 | self.notify_topology_update() |
|
501 | 1 | self.update_instance_metadata(interface) |
|
502 | |||
503 | 1 | @listen_to('.*.switch.interface.created') |
|
504 | def handle_interface_created(self, event): |
||
505 | """Update the topology based on a Port Create event.""" |
||
506 | 1 | self.handle_interface_up(event) |
|
507 | |||
508 | 1 | def handle_interface_down(self, event): |
|
509 | """Update the topology based on a Port Modify event. |
||
510 | |||
511 | The event notifies that an interface was changed to 'down'. |
||
512 | """ |
||
513 | 1 | interface = event.content['interface'] |
|
514 | 1 | interface.deactivate() |
|
515 | 1 | self.handle_interface_link_down(event) |
|
516 | 1 | self.notify_topology_update() |
|
517 | |||
518 | 1 | @listen_to('.*.switch.interface.deleted') |
|
519 | def handle_interface_deleted(self, event): |
||
520 | """Update the topology based on a Port Delete event.""" |
||
521 | 1 | self.handle_interface_down(event) |
|
522 | |||
523 | 1 | @listen_to('.*.switch.interface.link_up') |
|
524 | def handle_interface_link_up(self, event): |
||
525 | """Update the topology based on a Port Modify event. |
||
526 | |||
527 | The event notifies that an interface's link was changed to 'up'. |
||
528 | """ |
||
529 | 1 | interface = event.content['interface'] |
|
530 | 1 | self.handle_link_up(interface) |
|
531 | |||
532 | 1 | @listen_to('kytos/maintenance.end_switch') |
|
533 | def handle_switch_maintenance_end(self, event): |
||
534 | """Handle the end of the maintenance of a switch.""" |
||
535 | 1 | switches = event.content['switches'] |
|
536 | 1 | for switch in switches: |
|
537 | 1 | switch.enable() |
|
538 | 1 | switch.activate() |
|
539 | 1 | for interface in switch.interfaces.values(): |
|
540 | 1 | interface.enable() |
|
541 | 1 | self.handle_link_up(interface) |
|
542 | |||
543 | 1 | def handle_link_up(self, interface): |
|
544 | """Notify a link is up.""" |
||
545 | 1 | link = self._get_link_from_interface(interface) |
|
546 | 1 | if not link: |
|
547 | return |
||
548 | 1 | if link.endpoint_a == interface: |
|
549 | 1 | other_interface = link.endpoint_b |
|
550 | else: |
||
551 | other_interface = link.endpoint_a |
||
552 | 1 | interface.activate() |
|
553 | 1 | if other_interface.is_active() is False: |
|
554 | return |
||
555 | 1 | if link.is_active() is False: |
|
556 | 1 | link.update_metadata('last_status_change', time.time()) |
|
557 | 1 | link.activate() |
|
558 | |||
559 | # As each run of this method uses a different thread, |
||
560 | # there is no risk this sleep will lock the NApp. |
||
561 | 1 | time.sleep(self.link_up_timer) |
|
562 | |||
563 | 1 | last_status_change = link.get_metadata('last_status_change') |
|
564 | 1 | now = time.time() |
|
565 | 1 | if link.is_active() and \ |
|
566 | now - last_status_change >= self.link_up_timer: |
||
567 | 1 | self.notify_topology_update() |
|
568 | 1 | self.update_instance_metadata(link) |
|
569 | 1 | self.notify_link_status_change(link) |
|
570 | |||
571 | 1 | @listen_to('.*.switch.interface.link_down') |
|
572 | def handle_interface_link_down(self, event): |
||
573 | """Update the topology based on a Port Modify event. |
||
574 | |||
575 | The event notifies that an interface's link was changed to 'down'. |
||
576 | """ |
||
577 | 1 | interface = event.content['interface'] |
|
578 | 1 | self.handle_link_down(interface) |
|
579 | |||
580 | 1 | @listen_to('kytos/maintenance.start_switch') |
|
581 | def handle_switch_maintenance_start(self, event): |
||
582 | """Handle the start of the maintenance of a switch.""" |
||
583 | 1 | switches = event.content['switches'] |
|
584 | 1 | for switch in switches: |
|
585 | 1 | switch.disable() |
|
586 | 1 | switch.deactivate() |
|
587 | 1 | for interface in switch.interfaces.values(): |
|
588 | 1 | interface.disable() |
|
589 | 1 | if interface.is_active(): |
|
590 | 1 | self.handle_link_down(interface) |
|
591 | |||
592 | 1 | def handle_link_down(self, interface): |
|
593 | """Notify a link is down.""" |
||
594 | 1 | link = self._get_link_from_interface(interface) |
|
595 | 1 | if link and link.is_active(): |
|
596 | 1 | link.deactivate() |
|
597 | 1 | link.update_metadata('last_status_change', time.time()) |
|
598 | 1 | self.notify_topology_update() |
|
599 | 1 | self.notify_link_status_change(link) |
|
600 | |||
601 | 1 | @listen_to('.*.interface.is.nni') |
|
602 | def add_links(self, event): |
||
603 | """Update the topology with links related to the NNI interfaces.""" |
||
604 | 1 | interface_a = event.content['interface_a'] |
|
605 | 1 | interface_b = event.content['interface_b'] |
|
606 | |||
607 | 1 | link = self._get_link_or_create(interface_a, interface_b) |
|
608 | |||
609 | 1 | if link is None: |
|
610 | return |
||
611 | |||
612 | 1 | interface_a.update_link(link) |
|
613 | 1 | interface_b.update_link(link) |
|
614 | |||
615 | 1 | interface_a.nni = True |
|
616 | 1 | interface_b.nni = True |
|
617 | |||
618 | 1 | self.notify_topology_update() |
|
619 | |||
620 | # def add_host(self, event): |
||
621 | # """Update the topology with a new Host.""" |
||
622 | |||
623 | # interface = event.content['port'] |
||
624 | # mac = event.content['reachable_mac'] |
||
625 | |||
626 | # host = Host(mac) |
||
627 | # link = self.topology.get_link(interface.id) |
||
628 | # if link is not None: |
||
629 | # return |
||
630 | |||
631 | # self.topology.add_link(interface.id, host.id) |
||
632 | # self.topology.add_device(host) |
||
633 | |||
634 | # if settings.DISPLAY_FULL_DUPLEX_LINKS: |
||
635 | # self.topology.add_link(host.id, interface.id) |
||
636 | |||
637 | # pylint: disable=unused-argument |
||
638 | 1 | @listen_to('.*.network_status.updated') |
|
639 | 1 | def save_status_on_storehouse(self, event=None): |
|
640 | """Save the network administrative status using storehouse.""" |
||
641 | 1 | status = self._get_switches_dict() |
|
642 | 1 | status['id'] = 'network_status' |
|
643 | 1 | if event: |
|
644 | content = event.content |
||
645 | log.info(f"Storing the administrative state of the" |
||
646 | f" {content['attribute']} attribute to" |
||
647 | f" {content['state']} in the interfaces" |
||
648 | f" {content['interface_ids']}") |
||
649 | 1 | status.update(self._get_links_dict()) |
|
650 | 1 | self.storehouse.save_status(status) |
|
651 | |||
652 | 1 | def notify_topology_update(self): |
|
653 | """Send an event to notify about updates on the topology.""" |
||
654 | 1 | name = 'kytos/topology.updated' |
|
655 | 1 | event = KytosEvent(name=name, content={'topology': |
|
656 | self._get_topology()}) |
||
657 | 1 | self.controller.buffers.app.put(event) |
|
658 | |||
659 | 1 | def notify_link_status_change(self, link): |
|
660 | """Send an event to notify about a status change on a link.""" |
||
661 | 1 | name = 'kytos/topology.' |
|
662 | 1 | if link.is_active(): |
|
663 | 1 | status = 'link_up' |
|
664 | else: |
||
665 | status = 'link_down' |
||
666 | 1 | event = KytosEvent(name=name+status, content={'link': link}) |
|
667 | 1 | self.controller.buffers.app.put(event) |
|
668 | |||
669 | 1 | def notify_metadata_changes(self, obj, action): |
|
670 | """Send an event to notify about metadata changes.""" |
||
671 | 1 | if isinstance(obj, Switch): |
|
672 | 1 | entity = 'switch' |
|
673 | 1 | entities = 'switches' |
|
674 | 1 | elif isinstance(obj, Interface): |
|
675 | 1 | entity = 'interface' |
|
676 | 1 | entities = 'interfaces' |
|
677 | elif isinstance(obj, Link): |
||
678 | entity = 'link' |
||
679 | entities = 'links' |
||
680 | |||
681 | 1 | name = f'kytos/topology.{entities}.metadata.{action}' |
|
682 | 1 | event = KytosEvent(name=name, content={entity: obj, |
|
683 | 'metadata': obj.metadata}) |
||
684 | 1 | self.controller.buffers.app.put(event) |
|
685 | 1 | log.debug(f'Metadata from {obj.id} was {action}.') |
|
686 | |||
687 | 1 | @listen_to('.*.switch.port.created') |
|
688 | def notify_port_created(self, original_event): |
||
689 | """Notify when a port is created.""" |
||
690 | 1 | name = 'kytos/topology.port.created' |
|
691 | 1 | event = KytosEvent(name=name, content=original_event.content) |
|
692 | 1 | self.controller.buffers.app.put(event) |
|
693 | |||
694 | 1 | @listen_to('kytos/topology.*.metadata.*') |
|
695 | def save_metadata_on_store(self, event): |
||
696 | """Send to storehouse the data updated.""" |
||
697 | 1 | name = 'kytos.storehouse.update' |
|
698 | 1 | if 'switch' in event.content: |
|
699 | 1 | store = self.store_items.get('switches') |
|
700 | 1 | obj = event.content.get('switch') |
|
701 | 1 | namespace = 'kytos.topology.switches.metadata' |
|
702 | 1 | elif 'interface' in event.content: |
|
703 | 1 | store = self.store_items.get('interfaces') |
|
704 | 1 | obj = event.content.get('interface') |
|
705 | 1 | namespace = 'kytos.topology.iterfaces.metadata' |
|
706 | 1 | elif 'link' in event.content: |
|
707 | 1 | store = self.store_items.get('links') |
|
708 | 1 | obj = event.content.get('link') |
|
709 | 1 | namespace = 'kytos.topology.links.metadata' |
|
710 | |||
711 | 1 | store.data[obj.id] = obj.metadata |
|
712 | 1 | content = {'namespace': namespace, |
|
713 | 'box_id': store.box_id, |
||
714 | 'data': store.data, |
||
715 | 'callback': self.update_instance} |
||
716 | |||
717 | 1 | event = KytosEvent(name=name, content=content) |
|
718 | 1 | self.controller.buffers.app.put(event) |
|
719 | |||
720 | 1 | @staticmethod |
|
721 | def update_instance(event, _data, error): |
||
722 | """Display in Kytos console if the data was updated.""" |
||
723 | entities = event.content.get('namespace', '').split('.')[-2] |
||
724 | if error: |
||
725 | log.error(f'Error trying to update storehouse {entities}.') |
||
726 | else: |
||
727 | log.debug(f'Storehouse update to entities: {entities}.') |
||
728 | |||
729 | 1 | def verify_storehouse(self, entities): |
|
730 | """Request a list of box saved by specific entity.""" |
||
731 | 1 | name = 'kytos.storehouse.list' |
|
732 | 1 | content = {'namespace': f'kytos.topology.{entities}.metadata', |
|
733 | 'callback': self.request_retrieve_entities} |
||
734 | 1 | event = KytosEvent(name=name, content=content) |
|
735 | 1 | self.controller.buffers.app.put(event) |
|
736 | 1 | log.info(f'verify data in storehouse for {entities}.') |
|
737 | |||
738 | 1 | def request_retrieve_entities(self, event, data, _error): |
|
739 | """Create a box or retrieve an existent box from storehouse.""" |
||
740 | 1 | msg = '' |
|
741 | 1 | content = {'namespace': event.content.get('namespace'), |
|
742 | 'callback': self.load_from_store, |
||
743 | 'data': {}} |
||
744 | |||
745 | 1 | if not data: |
|
746 | 1 | name = 'kytos.storehouse.create' |
|
747 | 1 | msg = 'Create new box in storehouse' |
|
748 | else: |
||
749 | 1 | name = 'kytos.storehouse.retrieve' |
|
750 | 1 | content['box_id'] = data[0] |
|
751 | 1 | msg = 'Retrieve data from storeohouse.' |
|
752 | |||
753 | 1 | event = KytosEvent(name=name, content=content) |
|
754 | 1 | self.controller.buffers.app.put(event) |
|
755 | 1 | log.debug(msg) |
|
756 | |||
757 | 1 | def load_from_store(self, event, box, error): |
|
758 | """Save the data retrived from storehouse.""" |
||
759 | entities = event.content.get('namespace', '').split('.')[-2] |
||
760 | if error: |
||
761 | log.error('Error while get a box from storehouse.') |
||
762 | else: |
||
763 | self.store_items[entities] = box |
||
764 | log.debug('Data updated') |
||
765 | |||
766 | 1 | def update_instance_metadata(self, obj): |
|
767 | """Update object instance with saved metadata.""" |
||
768 | metadata = None |
||
769 | if isinstance(obj, Interface): |
||
770 | all_metadata = self.store_items.get('interfaces', None) |
||
771 | if all_metadata: |
||
772 | metadata = all_metadata.data.get(obj.id) |
||
773 | elif isinstance(obj, Switch): |
||
774 | all_metadata = self.store_items.get('switches', None) |
||
775 | if all_metadata: |
||
776 | metadata = all_metadata.data.get(obj.id) |
||
777 | elif isinstance(obj, Link): |
||
778 | all_metadata = self.store_items.get('links', None) |
||
779 | if all_metadata: |
||
780 | metadata = all_metadata.data.get(obj.id) |
||
781 | |||
782 | if metadata: |
||
783 | obj.extend_metadata(metadata) |
||
784 | log.debug(f'Metadata to {obj.id} was updated') |
||
785 | |||
786 | 1 | @listen_to('kytos/maintenance.start_link') |
|
787 | def handle_link_maintenance_start(self, event): |
||
788 | """Deals with the start of links maintenance.""" |
||
789 | 1 | notify_links = [] |
|
790 | 1 | maintenance_links = event.content['links'] |
|
791 | 1 | for maintenance_link in maintenance_links: |
|
792 | 1 | try: |
|
793 | 1 | link = self.links[maintenance_link.id] |
|
794 | 1 | except KeyError: |
|
795 | 1 | continue |
|
796 | 1 | notify_links.append(link) |
|
797 | 1 | for link in notify_links: |
|
798 | 1 | link.disable() |
|
799 | 1 | link.deactivate() |
|
800 | 1 | link.endpoint_a.deactivate() |
|
801 | 1 | link.endpoint_b.deactivate() |
|
802 | 1 | link.endpoint_a.disable() |
|
803 | 1 | link.endpoint_b.disable() |
|
804 | 1 | self.notify_link_status_change(link) |
|
805 | |||
806 | 1 | @listen_to('kytos/maintenance.end_link') |
|
807 | def handle_link_maintenance_end(self, event): |
||
808 | """Deals with the end of links maintenance.""" |
||
809 | 1 | notify_links = [] |
|
810 | 1 | maintenance_links = event.content['links'] |
|
811 | 1 | for maintenance_link in maintenance_links: |
|
812 | 1 | try: |
|
813 | 1 | link = self.links[maintenance_link.id] |
|
814 | 1 | except KeyError: |
|
815 | 1 | continue |
|
816 | 1 | notify_links.append(link) |
|
817 | 1 | for link in notify_links: |
|
818 | 1 | link.enable() |
|
819 | 1 | link.activate() |
|
820 | 1 | link.endpoint_a.activate() |
|
821 | 1 | link.endpoint_b.activate() |
|
822 | 1 | link.endpoint_a.enable() |
|
823 | 1 | link.endpoint_b.enable() |
|
824 | self.notify_link_status_change(link) |
||
825 |