Passed
Pull Request — master (#114)
by Aldo
04:00
created

build.tracing.tracer   A

Complexity

Total Complexity 20

Size/Duplication

Total Lines 197
Duplicated Lines 0 %

Test Coverage

Coverage 94.87%

Importance

Changes 0
Metric Value
eloc 97
dl 0
loc 197
ccs 74
cts 78
cp 0.9487
rs 10
c 0
b 0
f 0
wmc 20

7 Methods

Rating   Name   Duplication   Size   Complexity  
A TracePath.tracepath_loop() 0 28 4
A TracePath.tracepath() 0 34 1
A TracePath.get_init_switch() 0 7 1
A TracePath.__init__() 0 17 1
B TracePath.send_trace_probe() 0 50 6
A TracePath.check_loop() 0 15 4
A TracePath.clear_trace_pkt_in() 0 7 3
1
"""
2
    Tracer main class
3
"""
4 1
import time
5 1
import asyncio
6 1
import copy
7 1
from kytos.core import log
8 1
from napps.amlight.sdntrace.tracing.trace_pkt import generate_trace_pkt
9 1
from napps.amlight.sdntrace.tracing.trace_pkt import prepare_next_packet
10 1
from napps.amlight.sdntrace.tracing.rest import FormatRest
11 1
from napps.amlight.sdntrace.backends.of_parser import send_packet_out
12 1
from napps.amlight.sdntrace.shared.switches import Switches
13 1
from napps.amlight.sdntrace.shared.colors import Colors
14
15
16 1
class TracePath(object):
17
    """ Tracer main class - responsible for running traces.
18
    It is composed of two parts:
19
     1) Sending PacketOut messages to switches
20
     2) Reading the pktIn queue with PacketIn received
21
22
    There are a few possibilities of result (except for errors):
23
    - Timeouts ({'trace': 'completed'}) - even positive results end w/
24
        timeouts.
25
    - Loops ({'trace': 'loop'}) - every time an entry is seen twice
26
        in the trace_result queue, we stop
27
28
    Some things to take into consideration:
29
    - we can have parallel traces
30
    - we can have flow rewrite along the path (vlan translation, f.i)
31
    """
32
33 1
    def __init__(self, trace_manager, r_id, initial_entries):
34
        """
35
        Args:
36
            trace_manager: main TraceManager class - needed for
37
            Kytos.controller
38
            r_id: request ID
39
            initial_entries: user entries for trace
40
        """
41 1
        self.switches = Switches()
42 1
        self.trace_mgr = trace_manager
43 1
        self.id = r_id
44 1
        self.init_entries = initial_entries
45
46 1
        self.trace_result = []
47 1
        self.trace_ended = False
48 1
        self.init_switch = self.get_init_switch()
49 1
        self.rest = FormatRest()
50
51 1
    def get_init_switch(self):
52
        """Get the Switch class of the switch requested by user
53
54
        Returns:
55
            Switch class
56
        """
57 1
        return Switches().get_switch(self.init_entries.dpid)
58
59 1
    async def tracepath(self):
60
        """
61
            Do the trace path
62
            The logic is very simple:
63
            1 - Generate the probe packet using entries provided
64
            2 - Results a result and the packet_in (used to generate new probe)
65
                Possible results: 'timeout' meaning the end of trace
66
                                  or the trace step {'dpid', 'port'}
67
                Some networks do vlan rewriting, so it is important to get the
68
                packetIn msg with the header
69
            3 - If result is a trace step, send PacketOut to the switch that
70
                originated the PacketIn. Repeat till reaching timeout
71
        """
72 1
        log.warning("Starting Trace Path ID: %s" % self.id)
73
74 1
        entries = copy.deepcopy(self.init_entries)
75 1
        color = await Colors().aget_switch_color(self.init_switch.dpid)
76 1
        switch = self.init_switch
77
        # Add initial trace step
78 1
        self.rest.add_trace_step(self.trace_result, trace_type='starting',
79
                                 dpid=switch.dpid,
80
                                 port=entries.in_port)
81
82
        # A loop waiting for 'trace_ended'.
83
        # It changes to True when reaches timeout
84 1
        await self.tracepath_loop(entries, color, switch)
85
        # Add final result to trace_results_queue
86 1
        t_result = {"request_id": self.id,
87
                    "result": self.trace_result,
88
                    "start_time": str(self.rest.start_time),
89
                    "total_time": self.rest.get_time(),
90
                    "request": self.init_entries.init_entries}
91
92 1
        self.trace_mgr.add_result(self.id, t_result)
93
94 1
    async def tracepath_loop(self, entries, color, switch):
95
        """ This method sends the packet_out per hop, create the result
96
        to be posted via REST.
97
        """
98
        # A loop waiting for 'trace_ended'.
99
        # It changes to True when reaches timeout
100 1
        while not self.trace_ended:
101 1
            in_port, probe_pkt = generate_trace_pkt(entries, color, self.id)
102 1
            result, packet_in = await self.send_trace_probe(switch, in_port,
103
                                                            probe_pkt)
104 1
            if result == 'timeout':
105 1
                self.rest.add_trace_step(self.trace_result, trace_type='last')
106 1
                log.warning("Trace %s: Trace Completed!" % self.id)
107 1
                self.trace_ended = True
108
            else:
109 1
                self.rest.add_trace_step(self.trace_result,
110
                                         trace_type='trace',
111
                                         dpid=result['dpid'],
112
                                         port=result['port'])
113 1
                if self.check_loop():
114 1
                    self.rest.add_trace_step(self.trace_result,
115
                                             trace_type='last',
116
                                             reason='loop')
117 1
                    self.trace_ended = True
118 1
                    break
119
                # If we got here, that means we need to keep going.
120 1
                entries, color, switch = await prepare_next_packet(entries, result,
121
                                                                    packet_in)
122
123 1
    async def send_trace_probe(self, switch, in_port, probe_pkt):
124
        """ This method sends the PacketOut and checks if the
125
        PacketIn was received in 3 seconds.
126
127
        Args:
128
            switch: target switch to start with
129
            in_port: target port to start with
130
            probe_pkt: ethernet frame to send (PacketOut.data)
131
132
        Returns:
133
            Timeout
134
            {switch & port}
135
        """
136 1
        timeout_control = 0  # Controls the timeout of 1 second and two tries
137 1
        try:
138 1
            while True:
139 1
                log.warning(f'Trace {self.id}: Sending POut to switch:'
140
                            f' {switch.dpid} and in_port {in_port}.'
141
                            f' Timeout: {self.init_entries.timeout}')
142 1
                await send_packet_out(self.trace_mgr.controller,
143
                                       switch, in_port, probe_pkt)
144
                # Wait 0.5 second before querying for PacketIns
145
                # 0.5 is by default if it was not specified otherwise through request
146 1
                await asyncio.sleep(self.init_entries.timeout)
147 1
                timeout_control += 1
148
149 1
                if timeout_control >= 3:
150 1
                    return 'timeout', False
151
152
                # Check if there is any Probe PacketIn in the queue
153 1
                for pkt_in_msg in self.trace_mgr.trace_pkt_in:
154
                    # Let's look for traces with our self.id
155
                    # Each entry has the following format:
156
                    # {"dpid": pkt_in_dpid, "in_port": pkt_in_port,
157
                    #  "msg": msg, "ethernet": ethernet, "event": event}
158
                    # packetIn_data_request_id is the request id
159
                    # of the packetIn.data.
160
161 1
                    msg = pkt_in_msg["msg"]
162 1
                    if self.id == msg.request_id:
163 1
                        self.clear_trace_pkt_in()
164 1
                        result = {"dpid": pkt_in_msg["dpid"],
165
                                  "port": pkt_in_msg["in_port"]}
166 1
                        return result, pkt_in_msg["event"]
167
                    else:
168
                        log.warning('Trace %s: Sending PacketOut Again' % self.id)
169
                        await send_packet_out(self.trace_mgr.controller,
170
                                               switch, in_port, probe_pkt)
171
        except asyncio.CancelledError:
172
            log.warning(f"Trace {self.id} is getting cancelled.")
173
174 1
    def clear_trace_pkt_in(self):
175
        """ Once the probe PacketIn was processed, delete it from queue """
176
177 1
        for pkt_in_msg in self.trace_mgr.trace_pkt_in[:]:
178 1
            msg = pkt_in_msg["msg"]
179 1
            if self.id == msg.request_id:
180 1
                self.trace_mgr.trace_pkt_in.remove(pkt_in_msg)
181
182 1
    def check_loop(self):
183
        """ Check if there are equal entries
184
185
        Return:
186
            True if loop
187
            0 if not
188
        """
189 1
        last = self.trace_result[-1]
190 1
        for result in self.trace_result[:-1]:
191 1
            if result['dpid'] == last['dpid']:
192 1
                if result['port'] == last['port']:
193 1
                    log.warning('Trace %s: Loop Detected on %s port %s!!' %
194
                                (self.id, last['dpid'], last['port']))
195 1
                    return True
196
        return 0
197