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

build.tracing.tracer   A

Complexity

Total Complexity 22

Size/Duplication

Total Lines 191
Duplicated Lines 0 %

Test Coverage

Coverage 95.29%

Importance

Changes 0
Metric Value
eloc 103
dl 0
loc 191
ccs 81
cts 85
cp 0.9529
rs 10
c 0
b 0
f 0
wmc 22

8 Methods

Rating   Name   Duplication   Size   Complexity  
A TracePath.__init__() 0 19 1
A TracePath.tracepath() 0 32 1
A TracePath.get_init_switch() 0 7 1
A TracePath.send_trace_probe() 0 32 4
A TracePath.check_loop() 0 15 4
A TracePath.tracepath_loop() 0 29 4
A TracePath.get_packet_in() 0 12 5
A TracePath.clear_trace_pkt_in() 0 5 2
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 == 'timeout':
106 1
                self.rest.add_trace_step(self.trace_result, trace_type='last')
107 1
                log.warning("Trace %s: Trace Completed!" % self.id)
108 1
                self.trace_ended = True
109
            else:
110 1
                self.rest.add_trace_step(self.trace_result,
111
                                         trace_type='trace',
112
                                         dpid=result['dpid'],
113
                                         port=result['port'])
114 1
                if self.check_loop():
115 1
                    self.rest.add_trace_step(self.trace_result,
116
                                             trace_type='last',
117
                                             reason='loop')
118 1
                    self.trace_ended = True
119 1
                    break
120
                # If we got here, that means we need to keep going.
121 1
                entries, color, switch = prepare_next_packet(entries, result,
122
                                                             packet_in)
123
124 1
    def send_trace_probe(self, switch, in_port, probe_pkt):
125
        """ This method sends the PacketOut and checks if the
126
        PacketIn was received in 3 seconds.
127
128
        Args:
129
            switch: target switch to start with
130
            in_port: target port to start with
131
            probe_pkt: ethernet frame to send (PacketOut.data)
132
133
        Returns:
134
            Timeout
135
            {switch & port}
136
        """
137 1
        timeout_control = 0  # Controls the timeout of 1 second and two tries
138 1
        while not self.trace_ended:
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
            send_packet_out(self.trace_mgr.controller,
143
                            switch, in_port, probe_pkt)
144
145 1
            time.sleep(self.init_entries.timeout)
146 1
            pkt_in_msg = self.get_packet_in()
147
148 1
            if pkt_in_msg:
149 1
                result = {"dpid": pkt_in_msg["dpid"],
150
                          "port": pkt_in_msg["in_port"]}
151 1
                return result, pkt_in_msg["event"]
152
153 1
            timeout_control += 1
154 1
            if timeout_control >= 3:
155 1
                return 'timeout', False
156
157 1
    def get_packet_in(self):
158
        """Wait for a PacketIn and verify if it is from the correct step."""
159 1
        while not self.trace_ended:
160 1
            if self.id not in self.trace_mgr._trace_pkt_in:
161 1
                return None
162 1
            try:
163 1
                pkt_in_msg = self.trace_mgr._trace_pkt_in[self.id].sync_q.get(block=False)
164
            except queue.Empty:
165
                return None
166 1
            msg = pkt_in_msg["msg"]
167 1
            if msg.step == self.step:
168 1
                return pkt_in_msg
169
170 1
    def clear_trace_pkt_in(self):
171
        """ Once the probe PacketIn was processed, delete it from queue."""
172 1
        if self.id in self.trace_mgr._trace_pkt_in:
173
            self.trace_mgr._trace_pkt_in[self.id].close()
174
            del self.trace_mgr._trace_pkt_in[self.id]
175
176 1
    def check_loop(self):
177
        """ Check if there are equal entries
178
179
        Return:
180
            True if loop
181
            0 if not
182
        """
183 1
        last = self.trace_result[-1]
184 1
        for result in self.trace_result[:-1]:
185 1
            if result['dpid'] == last['dpid']:
186 1
                if result['port'] == last['port']:
187 1
                    log.warning('Trace %s: Loop Detected on %s port %s!!' %
188
                                (self.id, last['dpid'], last['port']))
189 1
                    return True
190
        return 0
191