Test Failed
Pull Request — master (#49)
by
unknown
03:59
created

build.main   B

Complexity

Total Complexity 52

Size/Duplication

Total Lines 248
Duplicated Lines 0 %

Test Coverage

Coverage 75.17%

Importance

Changes 0
Metric Value
eloc 166
dl 0
loc 248
rs 7.44
c 0
b 0
f 0
ccs 109
cts 145
cp 0.7517
wmc 52

12 Methods

Rating   Name   Duplication   Size   Complexity  
A Main.execute() 0 2 1
A Main.update_circuits() 0 5 2
A Main.trace_step() 0 22 4
A Main.shutdown() 0 7 1
A Main.setup() 0 14 1
A Main.has_loop() 0 8 4
C Main.match_and_apply() 0 29 11
B Main.tracepath() 0 42 7
A Main.get_traces() 0 18 4
A Main.trace() 0 8 1
B Main.match_flows() 0 26 7
C Main.do_match() 0 23 9

How to fix   Complexity   

Complexity

Complex classes like build.main often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

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 1
                                             convert_list_entries,
15 1
                                             find_endpoint, get_stored_flows,
16
                                             prepare_json, prepare_list_json)
17
18
19
class Main(KytosNApp):
20
    """Main class of amlight/sdntrace_cp NApp.
21 1
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
    def setup(self):
27
        """Replace the '__init__' method for the KytosNApp subclass.
28 1
29
        The setup method is automatically called by the controller when your
30
        application is loaded.
31
32
        """
33
        log.info("Starting Kytos SDNTrace CP App!")
34
35 1
        self.traces = {}
36
        self.last_id = 30000
37 1
        self.automate = Automate(self)
38 1
        self.automate.schedule_traces()
39 1
        self.automate.schedule_important_traces()
40 1
41 1
    def execute(self):
42
        """This method is executed right after the setup method execution.
43 1
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
    def shutdown(self):
51
        """This method is executed when your napp is unloaded.
52 1
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
    @rest('/trace', methods=['PUT'])
59
    def trace(self):
60 1
        """Trace a path."""
61 1
        entries = request.get_json()
62
        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 1
67 1
    @rest('/traces', methods=['PUT'])
68
    def get_traces(self):
69 1
        """For bulk requests."""
70 1
        entries = request.get_json()
71
        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['dpid'], entry['in_port']) in list_ready:
77 1
                continue
78 1
            list_ready.append((entry['dpid'], entry['in_port']))
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 1
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
        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 1
                                 'port': entries['in_port'],
96 1
                                 'time': str(datetime.now()),
97
                                 'type': trace_type}}
98
            if 'dl_vlan' in entries:
99
                trace_step['in'].update({'vlan': entries['dl_vlan'][-1]})
100 1
            switch = self.controller.get_switch_by_dpid(entries['dpid'])
101 1
            result = self.trace_step(switch, entries, stored_flows)
102 1
            if result:
103 1
                out = {'port': result['out_port']}
104 1
                if 'dl_vlan' in result['entries']:
105 1
                    out.update({'vlan': result['entries']['dl_vlan'][-1]})
106 1
                trace_step.update({
107
                    'out': out
108 1
                })
109
                if 'dpid' in result:
110
                    next_step = {'dpid': result['dpid'],
111 1
                                 'port': result['in_port']}
112 1
                    if self.has_loop(next_step, trace_result):
113
                        do_trace = False
114 1
                    else:
115 1
                        entries = result['entries']
116
                        entries['dpid'] = result['dpid']
117 1
                        entries['in_port'] = result['in_port']
118 1
                        trace_type = 'trace'
119 1
                else:
120 1
                    do_trace = False
121
            else:
122
                do_trace = False
123
            trace_result.append(trace_step)
124 1
        self.traces.update({
125 1
            trace_id: trace_result
126 1
        })
127
        return trace_result
128
129 1
    @staticmethod
130
    def has_loop(trace_step, trace_result):
131 1
        """Check if there is a loop in the trace result."""
132 1
        for trace in trace_result:
133
            if trace['in']['dpid'] == trace_step['dpid'] and \
134 1
                            trace['in']['port'] == trace_step['port']:
135 1
                return True
136
        return False
137 1
138 1
    def trace_step(self, switch, entries, stored_flows):
139
        """Perform a trace step.
