Passed
Pull Request — master (#111)
by
unknown
02:45
created

build.main   F

Complexity

Total Complexity 143

Size/Duplication

Total Lines 772
Duplicated Lines 7.25 %

Test Coverage

Coverage 89.16%

Importance

Changes 0
Metric Value
eloc 539
dl 56
loc 772
ccs 436
cts 489
cp 0.8916
rs 2
c 0
b 0
f 0
wmc 143

57 Methods

Rating   Name   Duplication   Size   Complexity  
A Main.shutdown() 0 3 1
A Main.setup() 0 12 1
A Main.execute() 0 2 1
A Main._get_topology() 0 3 1
B Main._restore_status() 0 31 7
A Main.disable_switch() 0 9 2
A Main.disable_link() 0 9 2
A Main.enable_switch() 0 9 2
B Main.enable_interface() 28 28 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() 28 28 7
A Main.handle_switch_maintenance_start() 0 11 4
A Main._load_network_status() 0 22 4
A Main.handle_interface_link_down() 0 8 1
A Main.add_links() 0 14 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._get_switches_dict() 0 12 3
A Main._get_links_dict() 0 4 1
A Main._get_link_or_create() 0 9 3
A Main._get_link_from_interface() 0 6 3
A Main._get_topology_dict() 0 4 1
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 12 2
A Main.update_instance() 0 8 2
A Main.get_topology() 0 7 1
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

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
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 1
        new_link = Link(endpoint_a, endpoint_b)
49
50 1
        for link in self.links.values():
51
            if new_link == link:
52
                return link
53
54 1
        self.links[new_link.id] = new_link
55 1
        return new_link
56
57 1
    def _get_switches_dict(self):
58
        """Return a dictionary with the known switches."""
59 1
        switches = {'switches': {}}
60 1
        for idx, switch in enumerate(self.controller.switches.values()):
61 1
            switch_data = switch.as_dict()
62 1
            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 1
            switches['switches'][switch.id] = switch_data
68 1
        return switches
69
70 1
    def _get_links_dict(self):
71
        """Return a dictionary with the known links."""
72 1
        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 1
        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 1
        for link in self.links.values():
87 1
            if interface in (link.endpoint_a, link.endpoint_b):
88 1
                return link
89 1
        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 1
        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 (KeyError, 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'])
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
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'])
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
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
        if event:
592
            content = event.content
593
            log.info(f"Storing the administrative state of the"
594
                     f" {content['attribute']} attribute to"
595
                     f" {content['state']} in the interfaces"
596
                     f" {content['interface_ids']}")
597 1
        self.storehouse.save_status(status)
598
599 1
    def notify_topology_update(self):
600
        """Send an event to notify about updates on the topology."""
601 1
        name = 'kytos/topology.updated'
602 1
        event = KytosEvent(name=name, content={'topology':
603
                                               self._get_topology()})
604 1
        self.controller.buffers.app.put(event)
605
606 1
    def notify_link_status_change(self, link):
607
        """Send an event to notify about a status change on a link."""
608 1
        name = 'kytos/topology.'
609 1
        if link.is_active():
610 1
            status = 'link_up'
611
        else:
612
            status = 'link_down'
613 1
        event = KytosEvent(name=name+status, content={'link': link})
614 1
        self.controller.buffers.app.put(event)
615
616 1
    def notify_metadata_changes(self, obj, action):
617
        """Send an event to notify about metadata changes."""
618 1
        if isinstance(obj, Switch):
619 1
            entity = 'switch'
620 1
            entities = 'switches'
621 1
        elif isinstance(obj, Interface):
622 1
            entity = 'interface'
623 1
            entities = 'interfaces'
624
        elif isinstance(obj, Link):
625
            entity = 'link'
626
            entities = 'links'
627
628 1
        name = f'kytos/topology.{entities}.metadata.{action}'
629 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...
630
                                               'metadata': obj.metadata})
631 1
        self.controller.buffers.app.put(event)
632 1
        log.debug(f'Metadata from {obj.id} was {action}.')
633
634 1
    @listen_to('.*.switch.port.created')
635
    def notify_port_created(self, original_event):
636
        """Notify when a port is created."""
637 1
        name = 'kytos/topology.port.created'
638 1
        event = KytosEvent(name=name, content=original_event.content)
639 1
        self.controller.buffers.app.put(event)
640
641 1
    @listen_to('kytos/topology.*.metadata.*')
642
    def save_metadata_on_store(self, event):
643
        """Send to storehouse the data updated."""
644 1
        name = 'kytos.storehouse.update'
645 1
        if 'switch' in event.content:
646 1
            store = self.store_items.get('switches')
647 1
            obj = event.content.get('switch')
648 1
            namespace = 'kytos.topology.switches.metadata'
649 1
        elif 'interface' in event.content:
650 1
            store = self.store_items.get('interfaces')
651 1
            obj = event.content.get('interface')
652 1
            namespace = 'kytos.topology.iterfaces.metadata'
