Passed
Push — master ( ad70c0...a80f24 )
by
unknown
04:43 queued 13s
created

build.main.Main.match_flows()   C

Complexity

Conditions 9

Size

Total Lines 30
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 10.4768

Importance

Changes 0
Metric Value
cc 9
eloc 19
nop 5
dl 0
loc 30
rs 6.6666
c 0
b 0
f 0
ccs 14
cts 19
cp 0.7368
crap 10.4768
1
"""Main module of amlight/sdntrace_cp Kytos Network Application.
2
3
Run tracepaths on OpenFlow in the Control Plane
4
"""
5
6 1
import pathlib
7 1
from datetime import datetime
8
9 1
import tenacity
10 1
from kytos.core import KytosNApp, log, rest
11 1
from kytos.core.helpers import load_spec, validate_openapi
12 1
from kytos.core.rest_api import (HTTPException, JSONResponse, Request,
13
                                 get_json_or_400)
14 1
from napps.amlight.sdntrace_cp.utils import (convert_entries,
15
                                             convert_list_entries,
16
                                             find_endpoint, get_stored_flows,
17
                                             match_field_dl_vlan,
18
                                             match_field_ip, prepare_json)
19
20
21 1
class Main(KytosNApp):
22
    """Main class of amlight/sdntrace_cp NApp.
23
24
    This application gets the list of flows from the switches
25
    and uses it to trace paths without using the data plane.
26
    """
27
28 1
    spec = load_spec(pathlib.Path(__file__).parent / "openapi.yml")
29
30 1
    def setup(self):
31
        """Replace the '__init__' method for the KytosNApp subclass.
32
33
        The setup method is automatically called by the controller when your
34
        application is loaded.
35
36
        """
37 1
        log.info("Starting Kytos SDNTrace CP App!")
38
39 1
    def execute(self):
40
        """This method is executed right after the setup method execution.
41
42
        You can also use this method in loop mode if you add to the above setup
43
        method a line like the following example:
44
45
            self.execute_as_loop(30)  # 30-second interval.
46
        """
47
48 1
    def shutdown(self):
49
        """This method is executed when your napp is unloaded.
50
51
        If you have some cleanup procedure, insert it here.
52
        """
53
54 1
    @rest('/v1/trace', methods=['PUT'])
55 1
    @validate_openapi(spec)
56 1
    def trace(self, request: Request) -> JSONResponse:
57
        """Trace a path."""
58 1
        result = []
59 1
        data = get_json_or_400(request, self.controller.loop)
60 1
        entries = convert_entries(data)
61 1
        if not entries:
62
            raise HTTPException(400, "Empty entries")
63 1
        try:
64 1
            stored_flows = get_stored_flows()
65 1
        except tenacity.RetryError as exc:
66
            raise HTTPException(424, "It couldn't get stored_flows") from exc
67 1
        result = self.tracepath(entries, stored_flows)
68 1
        return JSONResponse(prepare_json(result))
69
70 1
    @rest('/v1/traces', methods=['PUT'])
71 1
    @validate_openapi(spec)
72 1
    def get_traces(self, request: Request) -> JSONResponse:
73
        """For bulk requests."""
74 1
        data = get_json_or_400(request, self.controller.loop)
75 1
        entries = convert_list_entries(data)
76 1
        results = []
77 1
        try:
78 1
            stored_flows = get_stored_flows()
79 1
        except tenacity.RetryError as exc:
80
            raise HTTPException(424, "It couldn't get stored_flows") from exc
81 1
        for entry in entries:
82 1
            results.append(self.tracepath(entry, stored_flows))
83 1
        return JSONResponse(prepare_json(results))
84
85 1
    def tracepath(self, entries, stored_flows):
86
        """Trace a path for a packet represented by entries."""
87
        # pylint: disable=too-many-branches
88 1
        trace_result = []
89 1
        trace_type = 'starting'
90 1
        do_trace = True
91 1
        while do_trace:
92 1
            if 'dpid' not in entries or 'in_port' not in entries:
93
                break
94 1
            trace_step = {'in': {'dpid': entries['dpid'],
95
                                 'port': entries['in_port'],
96
                                 'time': str(datetime.now()),
97
                                 'type': trace_type}}
98 1
            if 'dl_vlan' in entries:
99 1
                trace_step['in'].update({'vlan': entries['dl_vlan'][-1]})
100
101 1
            switch = self.controller.get_switch_by_dpid(entries['dpid'])
102 1
            if not switch:
103 1
                trace_step['in']['type'] = 'last'
104 1
                trace_result.append(trace_step)
105 1
                break
106 1
            result = self.trace_step(switch, entries, stored_flows)
107 1
            if result:
108 1
                out = {'port': result['out_port']}
109 1
                if 'dl_vlan' in result['entries']:
110 1
                    out.update({'vlan': result['entries']['dl_vlan'][-1]})
111 1
                trace_step.update({
112
                    'out': out
113
                })
114 1
                if 'dpid' in result:
115 1
                    next_step = {'dpid': result['dpid'],
116
                                 'port': result['in_port']}
117 1
                    entries = result['entries']
118 1
                    entries['dpid'] = result['dpid']
119 1
                    entries['in_port'] = result['in_port']
120 1
                    if self.has_loop(next_step, trace_result):
121 1
                        trace_step['in']['type'] = 'loop'
122 1
                        do_trace = False
123
                    else:
124 1
                        trace_type = 'intermediary'
125
                else:
126 1
                    trace_step['in']['type'] = 'last'
127 1
                    do_trace = False
128
            else:
129 1
                trace_step['in']['type'] = 'incomplete'
130 1
                do_trace = False
131 1
            if 'out' in trace_step and trace_step['out']:
132 1
                if self.check_loop_trace_step(trace_step, trace_result):
133 1
                    do_trace = False
134 1
            trace_result.append(trace_step)
135 1
        return trace_result
136
137 1
    @staticmethod
138 1
    def check_loop_trace_step(trace_step, trace_result):
139
        """Check if there is a loop in the trace and add the step."""
140
        # outgoing interface is the same as the input interface
141 1
        if not trace_result and \
142
                trace_step['in']['type'] == 'last' and \
143
                trace_step['in']['port'] == trace_step['out']['port']:
144 1
            trace_step['in']['type'] = 'loop'
145 1
            return True
146 1
        if trace_result and \
147
                trace_result[0]['in']['dpid'] == trace_step['in']['dpid'] and \
148
                trace_result[0]['in']['port'] == trace_step['out']['port']:
149 1
            trace_step['in']['type'] = 'loop'
150 1
            return True
151 1
        return False
152
153 1
    @staticmethod
154 1
    def has_loop(trace_step, trace_result):
155
        """Check if there is a loop in the trace result."""
156 1
        for trace in trace_result:
157 1
            if trace['in']['dpid'] == trace_step['dpid'] and \
158
                            trace['in']['port'] == trace_step['port']:
159 1
                return True
160 1
        return False
161
162 1
    def trace_step(self, switch, entries, stored_flows):
163
        """Perform a trace step.
164
165
        Match the given fields against the switch's list of flows."""
166 1
        flow, entries, port = self.match_and_apply(
167
                                                    switch,
168
                                                    entries,
169
                                                    stored_flows
170
                                                )
171
172 1
        if not flow or not port:
173 1
            return None
174
175 1
        endpoint = find_endpoint(switch, port)
176 1
        if endpoint is None:
177
            log.warning(f"Port {port} not found on switch {switch}")
178
            return None
179 1
        endpoint = endpoint['endpoint']
180 1
        if endpoint is None:
181 1
            return {'out_port': port,
182
                    'entries': entries}
183
184 1
        return {'dpid': endpoint.switch.dpid,
185
                'in_port': endpoint.port_number,
186
                'out_port': port,
187
                'entries': entries}
188
189 1
    @classmethod
190 1
    def do_match(cls, flow, args):
191
        """Match a packet against this flow (OF1.3)."""
192
        # pylint: disable=consider-using-dict-items
193
        # pylint: disable=too-many-return-statements
194 1
        if ('match' not in flow['flow']) or (len(flow['flow']['match']) == 0):
195 1
            return False
196 1
        for name in flow['flow']['match']:
197 1
            field_flow = flow['flow']['match'][name]
198 1
            field = args.get(name)
199 1
            if name == 'dl_vlan':
200 1
                if not match_field_dl_vlan(field, field_flow):
201 1
                    return False
202
                continue
203
            # In the case of dl_vlan field, the match must be checked
204
            # even if this field is not in the packet args.
205 1
            if not field:
206
                return False
207 1
            if name in ('nw_src', 'nw_dst', 'ipv6_src', 'ipv6_dst'):
208
                if not match_field_ip(field, field_flow):
209
                    return False
210
                continue
211 1
            if field_flow != field:
212 1
                return False
213 1
        return flow
214
215 1
    def match_flows(self, switch, args, stored_flows, many=True):
216
        # pylint: disable=bad-staticmethod-argument
217
        """
218
        Match the packet in request against the stored flows from flow_manager.
219
        Try the match with each flow, in other. If many is True, tries the
220
        match with all flows, if False, tries until the first match.
221
        :param args: packet data
222
        :param many: Boolean, indicating whether to continue after matching the
223
                first flow or not
224
        :return: If many, the list of matched flows, or the matched flow
225
        """
226 1
        if switch.dpid not in stored_flows:
227
            return None
228 1
        response = []
229 1
        if switch.dpid not in stored_flows:
230
            return None
231 1
        try:
232 1
            for flow in stored_flows[switch.dpid]:
233 1
                match = Main.do_match(flow, args)
234 1
                if match:
235 1
                    if many:
236
                        response.append(match)
237
                    else:
238 1
                        response = match
239 1
                        break
240
        except AttributeError:
241
            return None
242 1
        if not many and isinstance(response, list):
243 1
            return None
244 1
        return response
245
246
    # pylint: disable=redefined-outer-name
247 1
    def match_and_apply(self, switch, args, stored_flows):
248
        # pylint: disable=bad-staticmethod-argument
249
        """Match flows and apply actions.
250
        Match given packet (in args) against
251
        the stored flows (from flow_manager) and,
252
        if a match flow is found, apply its actions."""
253 1
        flow = self.match_flows(switch, args, stored_flows, False)
254 1
        port = None
255 1
        actions = []
256
        # pylint: disable=too-many-nested-blocks
257 1
        if not flow or switch.ofp_version != '0x04':
258 1
            return flow, args, port
259 1
        if 'actions' in flow['flow']:
260 1
            actions = flow['flow']['actions']
261 1
        for action in actions:
262 1
            action_type = action['action_type']
263 1
            if action_type == 'output':
264 1
                port = action['port']
265 1
            if action_type == 'push_vlan':
266 1
                if 'dl_vlan' not in args:
267
                    args['dl_vlan'] = []
268 1
                args['dl_vlan'].append(0)
269 1
            if action_type == 'pop_vlan':
270 1
                if 'dl_vlan' in args:
271 1
                    args['dl_vlan'].pop()
272 1
                    if len(args['dl_vlan']) == 0:
273 1
                        del args['dl_vlan']
274 1
            if action_type == 'set_vlan':
275 1
                args['dl_vlan'][-1] = action['vlan_id']
276
        return flow, args, port
277