Passed
Pull Request — master (#38)
by Vinicius
02:27
created

build.main.Main.handle_interface_created()   A

Complexity

Conditions 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 2
nop 2
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
"""Main module of kytos/topology Kytos Network Application.
2
3
Manage the network topology
4
"""
5 1
import time
6 1
from threading import Lock
7
8 1
from flask import jsonify, request
9 1
from werkzeug.exceptions import BadRequest, UnsupportedMediaType
10
11 1
from kytos.core import KytosEvent, KytosNApp, log, rest
12 1
from kytos.core.exceptions import KytosLinkCreationError
13 1
from kytos.core.helpers import listen_to
14 1
from kytos.core.interface import Interface
15 1
from kytos.core.link import Link
16 1
from kytos.core.switch import Switch
17 1
from napps.kytos.topology import settings
18 1
from napps.kytos.topology.exceptions import RestoreError
19 1
from napps.kytos.topology.models import Topology
20 1
from napps.kytos.topology.storehouse import StoreHouse
21
22 1
DEFAULT_LINK_UP_TIMER = 10
23
24
25 1
class Main(KytosNApp):  # pylint: disable=too-many-public-methods
26
    """Main class of kytos/topology NApp.
27
28
    This class is the entry point for this napp.
29
    """
30
31 1
    def setup(self):
32
        """Initialize the NApp's links list."""
33 1
        self.links = {}
34 1
        self.store_items = {}
35 1
        self.link_up_timer = getattr(settings, 'LINK_UP_TIMER',
36
                                     DEFAULT_LINK_UP_TIMER)
37
38 1
        self.verify_storehouse('switches')
39 1
        self.verify_storehouse('interfaces')
40 1
        self.verify_storehouse('links')
41
42 1
        self.storehouse = StoreHouse(self.controller)
43
44 1
        self._lock = Lock()
45 1
        self._links_lock = Lock()
46
47
    # pylint: disable=unused-argument,arguments-differ
48 1
    @listen_to('kytos/storehouse.loaded')
49 1
    def execute(self, event=None):
50
        """Execute once when the napp is running."""
51
        with self._lock:
52
            self._load_network_status()
53
54 1
    def shutdown(self):
55
        """Do nothing."""
56
        log.info('NApp kytos/topology shutting down.')
57
58 1
    @staticmethod
59
    def _get_metadata():
60
        """Return a JSON with metadata."""
61 1
        try:
62 1
            metadata = request.get_json()
63 1
            content_type = request.content_type
64 1
        except BadRequest:
65 1
            result = 'The request body is not a well-formed JSON.'
66 1
            raise BadRequest(result)
67 1
        if content_type is None:
68
            result = 'The request body is empty.'
69
            raise BadRequest(result)
70 1
        if metadata is None:
71 1
            if content_type != 'application/json':
72
                result = ('The content type must be application/json '
73
                          f'(received {content_type}).')
74
            else:
75 1
                result = 'Metadata is empty.'
76 1
            raise UnsupportedMediaType(result)
77 1
        return metadata
78
79 1
    def _get_link_or_create(self, endpoint_a, endpoint_b):
80
        """Get an existing link or create a new one.
81
82
        Returns:
83
            Tuple(Link, bool): Link and a boolean whether it has been created.
84
        """
85 1
        new_link = Link(endpoint_a, endpoint_b)
86
87 1
        for link in self.links.values():
88 1
            if new_link == link:
89 1
                return (link, False)
90
91 1
        self.links[new_link.id] = new_link
92 1
        return (new_link, True)
93
94 1
    def _get_switches_dict(self):
95
        """Return a dictionary with the known switches."""
96 1
        switches = {'switches': {}}
97 1
        for idx, switch in enumerate(self.controller.switches.values()):
98 1
            switch_data = switch.as_dict()
99 1
            if not all(key in switch_data['metadata']
100
                       for key in ('lat', 'lng')):
101
                # Switches are initialized somewhere in the ocean
102
                switch_data['metadata']['lat'] = str(0.0)
103
                switch_data['metadata']['lng'] = str(-30.0+idx*10.0)
104 1
            switches['switches'][switch.id] = switch_data
105 1
        return switches
106
107 1
    def _get_links_dict(self):
108
        """Return a dictionary with the known links."""
109 1
        return {'links': {l.id: l.as_dict() for l in
110
                          self.links.values()}}
111
112 1
    def _get_topology_dict(self):
113
        """Return a dictionary with the known topology."""
114 1
        return {'topology': {**self._get_switches_dict(),
115
                             **self._get_links_dict()}}
116
117 1
    def _get_topology(self):
118
        """Return an object representing the topology."""
119 1
        return Topology(self.controller.switches, self.links)
120
121 1
    def _get_link_from_interface(self, interface):
122
        """Return the link of the interface, or None if it does not exist."""
123 1
        for link in self.links.values():
124 1
            if interface in (link.endpoint_a, link.endpoint_b):
125 1
                return link
126 1
        return None
127
128 1
    def _load_link(self, link_att):
129 1
        dpid_a = link_att['endpoint_a']['switch']
130 1
        dpid_b = link_att['endpoint_b']['switch']
131 1
        port_a = link_att['endpoint_a']['port_number']
132 1
        port_b = link_att['endpoint_b']['port_number']
133 1
        link_str = f'{dpid_a}:{port_a}-{dpid_b}:{port_b}'
134 1
        log.info(f'Loading link from storehouse {link_str}')
135
136 1
        try:
137 1
            switch_a = self.controller.switches[dpid_a]
138 1
            switch_b = self.controller.switches[dpid_b]
139 1
            interface_a = switch_a.interfaces[port_a]
140 1
            interface_b = switch_b.interfaces[port_b]
141 1
        except Exception as err:
142 1
            error = f'Fail to load endpoints for link {link_str}: {err}'
143 1
            raise RestoreError(error)
144
145 1
        with self._links_lock:
146 1
            link, _ = self._get_link_or_create(interface_a, interface_b)
147
148 1
        if link_att['enabled']:
149 1
            link.enable()
150
        else:
151 1
            link.disable()
152
153 1
        interface_a.update_link(link)
154 1
        interface_b.update_link(link)
155 1
        interface_a.nni = True
156 1
        interface_b.nni = True
157 1
        self.update_instance_metadata(link)
158
159 1
    def _load_switch(self, switch_id, switch_att):
160 1
        log.info(f'Loading switch from storehouse dpid={switch_id}')
161 1
        switch = self.controller.get_switch_or_create(switch_id)
162 1
        if switch_att['enabled']:
163 1
            switch.enable()
164
        else:
165 1
            switch.disable()
166 1
        switch.description['manufacturer'] = switch_att.get('manufacturer', '')
167 1
        switch.description['hardware'] = switch_att.get('hardware', '')
168 1
        switch.description['software'] = switch_att.get('software')
169 1
        switch.description['serial'] = switch_att.get('serial', '')
170 1
        switch.description['data_path'] = switch_att.get('data_path', '')
171 1
        self.update_instance_metadata(switch)
172
173 1
        for iface_id, iface_att in switch_att.get('interfaces', {}).items():
174 1
            log.info(f'Loading interface iface_id={iface_id}')
175 1
            interface = switch.update_or_create_interface(
176
                            port_no=iface_att['port_number'],
177
                            name=iface_att['name'],
178
                            address=iface_att.get('mac', None),
179
                            speed=iface_att.get('speed', None))
180 1
            if iface_att['enabled']:
181 1
                interface.enable()
182
            else:
183 1
                interface.disable()
184 1
            interface.lldp = iface_att['lldp']
185 1
            self.update_instance_metadata(interface)
186 1
            name = 'kytos/topology.port.created'
187 1
            event = KytosEvent(name=name, content={
188
                                              'switch': switch_id,
189
                                              'port': interface.port_number,
190
                                              'port_description': {
191
                                                  'alias': interface.name,
192
                                                  'mac': interface.address,
193
                                                  'state': interface.state
194
                                                  }
195
                                              })
196 1
            self.controller.buffers.app.put(event)
197
198
    # pylint: disable=attribute-defined-outside-init
199 1
    def _load_network_status(self):
200
        """Load network status saved in storehouse."""
201 1
        try:
202 1
            status = self.storehouse.get_data()
203 1
        except FileNotFoundError as error:
204 1
            log.error(f'Fail to load network status from storehouse: {error}')
205 1
            return
206
207 1
        if not status:
208 1
            log.info('There is no status saved to restore.')
209 1
            return
210
211 1
        switches = status['network_status']['switches']
212 1
        links = status['network_status']['links']
213
214 1
        failed_switches = {}
215 1
        log.debug("_load_network_status switches=%s" % switches)
216 1
        for switch_id, switch_att in switches.items():
217 1
            try:
218 1
                self._load_switch(switch_id, switch_att)
219
            # pylint: disable=broad-except
220 1
            except Exception as err:
221 1
                failed_switches[switch_id] = err
222 1
                log.error(f'Error loading switch: {err}')
223
224 1
        failed_links = {}
225 1
        log.debug("_load_network_status links=%s" % links)
226 1
        for link_id, link_att in links.items():
227 1
            try:
228 1
                self._load_link(link_att)
229
            # pylint: disable=broad-except
230 1
            except Exception as err:
231 1
                failed_links[link_id] = err
232 1
                log.error(f'Error loading link {link_id}: {err}')
233
234 1
        name = 'kytos/topology.topology_loaded'
235 1
        event = KytosEvent(
236
            name=name,
237
            content={
238
                'topology': self._get_topology(),
239
                'failed_switches': failed_switches,
240
                'failed_links': failed_links
241
            })
242 1
        self.controller.buffers.app.put(event)
243
244 1
    @rest('v3/')
245
    def get_topology(self):
246
        """Return the latest known topology.
247
248
        This topology is updated when there are network events.
249
        """
250 1
        return jsonify(self._get_topology_dict())
251
252
    # Switch related methods
253 1
    @rest('v3/switches')
254
    def get_switches(self):
255
        """Return a json with all the switches in the topology."""
256
        return jsonify(self._get_switches_dict())
257
258 1
    @rest('v3/switches/<dpid>/enable', methods=['POST'])
259
    def enable_switch(self, dpid):
260
        """Administratively enable a switch in the topology."""
261 1
        try:
262 1
            self.controller.switches[dpid].enable()
263 1
        except KeyError:
264 1
            return jsonify("Switch not found"), 404
265
266 1
        log.info(f"Storing administrative state from switch {dpid}"
267
                 " to enabled.")
268 1
        self.save_status_on_storehouse()
269 1
        self.notify_switch_enabled(dpid)
270 1
        return jsonify("Operation successful"), 201
271
272 1
    @rest('v3/switches/<dpid>/disable', methods=['POST'])
273
    def disable_switch(self, dpid):
274
        """Administratively disable a switch in the topology."""
275 1
        try:
276 1
            self.controller.switches[dpid].disable()
277 1
        except KeyError:
278 1
            return jsonify("Switch not found"), 404
279
280 1
        log.info(f"Storing administrative state from switch {dpid}"
281
                 " to disabled.")
282 1
        self.save_status_on_storehouse()
283 1
        self.notify_switch_disabled(dpid)
284 1
        return jsonify("Operation successful"), 201
285
286 1
    @rest('v3/switches/<dpid>/metadata')
287
    def get_switch_metadata(self, dpid):
288
        """Get metadata from a switch."""
289 1
        try:
290 1
            return jsonify({"metadata":
291
                            self.controller.switches[dpid].metadata}), 200
292 1
        except KeyError:
293 1
            return jsonify("Switch not found"), 404
294
295 1
    @rest('v3/switches/<dpid>/metadata', methods=['POST'])
296
    def add_switch_metadata(self, dpid):
297
        """Add metadata to a switch."""
298 1
        metadata = self._get_metadata()
299
300 1
        try:
301 1
            switch = self.controller.switches[dpid]
302 1
        except KeyError:
303 1
            return jsonify("Switch not found"), 404
304
305 1
        switch.extend_metadata(metadata)
306 1
        self.notify_metadata_changes(switch, 'added')
307 1
        return jsonify("Operation successful"), 201
308
309 1
    @rest('v3/switches/<dpid>/metadata/<key>', methods=['DELETE'])
310
    def delete_switch_metadata(self, dpid, key):
311
        """Delete metadata from a switch."""
312 1
        try:
313 1
            switch = self.controller.switches[dpid]
314 1
        except KeyError:
315 1
            return jsonify("Switch not found"), 404
316
317 1
        switch.remove_metadata(key)
318 1
        self.notify_metadata_changes(switch, 'removed')
319 1
        return jsonify("Operation successful"), 200
320
321
    # Interface related methods
322 1
    @rest('v3/interfaces')
323
    def get_interfaces(self):
324
        """Return a json with all the interfaces in the topology."""
325
        interfaces = {}
326
        switches = self._get_switches_dict()
327
        for switch in switches['switches'].values():
328
            for interface_id, interface in switch['interfaces'].items():
329
                interfaces[interface_id] = interface
330
331
        return jsonify({'interfaces': interfaces})
332
333 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...
334 1
    @rest('v3/interfaces/<interface_enable_id>/enable', methods=['POST'])
335 1
    def enable_interface(self, interface_enable_id=None, dpid=None):
336
        """Administratively enable interfaces in the topology."""
337 1
        error_list = []  # List of interfaces that were not activated.
338 1
        msg_error = "Some interfaces couldn't be found and activated: "
339 1
        if dpid is None:
340 1
            dpid = ":".join(interface_enable_id.split(":")[:-1])
341 1
        try:
342 1
            switch = self.controller.switches[dpid]
343 1
        except KeyError as exc:
344 1
            return jsonify(f"Switch not found: {exc}"), 404
345
346 1
        if interface_enable_id:
347 1
            interface_number = int(interface_enable_id.split(":")[-1])
348
349 1
            try:
350 1
                switch.interfaces[interface_number].enable()
351 1
            except KeyError as exc:
352 1
                error_list.append(f"Switch {dpid} Interface {exc}")
353
        else:
354 1
            for interface in switch.interfaces.values():
355 1
                interface.enable()
356 1
        if not error_list:
357 1
            log.info(f"Storing administrative state for enabled interfaces.")
358 1
            self.save_status_on_storehouse()
359 1
            return jsonify("Operation successful"), 200
360 1
        return jsonify({msg_error:
361
                        error_list}), 409
362
363 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...
364 1
    @rest('v3/interfaces/<interface_disable_id>/disable', methods=['POST'])
365 1
    def disable_interface(self, interface_disable_id=None, dpid=None):
366
        """Administratively disable interfaces in the topology."""
367 1
        error_list = []  # List of interfaces that were not deactivated.
368 1
        msg_error = "Some interfaces couldn't be found and deactivated: "
369 1
        if dpid is None:
370 1
            dpid = ":".join(interface_disable_id.split(":")[:-1])
371 1
        try:
372 1
            switch = self.controller.switches[dpid]
373 1
        except KeyError as exc:
374 1
            return jsonify(f"Switch not found: {exc}"), 404
375
376 1
        if interface_disable_id:
377 1
            interface_number = int(interface_disable_id.split(":")[-1])
378
379 1
            try:
380 1
                switch.interfaces[interface_number].disable()
381 1
            except KeyError as exc:
382 1
                error_list.append(f"Switch {dpid} Interface {exc}")
383
        else:
384 1
            for interface in switch.interfaces.values():
385 1
                interface.disable()
386 1
        if not error_list:
387 1
            log.info(f"Storing administrative state for disabled interfaces.")
388 1
            self.save_status_on_storehouse()
389 1
            return jsonify("Operation successful"), 200
390 1
        return jsonify({msg_error:
391
                        error_list}), 409
392
393 1
    @rest('v3/interfaces/<interface_id>/metadata')
394
    def get_interface_metadata(self, interface_id):
395
        """Get metadata from an interface."""
396 1
        switch_id = ":".join(interface_id.split(":")[:-1])
397 1
        interface_number = int(interface_id.split(":")[-1])
398 1
        try:
399 1
            switch = self.controller.switches[switch_id]
400 1
        except KeyError:
401 1
            return jsonify("Switch not found"), 404
402
403 1
        try:
404 1
            interface = switch.interfaces[interface_number]
405 1
        except KeyError:
406 1
            return jsonify("Interface not found"), 404
407
408 1
        return jsonify({"metadata": interface.metadata}), 200
409
410 1 View Code Duplication
    @rest('v3/interfaces/<interface_id>/metadata', methods=['POST'])
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
411
    def add_interface_metadata(self, interface_id):
412
        """Add metadata to an interface."""
413 1
        metadata = self._get_metadata()
414 1
        switch_id = ":".join(interface_id.split(":")[:-1])
415 1
        interface_number = int(interface_id.split(":")[-1])
416 1
        try:
417 1
            switch = self.controller.switches[switch_id]
418 1
        except KeyError:
419 1
            return jsonify("Switch not found"), 404
420
421 1
        try:
422 1
            interface = switch.interfaces[interface_number]
423 1
        except KeyError:
424 1
            return jsonify("Interface not found"), 404
425
426 1
        interface.extend_metadata(metadata)
427 1
        self.notify_metadata_changes(interface, 'added')
428 1
        return jsonify("Operation successful"), 201
429
430 1 View Code Duplication
    @rest('v3/interfaces/<interface_id>/metadata/<key>', methods=['DELETE'])
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
431
    def delete_interface_metadata(self, interface_id, key):
432
        """Delete metadata from an interface."""
433 1
        switch_id = ":".join(interface_id.split(":")[:-1])
434 1
        interface_number = int(interface_id.split(":")[-1])
435
436 1
        try:
437 1
            switch = self.controller.switches[switch_id]
438 1
        except KeyError:
439 1
            return jsonify("Switch not found"), 404
440
441 1
        try:
442 1
            interface = switch.interfaces[interface_number]
443 1
        except KeyError:
444 1
            return jsonify("Interface not found"), 404
445
446 1
        if interface.remove_metadata(key) is False:
447 1
            return jsonify("Metadata not found"), 404
448
449 1
        self.notify_metadata_changes(interface, 'removed')
450 1
        return jsonify("Operation successful"), 200
451
452
    # Link related methods
453 1
    @rest('v3/links')
454
    def get_links(self):
455
        """Return a json with all the links in the topology.
456
457
        Links are connections between interfaces.
458
        """
459
        return jsonify(self._get_links_dict()), 200
460
461 1
    @rest('v3/links/<link_id>/enable', methods=['POST'])
462
    def enable_link(self, link_id):
463
        """Administratively enable a link in the topology."""
464 1
        try:
465 1
            with self._links_lock:
466 1
                self.links[link_id].enable()
467 1
        except KeyError:
468 1
            return jsonify("Link not found"), 404
469 1
        self.save_status_on_storehouse()
470 1
        self.notify_link_status_change(
471
            self.links[link_id],
472
            reason='link enabled'
473
        )
474 1
        return jsonify("Operation successful"), 201
475
476 1
    @rest('v3/links/<link_id>/disable', methods=['POST'])
477
    def disable_link(self, link_id):
478
        """Administratively disable a link in the topology."""
479 1
        try:
480 1
            with self._links_lock:
481 1
                self.links[link_id].disable()
482 1
        except KeyError:
483 1
            return jsonify("Link not found"), 404
484 1
        self.save_status_on_storehouse()
485 1
        self.notify_link_status_change(
486
            self.links[link_id],
487
            reason='link disabled'
488
        )
489 1
        return jsonify("Operation successful"), 201
490
491 1
    @rest('v3/links/<link_id>/metadata')
492
    def get_link_metadata(self, link_id):
493
        """Get metadata from a link."""
494 1
        try:
495 1
            return jsonify({"metadata": self.links[link_id].metadata}), 200
496 1
        except KeyError:
497 1
            return jsonify("Link not found"), 404
498
499 1
    @rest('v3/links/<link_id>/metadata', methods=['POST'])
500
    def add_link_metadata(self, link_id):
501
        """Add metadata to a link."""
502 1
        metadata = self._get_metadata()
503 1
        try:
504 1
            link = self.links[link_id]
505 1
        except KeyError:
506 1
            return jsonify("Link not found"), 404
507
508 1
        link.extend_metadata(metadata)
509 1
        self.notify_metadata_changes(link, 'added')
510 1
        return jsonify("Operation successful"), 201
511
512 1
    @rest('v3/links/<link_id>/metadata/<key>', methods=['DELETE'])
513
    def delete_link_metadata(self, link_id, key):
514
        """Delete metadata from a link."""
515 1
        try:
516 1
            link = self.links[link_id]
517 1
        except KeyError:
518 1
            return jsonify("Link not found"), 404
519
520 1
        if link.remove_metadata(key) is False:
521 1
            return jsonify("Metadata not found"), 404
522
523 1
        self.notify_metadata_changes(link, 'removed')
524 1
        return jsonify("Operation successful"), 200
525
526 1
    @listen_to('.*.switch.(new|reconnected)')
527
    def on_new_switch(self, event):
528
        """Create a new Device on the Topology.
529
530
        Handle the event of a new created switch and update the topology with
531
        this new device. Also notify if the switch is enabled.
532
        """
533
        self.handle_new_switch(event)
534
535 1
    def handle_new_switch(self, event):
536
        """Create a new Device on the Topology."""
537 1
        switch = event.content['switch']
538 1
        switch.activate()
539 1
        log.debug('Switch %s added to the Topology.', switch.id)
540 1
        self.notify_topology_update()
541 1
        self.update_instance_metadata(switch)
542 1
        if switch.is_enabled():
543 1
            self.notify_switch_enabled(switch.id)
544
545 1
    @listen_to('.*.connection.lost')
546
    def on_connection_lost(self, event):
547
        """Remove a Device from the topology.
548
549
        Remove the disconnected Device and every link that has one of its
550
        interfaces.
551
        """
552
        self.handle_connection_lost(event)
553
554 1
    def handle_connection_lost(self, event):
555
        """Remove a Device from the topology."""
556 1
        switch = event.content['source'].switch
557 1
        if switch:
558 1
            switch.deactivate()
559 1
            log.debug('Switch %s removed from the Topology.', switch.id)
560 1
            self.notify_topology_update()
561
562 1
    def handle_interface_up(self, event):
563
        """Update the topology based on a Port Modify event.
564
565
        The event notifies that an interface was changed to 'up'.
566
        """
567 1
        interface = event.content['interface']
568 1
        interface.activate()
569 1
        self.notify_topology_update()
570 1
        self.update_instance_metadata(interface)
571
572 1
    @listen_to('.*.switch.interface.created')
573
    def on_interface_created(self, event):
574
        """Update the topology based on a Port Create event.
575
576
        It's handled as a link_up in case a switch send a
577
        created event again and it can be belong to a link.
578
        """
579
        self.handle_link_up(event.content['interface'])
580
581 1
    def handle_interface_down(self, event):
582
        """Update the topology based on a Port Modify event.
583
584
        The event notifies that an interface was changed to 'down'.
585
        """
586 1
        interface = event.content['interface']
587 1
        interface.deactivate()
588 1
        self.handle_interface_link_down(interface)
589 1
        self.notify_topology_update()
590
591 1
    @listen_to('.*.switch.interface.deleted')
592
    def on_interface_deleted(self, event):
593
        """Update the topology based on a Port Delete event."""
594
        self.handle_interface_deleted(event)
595
596 1
    def handle_interface_deleted(self, event):
597
        """Update the topology based on a Port Delete event."""
598 1
        self.handle_interface_down(event)
599
600 1
    @listen_to('.*.switch.interface.link_up')
601
    def on_interface_link_up(self, event):
602
        """Update the topology based on a Port Modify event.
603
604
        The event notifies that an interface's link was changed to 'up'.
605
        """
606
        interface = event.content['interface']
607
        self.handle_interface_link_up(interface)
608
609 1
    def handle_interface_link_up(self, interface):
610
        """Update the topology based on a Port Modify event."""
611 1
        self.handle_link_up(interface)
612
613 1
    @listen_to('kytos/maintenance.end_switch')
614
    def on_switch_maintenance_end(self, event):
615
        """Handle the end of the maintenance of a switch."""
616
        self.handle_switch_maintenance_end(event)
617
618 1
    def handle_switch_maintenance_end(self, event):
619
        """Handle the end of the maintenance of a switch."""
620 1
        switches = event.content['switches']
621 1
        for switch in switches:
622 1
            switch.enable()
623 1
            switch.activate()
624 1
            for interface in switch.interfaces.values():
625 1
                interface.enable()
626 1
                self.handle_link_up(interface)
627
628 1
    def handle_link_up(self, interface):
629
        """Notify a link is up."""
630 1
        interface.activate()
631 1
        with self._links_lock:
632 1
            link = self._get_link_from_interface(interface)
633 1
        if not link:
634
            return
635 1
        if link.endpoint_a == interface:
636 1
            other_interface = link.endpoint_b
637
        else:
638 1
            other_interface = link.endpoint_a
639 1
        if other_interface.is_active() is False:
640 1
            return
641 1
        if link.is_active() is False:
642 1
            link.update_metadata('last_status_change', time.time())
643 1
            link.activate()
644
645
            # As each run of this method uses a different thread,
646
            # there is no risk this sleep will lock the NApp.
647 1
            time.sleep(self.link_up_timer)
648
649 1
            last_status_change = link.get_metadata('last_status_change')
650 1
            now = time.time()
651 1
            if link.is_active() and \
652
                    now - last_status_change >= self.link_up_timer:
653 1
                self.notify_topology_update()
654 1
                self.update_instance_metadata(link)
655 1
                self.notify_link_status_change(link, reason='link up')
656
        else:
657 1
            link.update_metadata('last_status_change', time.time())
658 1
            self.notify_topology_update()
659 1
            self.update_instance_metadata(link)
660 1
            self.notify_link_status_change(link, reason='link up')
661
662 1
    @listen_to('.*.switch.interface.link_down')
663
    def on_interface_link_down(self, event):
664
        """Update the topology based on a Port Modify event.
665
666
        The event notifies that an interface's link was changed to 'down'.
667
        """
668
        interface = event.content['interface']
669
        self.handle_interface_link_down(interface)
670
671 1
    def handle_interface_link_down(self, interface):
672
        """Update the topology based on an interface."""
673 1
        self.handle_link_down(interface)
674
675 1
    @listen_to('kytos/maintenance.start_switch')
676
    def on_switch_maintenance_start(self, event):
677
        """Handle the start of the maintenance of a switch."""
678
        self.handle_switch_maintenance_start(event)
679
680 1
    def handle_switch_maintenance_start(self, event):
681
        """Handle the start of the maintenance of a switch."""
682 1
        switches = event.content['switches']
683 1
        for switch in switches:
684 1
            switch.disable()
685 1
            switch.deactivate()
686 1
            for interface in switch.interfaces.values():
687 1
                interface.disable()
688 1
                if interface.is_active():
689 1
                    self.handle_link_down(interface)
690
691 1
    def handle_link_down(self, interface):
692
        """Notify a link is down."""
693 1
        link = self._get_link_from_interface(interface)
694 1
        if link and link.is_active():
695 1
            link.deactivate()
696 1
            link.update_metadata('last_status_change', time.time())
697 1
            self.notify_topology_update()
698 1
            self.notify_link_status_change(link, reason='link down')
699 1
        interface.deactivate()
700
701 1
    @listen_to('.*.interface.is.nni')
702
    def on_add_links(self, event):
703
        """Update the topology with links related to the NNI interfaces."""
704
        self.add_links(event)
705
706 1
    def add_links(self, event):
707
        """Update the topology with links related to the NNI interfaces."""
708 1
        interface_a = event.content['interface_a']
709 1
        interface_b = event.content['interface_b']
710
711 1
        try:
712 1
            with self._links_lock:
713 1
                link, created = self._get_link_or_create(interface_a,
714
                                                         interface_b)
715 1
                interface_a.update_link(link)
716 1
                interface_b.update_link(link)
717
718 1
                link.endpoint_a = interface_a
719 1
                link.endpoint_b = interface_b
720
721 1
                interface_a.nni = True
722 1
                interface_b.nni = True
723
724
        except KytosLinkCreationError as err:
725
            log.error(f'Error creating link: {err}.')
726
            return
727
728 1
        if created:
729 1
            self.notify_topology_update()
730
731
    # def add_host(self, event):
732
    #    """Update the topology with a new Host."""
733
734
    #    interface = event.content['port']
735
    #    mac = event.content['reachable_mac']
736
737
    #    host = Host(mac)
738
    #    link = self.topology.get_link(interface.id)
739
    #    if link is not None:
740
    #        return
741
742
    #    self.topology.add_link(interface.id, host.id)
743
    #    self.topology.add_device(host)
744
745
    #    if settings.DISPLAY_FULL_DUPLEX_LINKS:
746
    #        self.topology.add_link(host.id, interface.id)
747
748 1
    @listen_to('.*.network_status.updated')
749
    def on_network_status_updated(self, event):
750
        """Handle *.network_status.updated events, specially from of_lldp."""
751
        content = event.content
752
        log.info(f"Storing the administrative state of the"
753
                 f" {content['attribute']} attribute to"
754
                 f" {content['state']} in the interfaces"
755
                 f" {content['interface_ids']}")
756
        self.handle_network_status_updated()
757
758 1
    def handle_network_status_updated(self) -> None:
759
        """Handle *.network_status.updated events, specially from of_lldp."""
760 1
        self.save_status_on_storehouse()
761
762 1
    def save_status_on_storehouse(self):
763
        """Save the network administrative status using storehouse."""
764 1
        with self._lock:
765 1
            status = self._get_switches_dict()
766 1
            status['id'] = 'network_status'
767 1
            status.update(self._get_links_dict())
768 1
            self.storehouse.save_status(status)
769
770 1
    def notify_switch_enabled(self, dpid):
771
        """Send an event to notify that a switch is enabled."""
772 1
        name = 'kytos/topology.switch.enabled'
773 1
        event = KytosEvent(name=name, content={'dpid': dpid})
774 1
        self.controller.buffers.app.put(event)
775
776 1
    def notify_switch_disabled(self, dpid):
777
        """Send an event to notify that a switch is disabled."""
778 1
        name = 'kytos/topology.switch.disabled'
779 1
        event = KytosEvent(name=name, content={'dpid': dpid})
780 1
        self.controller.buffers.app.put(event)
781
782 1
    def notify_topology_update(self):
783
        """Send an event to notify about updates on the topology."""
784 1
        name = 'kytos/topology.updated'
785 1
        event = KytosEvent(name=name, content={'topology':
786
                                               self._get_topology()})
787 1
        self.controller.buffers.app.put(event)
788
789 1
    def notify_link_status_change(self, link, reason='not given'):
790
        """Send an event to notify about a status change on a link."""
791 1
        name = 'kytos/topology.'
792 1
        if link.is_active() and link.is_enabled():
793 1
            status = 'link_up'
794
        else:
795
            status = 'link_down'
796 1
        event = KytosEvent(
797
            name=name+status,
798
            content={
799
                'link': link,
800
                'reason': reason
801
            })
802 1
        self.controller.buffers.app.put(event)
803
804 1
    def notify_metadata_changes(self, obj, action):
805
        """Send an event to notify about metadata changes."""
806 1
        if isinstance(obj, Switch):
807 1
            entity = 'switch'
808 1
            entities = 'switches'
809 1
        elif isinstance(obj, Interface):
810 1
            entity = 'interface'
811 1
            entities = 'interfaces'
812 1
        elif isinstance(obj, Link):
813 1
            entity = 'link'
814 1
            entities = 'links'
815
        else:
816 1
            raise ValueError(
817
                'Invalid object, supported: Switch, Interface, Link'
818
            )
819
820 1
        self.save_metadata_on_store(obj, entities)
821
822 1
        name = f'kytos/topology.{entities}.metadata.{action}'
823 1
        event = KytosEvent(name=name, content={entity: obj,
824
                                               'metadata': obj.metadata})
825 1
        self.controller.buffers.app.put(event)
826 1
        log.debug(f'Metadata from {obj.id} was {action}.')
827
828 1
    @listen_to('.*.switch.port.created')
829
    def on_notify_port_created(self, event):
830
        """Notify when a port is created."""
831
        self.notify_port_created(event)
832
833 1
    def notify_port_created(self, event):
834
        """Notify when a port is created."""
835 1
        name = 'kytos/topology.port.created'
836 1
        event = KytosEvent(name=name, content=event.content)
837 1
        self.controller.buffers.app.put(event)
838
839 1
    def save_metadata_on_store(self, obj, entities):
840
        """Send to storehouse the data updated."""
841 1
        name = 'kytos.storehouse.update'
842 1
        store = self.store_items.get(entities)
843 1
        namespace = f'kytos.topology.{entities}.metadata'
844
845 1
        store.data[obj.id] = obj.metadata
846 1
        content = {'namespace': namespace,
847
                   'box_id': store.box_id,
848
                   'data': store.data,
849
                   'callback': self.update_instance}
850
851 1
        event = KytosEvent(name=name, content=content)
852 1
        self.controller.buffers.app.put(event)
853
854 1
    @staticmethod
855
    def update_instance(event, _data, error):
856
        """Display in Kytos console if the data was updated."""
857
        entities = event.content.get('namespace', '').split('.')[-2]
858
        if error:
859
            log.error(f'Error trying to update storehouse {entities}.')
860
        else:
861
            log.debug(f'Storehouse update to entities: {entities}.')
862
863 1
    def verify_storehouse(self, entities):
864
        """Request a list of box saved by specific entity."""
865 1
        name = 'kytos.storehouse.list'
866 1
        content = {'namespace': f'kytos.topology.{entities}.metadata',
867
                   'callback': self.request_retrieve_entities}
868 1
        event = KytosEvent(name=name, content=content)
869 1
        self.controller.buffers.app.put(event)
870 1
        log.info(f'verify data in storehouse for {entities}.')
871
872 1
    def request_retrieve_entities(self, event, data, _error):
873
        """Create a box or retrieve an existent box from storehouse."""
874 1
        msg = ''
875 1
        content = {'namespace': event.content.get('namespace'),
876
                   'callback': self.load_from_store,
877
                   'data': {}}
878
879 1
        if not data:
880 1
            name = 'kytos.storehouse.create'
881 1
            msg = 'Create new box in storehouse'
882
        else:
883 1
            name = 'kytos.storehouse.retrieve'
884 1
            content['box_id'] = data[0]
885 1
            msg = 'Retrieve data from storehouse.'
886
887 1
        event = KytosEvent(name=name, content=content)
888 1
        self.controller.buffers.app.put(event)
889 1
        log.debug(msg)
890
891 1
    def load_from_store(self, event, box, error):
892
        """Save the data retrived from storehouse."""
893
        entities = event.content.get('namespace', '').split('.')[-2]
894
        if error:
895
            log.error('Error while get a box from storehouse.')
896
        else:
897
            self.store_items[entities] = box
898
            log.debug('Data updated')
899
900 1
    def update_instance_metadata(self, obj):
901
        """Update object instance with saved metadata."""
902 1
        metadata = None
903 1
        if isinstance(obj, Interface):
904 1
            all_metadata = self.store_items.get('interfaces', None)
905 1
            if all_metadata:
906
                metadata = all_metadata.data.get(obj.id)
907 1
        elif isinstance(obj, Switch):
908 1
            all_metadata = self.store_items.get('switches', None)
909 1
            if all_metadata:
910 1
                metadata = all_metadata.data.get(obj.id)
911 1
        elif isinstance(obj, Link):
912 1
            all_metadata = self.store_items.get('links', None)
913 1
            if all_metadata:
914
                metadata = all_metadata.data.get(obj.id)
915 1
        if metadata:
916
            obj.extend_metadata(metadata)
917
            log.debug(f'Metadata to {obj.id} was updated')
918
919 1
    @listen_to('kytos/maintenance.start_link')
920
    def on_link_maintenance_start(self, event):
921
        """Deals with the start of links maintenance."""
922
        with self._links_lock:
923
            self.handle_link_maintenance_start(event)
924
925 1
    def handle_link_maintenance_start(self, event):
926
        """Deals with the start of links maintenance."""
927 1
        notify_links = []
928 1
        maintenance_links = event.content['links']
929 1
        for maintenance_link in maintenance_links:
930 1
            try:
931 1
                link = self.links[maintenance_link.id]
932 1
            except KeyError:
933 1
                continue
934 1
            notify_links.append(link)
935 1
        for link in notify_links:
936 1
            link.disable()
937 1
            link.deactivate()
938 1
            link.endpoint_a.deactivate()
939 1
            link.endpoint_b.deactivate()
940 1
            link.endpoint_a.disable()
941 1
            link.endpoint_b.disable()
942 1
            self.notify_link_status_change(link, reason='maintenance')
943
944 1
    @listen_to('kytos/maintenance.end_link')
945
    def on_link_maintenance_end(self, event):
946
        """Deals with the end of links maintenance."""
947
        with self._links_lock:
948
            self.handle_link_maintenance_end(event)
949
950 1
    def handle_link_maintenance_end(self, event):
951
        """Deals with the end of links maintenance."""
952 1
        notify_links = []
953 1
        maintenance_links = event.content['links']
954 1
        for maintenance_link in maintenance_links:
955 1
            try:
956 1
                link = self.links[maintenance_link.id]
957 1
            except KeyError:
958 1
                continue
959 1
            notify_links.append(link)
960 1
        for link in notify_links:
961 1
            link.enable()
962 1
            link.activate()
963 1
            link.endpoint_a.activate()
964 1
            link.endpoint_b.activate()
965 1
            link.endpoint_a.enable()
966 1
            link.endpoint_b.enable()
967
            self.notify_link_status_change(link, reason='maintenance')
968