Passed
Pull Request — master (#130)
by Carlos
02:07
created

build.main   F

Complexity

Total Complexity 149

Size/Duplication

Total Lines 826
Duplicated Lines 7.02 %

Test Coverage

Coverage 89.62%

Importance

Changes 0
Metric Value
wmc 149
eloc 583
dl 58
loc 826
ccs 475
cts 530
cp 0.8962
rs 2
c 0
b 0
f 0

58 Methods

Rating   Name   Duplication   Size   Complexity  
A Main._get_switches_dict() 0 12 3
A Main.shutdown() 0 3 1
A Main._get_links_dict() 0 4 1
A Main._get_link_from_interface() 0 6 3
A Main._get_topology_dict() 0 4 1
A Main._get_topology() 0 3 1
A Main.disable_switch() 0 11 2
A Main.disable_link() 0 9 2
A Main.enable_switch() 0 11 2
B Main.enable_interface() 29 29 7
A Main.add_switch_metadata() 0 12 2
A Main.get_interfaces() 0 10 3
A Main.delete_interface_metadata() 0 21 4
A Main.add_interface_metadata() 0 20 3
A Main.get_switches() 0 4 1
A Main.handle_interface_down() 0 9 1
A Main.handle_interface_link_up() 0 8 1
B Main.handle_link_up() 0 27 7
A Main.handle_interface_created() 0 4 1
A Main.get_interface_metadata() 0 16 3
A Main.delete_link_metadata() 0 13 3
A Main.enable_link() 0 9 2
A Main.handle_link_down() 0 8 3
A Main.handle_new_switch() 0 12 1
A Main.get_switch_metadata() 0 8 2
A Main.handle_switch_maintenance_end() 0 10 3
A Main.handle_connection_lost() 0 12 2
A Main.get_links() 0 7 1
B Main.disable_interface() 29 29 7
A Main.handle_switch_maintenance_start() 0 11 4
A Main._load_network_status() 0 22 4
A Main.get_topology() 0 7 1
A Main.handle_interface_link_down() 0 8 1
A Main.handle_interface_up() 0 9 1
A Main.handle_interface_deleted() 0 4 1
A Main.restore_network_status() 0 10 2
A Main.add_link_metadata() 0 12 2
A Main.delete_switch_metadata() 0 11 2
A Main.get_link_metadata() 0 7 2
A Main.notify_port_created() 0 6 1
A Main.verify_storehouse() 0 8 1
A Main.load_from_store() 0 8 2
A Main.request_retrieve_entities() 0 18 2
A Main.handle_link_maintenance_end() 0 19 4
A Main.notify_link_status_change() 0 9 2
A Main.notify_topology_update() 0 6 1
A Main.save_status_on_storehouse() 0 13 2
A Main.update_instance() 0 8 2
A Main.save_metadata_on_store() 0 25 4
A Main.handle_link_maintenance_start() 0 19 4
A Main.notify_metadata_changes() 0 17 4
B Main._restore_links() 0 34 5
A Main.setup() 0 15 1
A Main.execute() 0 2 1
A Main._get_link_or_create() 0 9 3
B Main._restore_status() 0 33 7
B Main.update_instance_metadata() 0 19 8
A Main.add_links() 0 19 2

How to fix   Duplicated Code    Complexity   

Duplicated Code

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:

Complexity

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

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.exceptions import KytosLinkCreationError
11 1
from kytos.core.helpers import listen_to
12 1
from kytos.core.interface import Interface
13 1
from kytos.core.link import Link
14 1
from kytos.core.switch import Switch
15 1
from napps.kytos.topology import settings
16 1
from napps.kytos.topology.models import Topology
17 1
from napps.kytos.topology.storehouse import StoreHouse
18
19 1
DEFAULT_LINK_UP_TIMER = 10
20
21
22 1
class Main(KytosNApp):  # pylint: disable=too-many-public-methods
23
    """Main class of kytos/topology NApp.
24
25
    This class is the entry point for this napp.
26
    """
27
28 1
    def setup(self):
29
        """Initialize the NApp's links list."""
30 1
        self.links = {}
31 1
        self.store_items = {}
32 1
        self.switches_state = {}
33 1
        self.interfaces_state = {}
34 1
        self.links_state = {}
35 1
        self.link_up_timer = getattr(settings, 'LINK_UP_TIMER',
36
                                     DEFAULT_LINK_UP_TIMER)
37
38 1
        self.verify_storehouse('switches')
39 1
        self.verify_storehouse('interfaces')
40 1
        self.verify_storehouse('links')
41
42 1
        self.storehouse = StoreHouse(self.controller)
43
44 1
    def execute(self):
45
        """Do nothing."""
46
47 1
    def shutdown(self):
48
        """Do nothing."""
49
        log.info('NApp kytos/topology shutting down.')
50
51 1
    def _get_link_or_create(self, endpoint_a, endpoint_b):
52 1
        new_link = Link(endpoint_a, endpoint_b)
53
54 1
        for link in self.links.values():
55 1
            if new_link == link:
56 1
                return link
57
58 1
        self.links[new_link.id] = new_link
59 1
        return new_link
60
61 1
    def _get_switches_dict(self):
62
        """Return a dictionary with the known switches."""
63 1
        switches = {'switches': {}}
64 1
        for idx, switch in enumerate(self.controller.switches.values()):
65 1
            switch_data = switch.as_dict()
66 1
            if not all(key in switch_data['metadata']
67
                       for key in ('lat', 'lng')):
68
                # Switches are initialized somewhere in the ocean
69
                switch_data['metadata']['lat'] = str(0.0)
70
                switch_data['metadata']['lng'] = str(-30.0+idx*10.0)
71 1
            switches['switches'][switch.id] = switch_data
72 1
        return switches
73
74 1
    def _get_links_dict(self):
75
        """Return a dictionary with the known links."""
76 1
        return {'links': {l.id: l.as_dict() for l in
77
                          self.links.values()}}
78
79 1
    def _get_topology_dict(self):
80
        """Return a dictionary with the known topology."""
81 1
        return {'topology': {**self._get_switches_dict(),
82
                             **self._get_links_dict()}}
83
84 1
    def _get_topology(self):
85
        """Return an object representing the topology."""
86 1
        return Topology(self.controller.switches, self.links)
87
88 1
    def _get_link_from_interface(self, interface):
89
        """Return the link of the interface, or None if it does not exist."""
90 1
        for link in self.links.values():
91 1
            if interface in (link.endpoint_a, link.endpoint_b):
92 1
                return link
93 1
        return None
94
95 1
    def _restore_links(self):
96
        """Restore link saved in StoreHouse."""
97 1
        for link_id, state, in self.links_state.items():
98 1
            dpid_a = state['endpoint_a']['switch']
99 1
            iface_id_a = int(state['endpoint_a']['id'][-1])
100 1
            dpid_b = state['endpoint_b']['switch']
101 1
            iface_id_b = int(state['endpoint_b']['id'][-1])
102 1
            try:
103 1
                endpoint_a = self.controller.switches[dpid_a].interfaces[
104
                    iface_id_a]
105 1
                endpoint_b = self.controller.switches[dpid_b].interfaces[
106
                    iface_id_b]
107
            except KeyError as error:
108
                error_msg = (f"Error restoring link endpoint: {error}")
109
                raise KeyError(error_msg)
110
111 1
            link = self._get_link_or_create(endpoint_a, endpoint_b)
112 1
            endpoint_a.update_link(link)
113 1
            endpoint_b.update_link(link)
114
115 1
            endpoint_a.nni = True
116 1
            endpoint_b.nni = True
117
118 1
            self.notify_topology_update()
119
120 1
            try:
121 1
                if state['enabled']:
122 1
                    self.links[link_id].enable()
123
                else:
124 1
                    self.links[link_id].disable()
125
            except KeyError:
126
                error = ('Error restoring link status.'
127
                         f'The link {link} does not exist.')
128
                raise KeyError(error)
129
130 1
    def _restore_status(self):
131
        """Restore the network administrative status saved in StoreHouse."""
132
        # restore Switches
133 1
        for switch_id, state in self.switches_state.items():
134 1
            try:
135 1
                if state:
136 1
                    self.controller.switches[switch_id].enable()
137
                else:
138 1
                    self.controller.switches[switch_id].disable()
139
            except KeyError:
140
                error = ('Error while restoring switches status. The '
141
                         f'{switch_id} does not exist.')
142
                raise KeyError(error)
143
        # restore interfaces
144 1
        for interface_id, state in self.interfaces_state.items():
145 1
            switch_id = ":".join(interface_id.split(":")[:-1])
146 1
            interface_number = int(interface_id.split(":")[-1])
147 1
            interface_status, lldp_status = state
148 1
            try:
149 1
                switch = self.controller.switches[switch_id]
150 1
                interface = switch.interfaces[interface_number]
151 1
                if interface_status:
152 1
                    interface.enable()
153
                else:
154 1
                    interface.disable()
155 1
                interface.lldp = lldp_status
156 1
                self.update_instance_metadata(interface)
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'])
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
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'])
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
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
        try:
608 1
            link = self._get_link_or_create(interface_a, interface_b)
609
        except KytosLinkCreationError as err:
610
            log.error(f'Error creating link: {err}.')
611
            return
612
613 1
        interface_a.update_link(link)
614 1
        interface_b.update_link(link)
615
616 1
        interface_a.nni = True
617 1
        interface_b.nni = True
618
619 1
        self.notify_topology_update()
620
621
    # def add_host(self, event):
622
    #    """Update the topology with a new Host."""
623
624
    #    interface = event.content['port']
625
    #    mac = event.content['reachable_mac']
626
627
    #    host = Host(mac)
628
    #    link = self.topology.get_link(interface.id)
629
    #    if link is not None:
630
    #        return
631
632
    #    self.topology.add_link(interface.id, host.id)
633
    #    self.topology.add_device(host)
634
635
    #    if settings.DISPLAY_FULL_DUPLEX_LINKS:
636
    #        self.topology.add_link(host.id, interface.id)
637
638
    # pylint: disable=unused-argument
639 1
    @listen_to('.*.network_status.updated')
640 1
    def save_status_on_storehouse(self, event=None):
641
        """Save the network administrative status using storehouse."""
642 1
        status = self._get_switches_dict()
643 1
        status['id'] = 'network_status'
644 1
        if event:
645
            content = event.content
646
            log.info(f"Storing the administrative state of the"
647
                     f" {content['attribute']} attribute to"
648
                     f" {content['state']} in the interfaces"
649
                     f" {content['interface_ids']}")
650 1
        status.update(self._get_links_dict())
651 1
        self.storehouse.save_status(status)
652
653 1
    def notify_topology_update(self):
654
        """Send an event to notify about updates on the topology."""
655 1
        name = 'kytos/topology.updated'
656 1
        event = KytosEvent(name=name, content={'topology':
657
                                               self._get_topology()})
658 1
        self.controller.buffers.app.put(event)
659
660 1
    def notify_link_status_change(self, link):
661
        """Send an event to notify about a status change on a link."""
662 1
        name = 'kytos/topology.'
663 1
        if link.is_active():
664 1
            status = 'link_up'
665
        else:
666
            status = 'link_down'
667 1
        event = KytosEvent(name=name+status, content={'link': link})
668 1
        self.controller.buffers.app.put(event)
669
670 1
    def notify_metadata_changes(self, obj, action):
671
        """Send an event to notify about metadata changes."""
672 1
        if isinstance(obj, Switch):
673 1
            entity = 'switch'
674 1
            entities = 'switches'
675 1
        elif isinstance(obj, Interface):
676 1
            entity = 'interface'
677 1
            entities = 'interfaces'
678
        elif isinstance(obj, Link):
679
            entity = 'link'
680
            entities = 'links'
681
682 1
        name = f'kytos/topology.{entities}.metadata.{action}'
683 1
        event = KytosEvent(name=name, content={entity: obj,
0 ignored issues
show
introduced by
The variable entity does not seem to be defined for all execution paths.
Loading history...
684
                                               'metadata': obj.metadata})
685 1
        self.controller.buffers.app.put(event)
686 1
        log.debug(f'Metadata from {obj.id} was {action}.')
687
688 1
    @listen_to('.*.switch.port.created')
689
    def notify_port_created(self, original_event):
690
        """Notify when a port is created."""
691 1
        name = 'kytos/topology.port.created'
692 1
        event = KytosEvent(name=name, content=original_event.content)
693 1
        self.controller.buffers.app.put(event)
694
695 1
    @listen_to('kytos/topology.*.metadata.*')
696
    def save_metadata_on_store(self, event):
697
        """Send to storehouse the data updated."""
698 1
        name = 'kytos.storehouse.update'
699 1
        if 'switch' in event.content:
700 1
            store = self.store_items.get('switches')
701 1
            obj = event.content.get('switch')
702 1
            namespace = 'kytos.topology.switches.metadata'
703 1
        elif 'interface' in event.content:
704 1
            store = self.store_items.get('interfaces')
705 1
            obj = event.content.get('interface')
706 1
            namespace = 'kytos.topology.interfaces.metadata'
707 1
        elif 'link' in event.content:
708 1
            store = self.store_items.get('links')
709 1
            obj = event.content.get('link')
710 1
            namespace = 'kytos.topology.links.metadata'
711
712 1
        store.data[obj.id] = obj.metadata
0 ignored issues
show
introduced by
The variable store does not seem to be defined for all execution paths.
Loading history...
introduced by
The variable obj does not seem to be defined for all execution paths.
Loading history...
713 1
        content = {'namespace': namespace,
0 ignored issues
show
introduced by
The variable namespace does not seem to be defined for all execution paths.
Loading history...
714
                   'box_id': store.box_id,
715
                   'data': store.data,
716
                   'callback': self.update_instance}
717
718 1
        event = KytosEvent(name=name, content=content)
719 1
        self.controller.buffers.app.put(event)
720
721 1
    @staticmethod
722
    def update_instance(event, _data, error):
723
        """Display in Kytos console if the data was updated."""
724
        entities = event.content.get('namespace', '').split('.')[-2]
725
        if error:
726
            log.error(f'Error trying to update storehouse {entities}.')
727
        else:
728
            log.debug(f'Storehouse update to entities: {entities}.')
729
730 1
    def verify_storehouse(self, entities):
731
        """Request a list of box saved by specific entity."""
732 1
        name = 'kytos.storehouse.list'
733 1
        content = {'namespace': f'kytos.topology.{entities}.metadata',
734
                   'callback': self.request_retrieve_entities}
735 1
        event = KytosEvent(name=name, content=content)
736 1
        self.controller.buffers.app.put(event)
737 1
        log.info(f'verify data in storehouse for {entities}.')
738
739 1
    def request_retrieve_entities(self, event, data, _error):
740
        """Create a box or retrieve an existent box from storehouse."""
741 1
        msg = ''
742 1
        content = {'namespace': event.content.get('namespace'),
743
                   'callback': self.load_from_store,
744
                   'data': {}}
745
746 1
        if not data:
747 1
            name = 'kytos.storehouse.create'
748 1
            msg = 'Create new box in storehouse'
749
        else:
750 1
            name = 'kytos.storehouse.retrieve'
751 1
            content['box_id'] = data[0]
752 1
            msg = 'Retrieve data from storehouse.'
753
754 1
        event = KytosEvent(name=name, content=content)
755 1
        self.controller.buffers.app.put(event)
756 1
        log.debug(msg)
757
758 1
    def load_from_store(self, event, box, error):
759
        """Save the data retrived from storehouse."""
760
        entities = event.content.get('namespace', '').split('.')[-2]
761
        if error:
762
            log.error('Error while get a box from storehouse.')
763
        else:
764
            self.store_items[entities] = box
765
            log.debug('Data updated')
766
767 1
    def update_instance_metadata(self, obj):
768
        """Update object instance with saved metadata."""
769 1
        metadata = None
770 1
        if isinstance(obj, Interface):
771 1
            all_metadata = self.store_items.get('interfaces', None)
772 1
            if all_metadata:
773
                metadata = all_metadata.data.get(obj.id)
774
        elif isinstance(obj, Switch):
775
            all_metadata = self.store_items.get('switches', None)
776
            if all_metadata:
777
                metadata = all_metadata.data.get(obj.id)
778
        elif isinstance(obj, Link):
779
            all_metadata = self.store_items.get('links', None)
780
            if all_metadata:
781
                metadata = all_metadata.data.get(obj.id)
782
783 1
        if metadata:
784
            obj.extend_metadata(metadata)
785
            log.debug(f'Metadata to {obj.id} was updated')
786
787 1
    @listen_to('kytos/maintenance.start_link')
788
    def handle_link_maintenance_start(self, event):
789
        """Deals with the start of links maintenance."""
790 1
        notify_links = []
791 1
        maintenance_links = event.content['links']
792 1
        for maintenance_link in maintenance_links:
793 1
            try:
794 1
                link = self.links[maintenance_link.id]
795 1
            except KeyError:
796 1
                continue
797 1
            notify_links.append(link)
798 1
        for link in notify_links:
799 1
            link.disable()
800 1
            link.deactivate()
801 1
            link.endpoint_a.deactivate()
802 1
            link.endpoint_b.deactivate()
803 1
            link.endpoint_a.disable()
804 1
            link.endpoint_b.disable()
805 1
            self.notify_link_status_change(link)
806
807 1
    @listen_to('kytos/maintenance.end_link')
808
    def handle_link_maintenance_end(self, event):
809
        """Deals with the end of links maintenance."""
810 1
        notify_links = []
811 1
        maintenance_links = event.content['links']
812 1
        for maintenance_link in maintenance_links:
813 1
            try:
814 1
                link = self.links[maintenance_link.id]
815 1
            except KeyError:
816 1
                continue
817 1
            notify_links.append(link)
818 1
        for link in notify_links:
819 1
            link.enable()
820 1
            link.activate()
821 1
            link.endpoint_a.activate()
822 1
            link.endpoint_b.activate()
823 1
            link.endpoint_a.enable()
824 1
            link.endpoint_b.enable()
825
            self.notify_link_status_change(link)
826