Passed
Pull Request — master (#123)
by
unknown
02:09
created

build.main   F

Complexity

Total Complexity 150

Size/Duplication

Total Lines 818
Duplicated Lines 7.09 %

Test Coverage

Coverage 87.26%

Importance

Changes 0
Metric Value
eloc 577
dl 58
loc 818
rs 2
c 0
b 0
f 0
ccs 459
cts 526
cp 0.8726
wmc 150

58 Methods

Rating   Name   Duplication   Size   Complexity  
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
B Main.update_instance_metadata() 0 19 8
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
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._get_switches_dict() 0 12 3
A Main._restore_links() 0 18 4
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.shutdown() 0 3 1
A Main.enable_link() 0 9 2
A Main.handle_link_down() 0 8 3
A Main.setup() 0 18 1
A Main.handle_new_switch() 0 13 1
A Main.execute() 0 3 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
B Main._restore_switches() 0 40 7
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 21 4
A Main.get_topology() 0 7 1
A Main.handle_interface_link_down() 0 8 1
A Main._get_links_dict() 0 4 1
A Main.add_links() 0 15 1
A Main.handle_interface_up() 0 9 1
A Main.handle_interface_deleted() 0 4 1
A Main._get_link_or_create() 0 9 3
A Main.restore_network_status() 0 11 5
A Main._get_link_from_interface() 0 6 3
A Main.add_link_metadata() 0 12 2
A Main.delete_switch_metadata() 0 11 2
A Main._get_topology_dict() 0 4 1
A Main.get_link_metadata() 0 7 2
A Main._get_topology() 0 3 1

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