140 1
141
        Match the given fields against the switch's list of flows."""
142
        flow, entries, port = self.match_and_apply(
143
                                                    switch,
144 1
                                                    entries,
145
                                                    stored_flows
146
                                                )
147
148
        if not flow or not port:
149
            return None
150 1
151 1
        endpoint = find_endpoint(switch, port)
152
        if endpoint is None:
153 1
            return {'out_port': port,
154 1
                    'entries': entries}
155 1
156
        return {'dpid': endpoint.switch.dpid,
157
                'in_port': endpoint.port_number,
158 1
                'out_port': port,
159
                'entries': entries}
160
161
    def update_circuits(self):
162
        """Update the list of circuits after a flow change."""
163 1
        # pylint: disable=unused-argument
164 1
        if settings.FIND_CIRCUITS_IN_FLOWS:
165
            self.automate.find_circuits()
166
167 1
    @classmethod
168 1
    def do_match(cls, flow, args):
169
        """Match a packet against this flow (OF1.3)."""
170 1
        # pylint: disable=consider-using-dict-items
171 1
        if ('match' not in flow['flow']) or (len(flow['flow']['match']) == 0):
172
            return False
173
        for name in flow['flow']['match']:
174
            field_flow = flow['flow']['match'][name]
175
            if name not in args:
176
                return False
177
            if name == 'dl_vlan':
178
                field = args[name][-1]
179
            else:
180
                field = args[name]
181
            if name not in ('ipv4_src', 'ipv4_dst', 'ipv6_src', 'ipv6_dst'):
182
                if field_flow != field:
183
                    return False
184
            else:
185
                packet_ip = int(ipaddress.ip_address(field))
186 1
                ip_addr = flow['flow']['match'][name]
187 1
                if packet_ip & ip_addr.netmask != ip_addr.address:
188
                    return False
189
        return flow
190 1
191 1
    def match_flows(self, switch, args, stored_flows, many=True):
192
        # pylint: disable=bad-staticmethod-argument
193
        """
194
        Match the packet in request against the stored flows from flow_manager.
195
        Try the match with each flow, in other. If many is True, tries the
196
        match with all flows, if False, tries until the first match.
197
        :param args: packet data
198
        :param many: Boolean, indicating whether to continue after matching the
199
                first flow or not
200
        :return: If many, the list of matched flows, or the matched flow
201
        """
202
        response = []
203
        try:
204
            for flow in stored_flows[switch.dpid]:
205
                match = Main.do_match(flow, args)
206
                if match:
207
                    if many:
208
                        response.append(match)
209
                    else:
210 1
                        response = match
211
                        break
212
        except AttributeError:
213
            return None
214
        if not many and isinstance(response, list):
215
            return None
216
        return response
217
218
    # pylint: disable=redefined-outer-name
219
    def match_and_apply(self, switch, args, stored_flows):
220
        # pylint: disable=bad-staticmethod-argument
221 1
        """Match flows and apply actions.
222 1
        Match given packet (in args) against
223 1
        the stored flows (from flow_manager) and,
224 1
        if a match flow is found, apply its actions."""
225 1
        flow = self.match_flows(switch, args, stored_flows, False)
226
        port = None
227
        actions = None
228
        # pylint: disable=too-many-nested-blocks
229
        if not flow or switch.ofp_version != '0x04':
230
            return flow, args, port
231 1
        actions = flow['flow']['actions']
232 1
        for action in actions:
233 1
            action_type = action['action_type']
234 1
            if action_type == 'output':
235
                port = action['port']
236
            if action_type == 'push_vlan':
237
                if 'dl_vlan' not in args:
238 1
                    args['dl_vlan'] = []
239
                args['dl_vlan'].append(0)
240
            if action_type == 'pop_vlan':
241
                if 'dl_vlan' in args:
242
                    args['dl_vlan'].pop()
243
                    if len(args['dl_vlan']) == 0:
244 1
                        del args['dl_vlan']
245 1
            if action_type == 'set_vlan':
246 1
                args['dl_vlan'][-1] = action['vlan_id']
247
        return flow, args, port
248