Passed
Pull Request — master (#46)
by Vinicius
05:41 queued 02:55
created

build.main.Main.handle_link_down()   A

Complexity

Conditions 3

Size

Total Lines 9
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 3

Importance

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