Passed
Push — master ( 0c146b...211214 )
by
unknown
03:12 queued 13s
created

build.main   F

Complexity

Total Complexity 70

Size/Duplication

Total Lines 285
Duplicated Lines 0 %

Test Coverage

Coverage 89.77%

Importance

Changes 0
Metric Value
wmc 70
eloc 198
dl 0
loc 285
ccs 158
cts 176
cp 0.8977
rs 2.8
c 0
b 0
f 0

13 Methods

Rating   Name   Duplication   Size   Complexity  
A Main.shutdown() 0 7 1
A Main.execute() 0 2 1
A Main.has_loop() 0 8 4
A Main.setup() 0 12 1
B Main.check_loop_trace_step() 0 15 7
D Main.tracepath() 0 51 13
A Main.get_traces() 0 11 2
A Main.trace() 0 11 2
A Main.update_circuits() 0 5 2
B Main.trace_step() 0 26 5
D Main.match_and_apply() 0 30 12
C Main.match_flows() 0 30 9
C Main.do_match() 0 28 11

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
import pathlib
8 1
from datetime import datetime
9
10 1
from flask import jsonify
11 1
from kytos.core import KytosNApp, log, rest
12 1
from kytos.core.helpers import load_spec, validate_openapi
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, get_stored_flows,
18
                                             match_field_dl_vlan, 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
        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
    @validate_openapi(spec)
62 1
    def trace(self, data):
63
        """Trace a path."""
64 1
        result = []
65 1
        entries = convert_entries(data)
66 1
        if not entries:
67
            return "Bad request", 400
68 1
        stored_flows = get_stored_flows()
69 1
        result = self.tracepath(entries, stored_flows)
70 1
        return jsonify(prepare_json(result))
71
72 1
    @rest('/traces', methods=['PUT'])
73 1
    @validate_openapi(spec)
74 1
    def get_traces(self, data):
75
        """For bulk requests."""
76 1
        entries = convert_list_entries(data)
77 1
        stored_flows = get_stored_flows()
78 1
        results = []
79 1
        for entry in entries:
80 1
            results.append(self.tracepath(entry, stored_flows))
81 1
        temp = prepare_json(results)
82 1
        return jsonify(temp)
83
84 1
    def tracepath(self, entries, stored_flows):
85
        """Trace a path for a packet represented by entries."""
86
        # pylint: disable=too-many-branches
87 1
        trace_result = []
88 1
        trace_type = 'starting'
89 1
        do_trace = True
90 1
        while do_trace:
91 1
            if 'dpid' not in entries or 'in_port' not in entries:
92
                break
93 1
            trace_step = {'in': {'dpid': entries['dpid'],
94
                                 'port': entries['in_port'],
95
                                 'time': str(datetime.now()),
96
                                 'type': trace_type}}
97 1
            if 'dl_vlan' in entries:
98 1
                trace_step['in'].update({'vlan': entries['dl_vlan'][-1]})
99
100 1
            switch = self.controller.get_switch_by_dpid(entries['dpid'])
101 1
            if not switch:
102 1
                trace_step['in']['type'] = 'last'
103 1
                trace_result.append(trace_step)
104 1
                break
105 1
            result = self.trace_step(switch, entries, stored_flows)
106 1
            if result:
107 1
                out = {'port': result['out_port']}
108 1
                if 'dl_vlan' in result['entries']:
109 1
                    out.update({'vlan': result['entries']['dl_vlan'][-1]})
110 1
                trace_step.update({
111
                    'out': out
112
                })
113 1
                if 'dpid' in result:
114 1
                    next_step = {'dpid': result['dpid'],
115
                                 'port': result['in_port']}
116 1
                    entries = result['entries']
117 1
                    entries['dpid'] = result['dpid']
118 1
                    entries['in_port'] = result['in_port']
119 1
                    if self.has_loop(next_step, trace_result):
120 1
                        trace_step['in']['type'] = 'loop'
121 1
                        do_trace = False
122
                    else:
123 1
                        trace_type = 'intermediary'
124
                else:
125 1
                    trace_step['in']['type'] = 'last'
126 1
                    do_trace = False
127
            else:
128 1
                trace_step['in']['type'] = 'incomplete'
129 1
                do_trace = False
130 1
            if 'out' in trace_step and trace_step['out']:
131 1
                if self.check_loop_trace_step(trace_step, trace_result):
132 1
                    do_trace = False
133 1
            trace_result.append(trace_step)
134 1
        return trace_result
135
136 1
    @staticmethod
137 1
    def check_loop_trace_step(trace_step, trace_result):
138
        """Check if there is a loop in the trace and add the step."""
139
        # outgoing interface is the same as the input interface
140 1
        if not trace_result and \
141
                trace_step['in']['type'] == 'last' and \
142
                trace_step['in']['port'] == trace_step['out']['port']:
143 1
            trace_step['in']['type'] = 'loop'
144 1
            return True
145 1
        if trace_result and \
146
                trace_result[0]['in']['dpid'] == trace_step['in']['dpid'] and \
147
                trace_result[0]['in']['port'] == trace_step['out']['port']:
148 1
            trace_step['in']['type'] = 'loop'
149 1
            return True
150 1
        return False