653 1
        elif 'link' in event.content:
654 1
            store = self.store_items.get('links')
655 1
            obj = event.content.get('link')
656 1
            namespace = 'kytos.topology.links.metadata'
657
658 1
        store.data[obj.id] = obj.metadata
0 ignored issues
show
introduced by
The variable obj does not seem to be defined for all execution paths.
Loading history...
introduced by
The variable store does not seem to be defined for all execution paths.
Loading history...
659 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...
660
                   'box_id': store.box_id,
661
                   'data': store.data,
662
                   'callback': self.update_instance}
663
664 1
        event = KytosEvent(name=name, content=content)
665 1
        self.controller.buffers.app.put(event)
666
667 1
    @staticmethod
668
    def update_instance(event, _data, error):
669
        """Display in Kytos console if the data was updated."""
670
        entities = event.content.get('namespace', '').split('.')[-2]
671
        if error:
672
            log.error(f'Error trying to update storehouse {entities}.')
673
        else:
674
            log.debug(f'Storehouse update to entities: {entities}.')
675
676 1
    def verify_storehouse(self, entities):
677
        """Request a list of box saved by specific entity."""
678 1
        name = 'kytos.storehouse.list'
679 1
        content = {'namespace': f'kytos.topology.{entities}.metadata',
680
                   'callback': self.request_retrieve_entities}
681 1
        event = KytosEvent(name=name, content=content)
682 1
        self.controller.buffers.app.put(event)
683 1
        log.info(f'verify data in storehouse for {entities}.')
684
685 1
    def request_retrieve_entities(self, event, data, _error):
686
        """Create a box or retrieve an existent box from storehouse."""
687 1
        msg = ''
688 1
        content = {'namespace': event.content.get('namespace'),
689
                   'callback': self.load_from_store,
690
                   'data': {}}
691
692 1
        if not data:
693 1
            name = 'kytos.storehouse.create'
694 1
            msg = 'Create new box in storehouse'
695
        else:
696 1
            name = 'kytos.storehouse.retrieve'
697 1
            content['box_id'] = data[0]
698 1
            msg = 'Retrieve data from storeohouse.'
699
700 1
        event = KytosEvent(name=name, content=content)
701 1
        self.controller.buffers.app.put(event)
702 1
        log.debug(msg)
703
704 1
    def load_from_store(self, event, box, error):
705
        """Save the data retrived from storehouse."""
706
        entities = event.content.get('namespace', '').split('.')[-2]
707
        if error:
708
            log.error('Error while get a box from storehouse.')
709
        else:
710
            self.store_items[entities] = box
711
            log.debug('Data updated')
712
713 1
    def update_instance_metadata(self, obj):
714
        """Update object instance with saved metadata."""
715
        metadata = None
716
        if isinstance(obj, Interface):
717
            all_metadata = self.store_items.get('interfaces', None)
718
            if all_metadata:
719
                metadata = all_metadata.data.get(obj.id)
720
        elif isinstance(obj, Switch):
721
            all_metadata = self.store_items.get('switches', None)
722
            if all_metadata:
723
                metadata = all_metadata.data.get(obj.id)
724
        elif isinstance(obj, Link):
725
            all_metadata = self.store_items.get('links', None)
726
            if all_metadata:
727
                metadata = all_metadata.data.get(obj.id)
728
729
        if metadata:
730
            obj.extend_metadata(metadata)
731
            log.debug(f'Metadata to {obj.id} was updated')
732
733 1
    @listen_to('kytos/maintenance.start_link')
734
    def handle_link_maintenance_start(self, event):
735
        """Deals with the start of links maintenance."""
736 1
        notify_links = []
737 1
        maintenance_links = event.content['links']
738 1
        for maintenance_link in maintenance_links:
739 1
            try:
740 1
                link = self.links[maintenance_link.id]
741 1
            except KeyError:
742 1
                continue
743 1
            notify_links.append(link)
744 1
        for link in notify_links:
745 1
            link.disable()
746 1
            link.deactivate()
747 1
            link.endpoint_a.deactivate()
748 1
            link.endpoint_b.deactivate()
749 1
            link.endpoint_a.disable()
750 1
            link.endpoint_b.disable()
751 1
            self.notify_link_status_change(link)
752
753 1
    @listen_to('kytos/maintenance.end_link')
754
    def handle_link_maintenance_end(self, event):
755
        """Deals with the end of links maintenance."""
756 1
        notify_links = []
757 1
        maintenance_links = event.content['links']
758 1
        for maintenance_link in maintenance_links:
759 1
            try:
760 1
                link = self.links[maintenance_link.id]
761 1
            except KeyError:
762 1
                continue
763 1
            notify_links.append(link)
764 1
        for link in notify_links:
765 1
            link.enable()
766 1
            link.activate()
767 1
            link.endpoint_a.activate()
768 1
            link.endpoint_b.activate()
769 1
            link.endpoint_a.enable()
770 1
            link.endpoint_b.enable()
771
            self.notify_link_status_change(link)
772