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

build.tracing.tracer.TracePath.tracepath_loop()   B

Complexity

Conditions 5

Size

Total Lines 33
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 5.0342

Importance

Changes 0
Metric Value
cc 5
eloc 25
nop 4
dl 0
loc 33
ccs 16
cts 18
cp 0.8889
crap 5.0342
rs 8.8133
c 0
b 0
f 0
1
"""
2
    Tracer main class
3
"""
4 1
import time
5 1
import queue
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_task = None
47 1
        self.step = 0
48 1
        self.trace_result = []
49 1
        self.trace_ended = False
50 1
        self.init_switch = self.get_init_switch()
51 1
        self.rest = FormatRest()
52
53 1
    def get_init_switch(self):
54
        """Get the Switch class of the switch requested by user
55
56
        Returns:
57
            Switch class
58
        """
59 1
        return Switches().get_switch(self.init_entries.dpid)
60
61 1
    def tracepath(self):
62
        """
63
            Do the trace path
64
            The logic is very simple:
65
            1 - Generate the probe packet using entries provided
66
            2 - Results a result and the packet_in (used to generate new probe)
67
                Possible results: 'timeout' meaning the end of trace
68
                                  or the trace step {'dpid', 'port'}
69
                Some networks do vlan rewriting, so it is important to get the
70
                packetIn msg with the header
71
            3 - If result is a trace step, send PacketOut to the switch that
72
                originated the PacketIn. Repeat till reaching timeout
73
        """
74 1
        log.warning("Starting Trace Path ID: %s" % self.id)
75 1
        entries = copy.deepcopy(self.init_entries)
76 1
        color = Colors().get_switch_color(self.init_switch.dpid)
77 1
        switch = self.init_switch
78
        # Add initial trace step
79 1
        self.rest.add_trace_step(self.trace_result, trace_type='starting',
80
                                 dpid=switch.dpid,
81
                                 port=entries.in_port)
82
        # A loop waiting for 'trace_ended'.
83
        # It changes to True when reaches timeout
84 1
        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 1
        self.trace_mgr.add_result(self.id, t_result)
92 1
        self.clear_trace_pkt_in()
93
94 1
    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, self.step)
102 1
            result, packet_in = self.send_trace_probe(switch, in_port,
103
                                                      probe_pkt)
104 1
            self.step += 1
105 1
            if result == 'pre-ended':
106
                # Trace got canceled. Kytos may have shut down.
107
                self.rest.add_trace_step(self.trace_result, trace_type=result)
108
                break
109 1
            if result == 'timeout':
110 1
                self.rest.add_trace_step(self.trace_result, trace_type='last')
111 1
                log.warning("Trace %s: Trace Completed!" % self.id)
112 1
                self.trace_ended = True
113
            else:
114 1
                self.rest.add_trace_step(self.trace_result,
115
                                         trace_type='trace',
116
                                         dpid=result['dpid'],
117
                                         port=result['port'])
118 1
                if self.check_loop():
119 1
                    self.rest.add_trace_step(self.trace_result,
120
                                             trace_type='last',
121
                                             reason='loop')
122 1
                    self.trace_ended = True
123 1
                    break
124
                # If we got here, that means we need to keep going.
125 1
                entries, color, switch = prepare_next_packet(entries, result,
126
                                                             packet_in)
127
128 1
    def send_trace_probe(self, switch, in_port, probe_pkt):
129
        """ This method sends the PacketOut and checks if the
130
        PacketIn was received in 3 seconds.
131
132
        Args:
133
            switch: target switch to start with
134
            in_port: target port to start with
135
            probe_pkt: ethernet frame to send (PacketOut.data)
136
137
        Returns:
138
            Timeout
139
            {switch & port}
140
        """
141 1
        timeout_control = 0  # Controls the timeout of 1 second and two tries
142 1
        while not self.trace_ended:
143 1
            log.info(f'Trace {self.id}: Sending POut to switch:'
144
                        f' {switch.dpid} and in_port {in_port}.'
145
                        f' Timeout: {self.init_entries.timeout}')
146 1
            send_packet_out(self.trace_mgr.controller,
147
                            switch, in_port, probe_pkt)
148
149 1
            time.sleep(self.init_entries.timeout)
150 1
            pkt_in_msg = self.get_packet_in()
151
152 1
            if pkt_in_msg:
153 1
                result = {"dpid": pkt_in_msg["dpid"],
154
                          "port": pkt_in_msg["in_port"]}
155 1
                return result, pkt_in_msg["event"]
156
157 1
            timeout_control += 1
158 1
            if timeout_control >= 3:
159 1
                return 'timeout', False
160 1
        return 'pre-ended', False
161
162 1
    def get_packet_in(self):
163
        """Wait for a PacketIn and verify if it is from the correct step."""
164 1
        while not self.trace_ended:
165 1
            if self.id not in self.trace_mgr._trace_pkt_in:
166 1
                return None
167 1
            try:
168 1
                pkt_in_msg = self.trace_mgr._trace_pkt_in[self.id].sync_q.get(block=False)
169
            except queue.Empty:
170
                return None
171 1
            msg = pkt_in_msg["msg"]
172 1
            if msg.step == self.step:
173 1
                return pkt_in_msg
174
175 1
    def clear_trace_pkt_in(self):
176
        """ Once the probe PacketIn was processed, delete it from queue."""
177 1
        if self.id in self.trace_mgr._trace_pkt_in:
178
            self.trace_mgr._trace_pkt_in[self.id].close()
179
            del self.trace_mgr._trace_pkt_in[self.id]
180
181 1
    def check_loop(self):
182
        """ Check if there are equal entries
183
184
        Return:
185
            True if loop
186
            0 if not
187
        """
188 1
        last = self.trace_result[-1]
189 1
        for result in self.trace_result[:-1]:
190 1
            if result['dpid'] == last['dpid']:
191 1
                if result['port'] == last['port']:
192 1
                    log.warning('Trace %s: Loop Detected on %s port %s!!' %
193
                                (self.id, last['dpid'], last['port']))
194 1
                    return True
195
        return 0
196