Passed
Pull Request — master (#47)
by
unknown
03:09
created

build.main.Main.match_flows()   B

Complexity

Conditions 7

Size

Total Lines 26
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 8.8142

Importance

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