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