Passed
Pull Request — master (#73)
by
unknown
03:12
created

build.main.Main.match_flows()   B

Complexity

Conditions 8

Size

Total Lines 28
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 8.8337

Importance

Changes 0
Metric Value
cc 8
eloc 17
nop 5
dl 0
loc 28
ccs 13
cts 17
cp 0.7647
crap 8.8337
rs 7.3333
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
from datetime import datetime
8
9 1
from flask import jsonify, request
10 1
from kytos.core import KytosNApp, log, rest
11 1
from napps.amlight.sdntrace_cp import settings
12 1
from napps.amlight.sdntrace_cp.automate import Automate
13 1
from napps.amlight.sdntrace_cp.utils import (convert_entries,
14
                                             convert_list_entries,
15
                                             find_endpoint, get_stored_flows,
16
                                             prepare_json, prepare_list_json)
17
18
19 1
class Main(KytosNApp):
20
    """Main class of amlight/sdntrace_cp NApp.
21
22
    This application gets the list of flows from the switches
23
    and uses it to trace paths without using the data plane.
24
    """
25
26 1
    def setup(self):
27
        """Replace the '__init__' method for the KytosNApp subclass.
28
29
        The setup method is automatically called by the controller when your
30
        application is loaded.
31
32
        """
33 1
        log.info("Starting Kytos SDNTrace CP App!")
34
35 1
        self.traces = {}
36 1
        self.last_id = 30000
37 1
        self.automate = Automate(self)
38 1
        self.automate.schedule_traces()
39 1
        self.automate.schedule_important_traces()
40
41 1
    def execute(self):
42
        """This method is executed right after the setup method execution.
43
44
        You can also use this method in loop mode if you add to the above setup
45
        method a line like the following example:
46
47
            self.execute_as_loop(30)  # 30-second interval.
48
        """
49
50 1
    def shutdown(self):
51
        """This method is executed when your napp is unloaded.
52
53
        If you have some cleanup procedure, insert it here.
54
        """
55
        self.automate.unschedule_ids()
56
        self.automate.sheduler_shutdown(wait=False)
57
58 1
    @rest('/trace', methods=['PUT'])
59 1
    def trace(self):
60
        """Trace a path."""
61 1
        entries = request.get_json()
62 1
        entries = convert_entries(entries)
63 1
        stored_flows = get_stored_flows()
64 1
        result = self.tracepath(entries, stored_flows)
65 1
        return jsonify(prepare_json(result))
66
67 1
    @rest('/traces', methods=['PUT'])
68 1
    def get_traces(self):
69
        """For bulk requests."""
70 1
        entries = request.get_json()
71 1
        entries = convert_list_entries(entries)
72 1
        stored_flows = get_stored_flows()
73 1
        results = {}
74 1
        list_ready = []
75 1
        for entry in entries:
76 1
            if entry in list_ready:
77 1
                continue
78 1
            list_ready.append(entry)
79 1
            dpid = entry['dpid']
80 1
            if dpid not in results:
81 1
                results[dpid] = []
82 1
            result = prepare_list_json(self.tracepath(entry, stored_flows))
83 1
            results[dpid].append(result)
84 1
        return jsonify(results)
85
86 1
    def tracepath(self, entries, stored_flows):
87
        """Trace a path for a packet represented by entries."""
88 1
        self.last_id += 1
89 1
        trace_id = self.last_id
90 1
        trace_result = []
91 1
        trace_type = 'starting'
92 1
        do_trace = True
93 1
        while do_trace:
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
            if trace_type == 'loop':
102 1
                trace_result.append(trace_step)
103 1
                break
104
105 1
            switch = self.controller.get_switch_by_dpid(entries['dpid'])
106 1
            if not switch:
107
                trace_step['in']['type'] = 'last'
108
                trace_result.append(trace_step)
109
                break
110 1
            result = self.trace_step(switch, entries, stored_flows)
111 1
            if result:
112 1
                out = {'port': result['out_port']}
113 1
                if 'dl_vlan' in result['entries']:
114 1
                    out.update({'vlan': result['entries']['dl_vlan'][-1]})
115 1
                trace_step.update({
116
                    'out': out
117
                })
118 1
                if 'dpid' in result:
119 1
                    next_step = {'dpid': result['dpid'],
120
                                 'port': result['in_port']}
121 1
                    entries = result['entries']
122 1
                    entries['dpid'] = result['dpid']
123 1
                    entries['in_port'] = result['in_port']
124 1
                    if self.has_loop(next_step, trace_result):
125 1
                        trace_type = 'loop'
126
                    else:
127 1
                        trace_type = 'trace'
128
                else:
129 1
                    trace_step['in']['type'] = 'last'
130 1
                    do_trace = False
131
            else:
132
                trace_step['in']['type'] = 'incomplete'
133
                do_trace = False
134 1
            trace_result.append(trace_step)
135 1
        self.traces.update({
136
            trace_id: trace_result
137
        })
138 1
        return trace_result
139
140 1
    @staticmethod
141 1
    def has_loop(trace_step, trace_result):
142
        """Check if there is a loop in the trace result."""
143 1
        for trace in trace_result:
144 1
            if trace['in']['dpid'] == trace_step['dpid'] and \
145
                            trace['in']['port'] == trace_step['port']:
146 1
                return True
147 1
        return False
148
149 1
    def trace_step(self, switch, entries, stored_flows):
150
        """Perform a trace step.
151
152
        Match the given fields against the switch's list of flows."""
153 1
        flow, entries, port = self.match_and_apply(
154
                                                    switch,
155
                                                    entries,
156
                                                    stored_flows
157
                                                )
158
159 1
        if not flow or not port:
160 1
            return None
161
162 1
        endpoint = find_endpoint(switch, port)
163 1
        if endpoint is None:
164 1
            return {'out_port': port,
165
                    'entries': entries}
166
167 1
        return {'dpid': endpoint.switch.dpid,
168
                'in_port': endpoint.port_number,
169
                'out_port': port,
170
                'entries': entries}
171
172 1
    def update_circuits(self):
173
        """Update the list of circuits after a flow change."""
174
        # pylint: disable=unused-argument
175 1
        if settings.FIND_CIRCUITS_IN_FLOWS:
176 1
            self.automate.find_circuits()
177
178 1
    @classmethod
179 1
    def do_match(cls, flow, args):
180
        """Match a packet against this flow (OF1.3)."""
181
        # pylint: disable=consider-using-dict-items
182 1
        if ('match' not in flow['flow']) or (len(flow['flow']['match']) == 0):
183 1
            return False
184 1
        for name in flow['flow']['match']:
185 1
            field_flow = flow['flow']['match'][name]
186 1
            if name not in args:
187
                return False
188 1
            if name == 'dl_vlan':
189 1
                field = args[name][-1]
190
            else:
191 1
                field = args[name]
192 1
            if name not in ('ipv4_src', 'ipv4_dst', 'ipv6_src', 'ipv6_dst'):
193 1
                if field_flow != field:
194
                    return False
195
            else:
196
                packet_ip = int(ipaddress.ip_address(field))
197
                ip_addr = flow['flow']['match'][name]
198
                if packet_ip & ip_addr.netmask != ip_addr.address:
199
                    return False
200 1
        return flow
201
202 1
    def match_flows(self, switch, args, stored_flows, many=True):
203
        # pylint: disable=bad-staticmethod-argument
204
        """
205
        Match the packet in request against the stored flows from flow_manager.
206
        Try the match with each flow, in other. If many is True, tries the
207
        match with all flows, if False, tries until the first match.
208
        :param args: packet data
209
        :param many: Boolean, indicating whether to continue after matching the
210
                first flow or not
211
        :return: If many, the list of matched flows, or the matched flow
212
        """
213 1
        if switch.dpid not in stored_flows:
214
            return None
215 1
        response = []
216 1
        try:
217 1
            for flow in stored_flows[switch.dpid]:
218 1
                match = Main.do_match(flow, args)
219 1
                if match:
220 1
                    if many:
221
                        response.append(match)
222
                    else:
223 1
                        response = match
224 1
                        break
225
        except AttributeError:
226
            return None
227 1
        if not many and isinstance(response, list):
228 1
            return None
229 1
        return response
230
231
    # pylint: disable=redefined-outer-name
232 1
    def match_and_apply(self, switch, args, stored_flows):
233
        # pylint: disable=bad-staticmethod-argument
234
        """Match flows and apply actions.
235
        Match given packet (in args) against
236
        the stored flows (from flow_manager) and,
237
        if a match flow is found, apply its actions."""
238 1
        flow = self.match_flows(switch, args, stored_flows, False)
239 1
        port = None
240 1
        actions = None
241
        # pylint: disable=too-many-nested-blocks
242 1
        if not flow or switch.ofp_version != '0x04':
243 1
            return flow, args, port
244 1
        actions = flow['flow']['actions']
245 1
        for action in actions:
246 1
            action_type = action['action_type']
247 1
            if action_type == 'output':
248 1
                port = action['port']
249 1
            if action_type == 'push_vlan':
250 1
                if 'dl_vlan' not in args:
251
                    args['dl_vlan'] = []
252 1
                args['dl_vlan'].append(0)
253 1
            if action_type == 'pop_vlan':
254 1
                if 'dl_vlan' in args:
255 1
                    args['dl_vlan'].pop()
256 1
                    if len(args['dl_vlan']) == 0:
257 1
                        del args['dl_vlan']
258 1
            if action_type == 'set_vlan':
259 1
                args['dl_vlan'][-1] = action['vlan_id']
260
        return flow, args, port
261