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