Passed
Pull Request — master (#209)
by Vinicius
13:06 queued 09:04
created

kytos.core.events.KytosEvent.__init__()   A

Complexity

Conditions 2

Size

Total Lines 21
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 7
nop 4
dl 0
loc 21
ccs 7
cts 7
cp 1
crap 2
rs 10
c 0
b 0
f 0
1
"""Module with Kytos Events."""
2 1
import json
3 1
from datetime import datetime
4 1
from uuid import uuid4
5
6 1
from kytos.core.helpers import now
7
8
9 1
class KytosEvent:
10
    """Base Event class.
11
12
    The event data will be passed in the `content` attribute, which should be a
13
    dictionary.
14
    """
15
16 1
    def __init__(self, name=None, content=None, trace_parent=None):
17
        """Create an event to be published.
18
19
        Args:
20
            name (string): The name of the event. You should prepend it with
21
                           the name of the napp.
22
            content (dict): Dictionary with any extra data for the event.
23
            trace_parent (object): APM TraceParent for distributed tracing,
24
                                   if you have APM enabled, @listen_to will
25
                                   set the root parent, and then you have to
26
                                   pass the trace_parent to subsequent
27
                                   correlated KytosEvent(s).
28
        """
29 1
        self.name = name
30 1
        self.content = content if content is not None else {}
31 1
        self.timestamp = now()
32 1
        self.reinjections = 0
33
34
        # pylint: disable=invalid-name
35 1
        self.id = uuid4()
36 1
        self.trace_parent = trace_parent
37
38 1
    def __str__(self):
39 1
        return self.name
40
41 1
    def __repr__(self):
42 1
        return f"KytosEvent({self.name!r}, {self.content!r})"
43
44 1
    def as_dict(self):
45
        """Return KytosEvent as a dict."""
46 1
        return {'id': str(self.id), 'name': self.name, 'content': self.content,
47
                'timestamp': self.timestamp, 'reinjections': self.reinjections}
48
49 1
    def as_json(self):
50
        """Return KytosEvent as json."""
51 1
        as_dict = self.as_dict()
52 1
        timestamp = datetime.strftime(as_dict['timestamp'],
53
                                      '%Y-%m-%dT%H:%M:%S')
54 1
        as_dict['timestamp'] = timestamp
55 1
        try:
56 1
            return json.dumps(as_dict)
57
        except TypeError:
58
            as_dict['content'] = str(as_dict['content'])
59
            return json.dumps(as_dict)
60
61 1
    @property
62 1
    def destination(self):
63
        """Return the destination of KytosEvent."""
64 1
        return self.content.get('destination')
65
66 1
    def set_destination(self, destination):
67
        """Update the destination of KytosEvent.
68
69
        Args:
70
            destination (string): destination of KytosEvent.
71
        """
72 1
        self.content['destination'] = destination
73
74 1
    @property
75 1
    def source(self):
76
        """Return the source of KytosEvent."""
77 1
        return self.content.get('source')
78
79 1
    def set_source(self, source):
80
        """Update the source of KytosEvent.
81
82
        Args:
83
            source (string): source of KytosEvent.
84
        """
85 1
        self.content['source'] = source
86
87 1
    @property
88 1
    def message(self):
89
        """Return the message carried by the event if it exists.
90
91
        If there is any OpenFlow message on the event it'll be stored on
92
        the 'message' key of the 'content' attribute.
93
94
        Returns:
95
            A python-openflow message instance if it exists, None otherwise.
96
97
        """
98 1
        try:
99 1
            return self.content['message']
100 1
        except KeyError:
101
            return None
102