Passed
Pull Request — master (#95)
by
unknown
02:56
created

build.main.Main.shutdown()   A

Complexity

Conditions 1

Size

Total Lines 2
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nop 1
dl 0
loc 2
ccs 1
cts 1
cp 1
crap 1
rs 10
c 0
b 0
f 0
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 ipaddress
7 1
import pathlib
8 1
from datetime import datetime
9
10 1
import requests
11 1
from flask import jsonify
12 1
from kytos.core import KytosNApp, log, rest
13 1
from kytos.core.helpers import load_spec, validate_openapi
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, prepare_json)
18
19
20 1
class Main(KytosNApp):
21
    """Main class of amlight/sdntrace_cp NApp.
22
23
    This application gets the list of flows from the switches
24
    and uses it to trace paths without using the data plane.
25
    """
26
27 1
    spec = load_spec(pathlib.Path(__file__).parent / "openapi.yml")
28
29 1
    def setup(self):
30
        """Replace the '__init__' method for the KytosNApp subclass.
31
32
        The setup method is automatically called by the controller when your
33
        application is loaded.
34
35
        """
36 1
        log.info("Starting Kytos SDNTrace CP App!")
37
38 1
    def execute(self):
39
        """This method is executed right after the setup method execution.
40
41
        You can also use this method in loop mode if you add to the above setup
42
        method a line like the following example:
43
44
            self.execute_as_loop(30)  # 30-second interval.
45
        """
46
47 1
    def shutdown(self):
48
        """This method is executed when your napp is unloaded.
49
50
        If you have some cleanup procedure, insert it here.
51
        """
52
53 1
    @rest('/v1/trace', methods=['PUT'])
54 1
    @validate_openapi(spec)
55 1
    def trace(self, data):
56
        """Trace a path."""
57 1
        result = []
58 1
        entries = convert_entries(data)
59 1
        try:
60 1
            stored_flows = get_stored_flows()
61
        except requests.RequestException:
62
            result = []
63
        else:
64 1
            result = self.tracepath(entries, stored_flows)
65 1
        return jsonify(prepare_json(result))
66
67 1
    @rest('/v1/traces', methods=['PUT'])
68 1
    @validate_openapi(spec)
69 1
    def get_traces(self, data):
70
        """For bulk requests."""
71 1
        entries = convert_list_entries(data)
72 1
        results = []
73 1
        try:
74 1
            stored_flows = get_stored_flows()
75
        except requests.RequestException:
76
            return jsonify({'result': []})
77 1
        for entry in entries:
78 1
            results.append(self.tracepath(entry, stored_flows))
79 1
        temp = prepare_json(results)
80 1
        return jsonify(temp)
81
82 1
    def tracepath(self, entries, stored_flows):
83
        """Trace a path for a packet represented by entries."""
84
        # pylint: disable=too-many-branches
85 1
        trace_result = []
86 1
        trace_type = 'starting'
87 1
        do_trace = True
88 1
        while do_trace:
89 1
            if 'dpid' not in entries or 'in_port' not in entries:
90
                break
91 1
            trace_step = {'in': {'dpid': entries['dpid'],
92
                                 'port': entries['in_port'],
93
                                 'time': str(datetime.now()),
94
                                 'type': trace_type}}
95 1
            if 'dl_vlan' in entries:
96 1
                trace_step['in'].update({'vlan': entries['dl_vlan'][-1]})
97
98 1
            switch = self.controller.get_switch_by_dpid(entries['dpid'])
99 1
            if not switch:
100 1
                trace_step['in']['type'] = 'last'
101 1
                trace_result.append(trace_step)
102 1
                break
103 1
            result = self.trace_step(switch, entries, stored_flows)
104 1
            if result:
105 1
                out = {'port': result['out_port']}
106 1
                if 'dl_vlan' in result['entries']:
107 1
                    out.update({'vlan': result['entries']['dl_vlan'][-1]})
108 1
                trace_step.update({
109
                    'out': out
110
                })
111 1
                if 'dpid' in result:
112 1
                    next_step = {'dpid': result['dpid'],
113
                                 'port': result['in_port']}
114 1
                    entries = result['entries']
115 1
                    entries['dpid'] = result['dpid']
116 1
                    entries['in_port'] = result['in_port']
117 1
                    if self.has_loop(next_step, trace_result):
118 1
                        trace_step['in']['type'] = 'loop'
119 1
                        do_trace = False
120
                    else:
121 1
                        trace_type = 'intermediary'
122
                else:
123 1
                    trace_step['in']['type'] = 'last'
124 1
                    do_trace = False
125
            else:
126 1
                trace_step['in']['type'] = 'incomplete'
127 1
                do_trace = False
128 1
            if 'out' in trace_step and trace_step['out']:
129 1
                if self.check_loop_trace_step(trace_step, trace_result):
130 1
                    do_trace = False
131 1
            trace_result.append(trace_step)
132 1
        return trace_result
133
134 1
    @staticmethod
135 1
    def check_loop_trace_step(trace_step, trace_result):
136
        """Check if there is a loop in the trace and add the step."""
137
        # outgoing interface is the same as the input interface
138 1
        if not trace_result and \
139
                trace_step['in']['type'] == 'last' and \
140
                trace_step['in']['port'] == trace_step['out']['port']:
141 1
            trace_step['in']['type'] = 'loop'
142 1
            return True
143 1
        if trace_result and \
144
                trace_result[0]['in']['dpid'] == trace_step['in']['dpid'] and \
145
                trace_result[0]['in']['port'] == trace_step['out']['port']:
146 1
            trace_step['in']['type'] = 'loop'
147 1
            return True
148 1
        return False
149
150 1
    @staticmethod
151 1
    def has_loop(trace_step, trace_result):
152
        """Check if there is a loop in the trace result."""
153 1
        for trace in trace_result:
154 1
            if trace['in']['dpid'] == trace_step['dpid'] and \
155
                            trace['in']['port'] == trace_step['port']:
156 1
                return True
157 1
        return False
158
159 1
    def trace_step(self, switch, entries, stored_flows):
160
        """Perform a trace step.
161
162
        Match the given fields against the switch's list of flows."""
163 1
        flow, entries, port = self.match_and_apply(
164
                                                    switch,
165
                                                    entries,
166
                                                    stored_flows
167
                                                )
168
169 1
        if not flow or not port:
170 1
            return None
171
172 1
        endpoint = find_endpoint(switch, port)
173 1
        if endpoint is None:
174
            log.warning(f"Port {port} not found on switch {switch}")
175
            return None
176 1
        endpoint = endpoint['endpoint']
177 1
        if endpoint is None:
178 1
            return {'out_port': port,
179
                    'entries': entries}
180
181 1
        return {'dpid': endpoint.switch.dpid,
182
                'in_port': endpoint.port_number,
183
                'out_port': port,
184
                'entries': entries}
185
186 1
    @classmethod
187 1
    def do_match(cls, flow, args):
188
        """Match a packet against this flow (OF1.3)."""
189
        # pylint: disable=consider-using-dict-items
190
        # pylint: disable=too-many-return-statements
191 1
        if ('match' not in flow['flow']) or (len(flow['flow']['match']) == 0):
192 1
            return False
193 1
        for name in flow['flow']['match']:
194 1
            field_flow = flow['flow']['match'][name]
195 1
            if name == 'dl_vlan':
196 1
                field = args.get(name)
197 1
                if field:
198 1
                    field = field[-1]
199 1
                if not match_field_dl_vlan(field, field_flow):
200 1
                    return False
201
                continue
202 1
            if name not in args:
203
                return False
204 1
            field = args[name]
205 1
            if name not in ('ipv4_src', 'ipv4_dst', 'ipv6_src', 'ipv6_dst'):
206 1
                if field_flow != field:
207 1
                    return False
208
            else:
209
                packet_ip = int(ipaddress.ip_address(field))
210
                ip_addr = flow['flow']['match'][name]
211
                if packet_ip & ip_addr.netmask != ip_addr.address:
212
                    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