151
152 1
    @staticmethod
153 1
    def has_loop(trace_step, trace_result):
154
        """Check if there is a loop in the trace result."""
155 1
        for trace in trace_result:
156 1
            if trace['in']['dpid'] == trace_step['dpid'] and \
157
                            trace['in']['port'] == trace_step['port']:
158 1
                return True
159 1
        return False
160
161 1
    def trace_step(self, switch, entries, stored_flows):
162
        """Perform a trace step.
163
164
        Match the given fields against the switch's list of flows."""
165 1
        flow, entries, port = self.match_and_apply(
166
                                                    switch,
167
                                                    entries,
168
                                                    stored_flows
169
                                                )
170
171 1
        if not flow or not port:
172 1
            return None
173
174 1
        endpoint = find_endpoint(switch, port)
175 1
        if endpoint is None:
176
            log.warning(f"Port {port} not found on switch {switch}")
177
            return None
178 1
        endpoint = endpoint['endpoint']
179 1
        if endpoint is None:
180 1
            return {'out_port': port,
181
                    'entries': entries}
182
183 1
        return {'dpid': endpoint.switch.dpid,
184
                'in_port': endpoint.port_number,
185
                'out_port': port,
186
                'entries': entries}
187
188 1
    def update_circuits(self):
189
        """Update the list of circuits after a flow change."""
190
        # pylint: disable=unused-argument
191 1
        if settings.FIND_CIRCUITS_IN_FLOWS:
192 1
            self.automate.find_circuits()
193
194 1
    @classmethod
195 1
    def do_match(cls, flow, args):
196
        """Match a packet against this flow (OF1.3)."""
197
        # pylint: disable=consider-using-dict-items
198
        # pylint: disable=too-many-return-statements
199 1
        if ('match' not in flow['flow']) or (len(flow['flow']['match']) == 0):
200 1
            return False
201 1
        for name in flow['flow']['match']:
202 1
            field_flow = flow['flow']['match'][name]
203 1
            if name == 'dl_vlan':
204 1
                field = args.get(name)
205 1
                if field:
206 1
                    field = field[-1]
207 1
                if not match_field_dl_vlan(field, field_flow):
208 1
                    return False
209
                continue
210 1
            if name not in args:
211
                return False
212 1
            field = args[name]
213 1
            if name not in ('ipv4_src', 'ipv4_dst', 'ipv6_src', 'ipv6_dst'):
214 1
                if field_flow != field:
215 1
                    return False
216
            else:
217
                packet_ip = int(ipaddress.ip_address(field))
218
                ip_addr = flow['flow']['match'][name]
219
                if packet_ip & ip_addr.netmask != ip_addr.address:
220
                    return False
221 1
        return flow
222
223 1
    def match_flows(self, switch, args, stored_flows, many=True):
224
        # pylint: disable=bad-staticmethod-argument
225
        """
226
        Match the packet in request against the stored flows from flow_manager.
227
        Try the match with each flow, in other. If many is True, tries the
228
        match with all flows, if False, tries until the first match.
229
        :param args: packet data
230
        :param many: Boolean, indicating whether to continue after matching the
231
                first flow or not
232
        :return: If many, the list of matched flows, or the matched flow
233
        """
234 1
        if switch.dpid not in stored_flows:
235
            return None
236 1
        response = []
237 1
        if switch.dpid not in stored_flows:
238
            return None
239 1
        try:
240 1
            for flow in stored_flows[switch.dpid]:
241 1
                match = Main.do_match(flow, args)
242 1
                if match:
243 1
                    if many:
244
                        response.append(match)
245
                    else:
246 1
                        response = match
247 1
                        break
248
        except AttributeError:
249
            return None
250 1
        if not many and isinstance(response, list):
251 1
            return None
252 1
        return response
253
254
    # pylint: disable=redefined-outer-name
255 1
    def match_and_apply(self, switch, args, stored_flows):
256
        # pylint: disable=bad-staticmethod-argument
257
        """Match flows and apply actions.
258
        Match given packet (in args) against
259
        the stored flows (from flow_manager) and,
260
        if a match flow is found, apply its actions."""
261 1
        flow = self.match_flows(switch, args, stored_flows, False)
262 1
        port = None
263 1
        actions = []
264
        # pylint: disable=too-many-nested-blocks
265 1
        if not flow or switch.ofp_version != '0x04':
266 1
            return flow, args, port
267 1
        if 'actions' in flow['flow']:
268 1
            actions = flow['flow']['actions']
269 1
        for action in actions:
270 1
            action_type = action['action_type']
271 1
            if action_type == 'output':
272 1
                port = action['port']
273 1
            if action_type == 'push_vlan':
274 1
                if 'dl_vlan' not in args:
275
                    args['dl_vlan'] = []
276 1
                args['dl_vlan'].append(0)
277 1
            if action_type == 'pop_vlan':
278 1
                if 'dl_vlan' in args:
279 1
                    args['dl_vlan'].pop()
280 1
                    if len(args['dl_vlan']) == 0:
281 1
                        del args['dl_vlan']
282 1
            if action_type == 'set_vlan':
283 1
                args['dl_vlan'][-1] = action['vlan_id']
284
        return flow, args, port
285