Passed
Pull Request — master (#125)
by
unknown
02:28
created

build.main   F

Complexity

Total Complexity 70

Size/Duplication

Total Lines 392
Duplicated Lines 0 %

Test Coverage

Coverage 79.74%

Importance

Changes 0
Metric Value
eloc 245
dl 0
loc 392
ccs 185
cts 232
cp 0.7974
rs 2.8
c 0
b 0
f 0
wmc 70

20 Methods

Rating   Name   Duplication   Size   Complexity  
A Main.resend_stored_flows() 0 17 4
A Main.shutdown() 0 3 1
A Main.execute() 0 10 2
A Main._send_flow_mod() 0 8 1
A Main._send_napp_event() 0 15 4
B Main.handle_errors() 0 45 8
A Main._add_flow_mod_sent() 0 5 2
A Main.list() 0 19 3
A Main._load_flows() 0 11 4
B Main._send_flow_mods_from_request() 0 23 7
A Main.delete() 0 10 1
A Main._get_all_switches_enabled() 0 4 1
B Main._store_changed_flows() 0 52 6
A Main.setup() 0 21 2
A Main.check_switch_consistency() 0 28 5
B Main._install_flows() 0 26 6
A Main.consistency_check() 0 11 4
A Main.add() 0 8 1
A Main.on_flow_stats_check_consistency() 0 10 4
A Main.check_storehouse_consistency() 0 26 4

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
"""kytos/flow_manager NApp installs, lists and deletes switch flows."""
2 1
from collections import OrderedDict
3
4 1
from flask import jsonify, request
5 1
from pyof.v0x01.asynchronous.error_msg import BadActionCode
6 1
from pyof.v0x01.common.phy_port import PortConfig
7
8 1
from kytos.core import KytosEvent, KytosNApp, log, rest
9 1
from kytos.core.helpers import listen_to
10 1
from napps.kytos.flow_manager.storehouse import StoreHouse
11 1
from napps.kytos.of_core.flow import FlowFactory
12
13 1
from .exceptions import InvalidCommandError
14 1
from .settings import CONSISTENCY_INTERVAL, FLOWS_DICT_MAX_SIZE
15
16
17 1
class Main(KytosNApp):
18
    """Main class to be used by Kytos controller."""
19
20 1
    def setup(self):
21
        """Replace the 'init' method for the KytosApp subclass.
22
23
        The setup method is automatically called by the run method.
24
        Users shouldn't call this method directly.
25
        """
26 1
        log.debug("flow-manager starting")
27 1
        self._flow_mods_sent = OrderedDict()
28 1
        self._flow_mods_sent_max_size = FLOWS_DICT_MAX_SIZE
29
30
        # Storehouse client to save and restore flow data:
31 1
        self.storehouse = StoreHouse(self.controller)
32
33
        # Format of stored flow data:
34
        # {'flow_persistence': {'dpid_str': {'flow_list': [
35
        #                                     {'command': '<add|delete>',
36
        #                                      'flow': {flow_dict}}]}}}
37 1
        self.stored_flows = {}
38 1
        self.resent_flows = set()
39 1
        if CONSISTENCY_INTERVAL > 0:
40
            self.execute_as_loop(CONSISTENCY_INTERVAL)
41
42 1
    def execute(self):
43
        """Run once on NApp 'start' or in a loop.
44
45
        The execute method is called by the run method of KytosNApp class.
46
        Users shouldn't call this method directly.
47
        """
48
        self._load_flows()
49
50
        if CONSISTENCY_INTERVAL > 0:
51
            self.consistency_check()
52
53 1
    def shutdown(self):
54
        """Shutdown routine of the NApp."""
55
        log.debug("flow-manager stopping")
56
57 1
    @listen_to('kytos/of_core.handshake.completed')
58
    def resend_stored_flows(self, event):
59
        """Resend stored Flows."""
60 1
        switch = event.content['switch']
61 1
        dpid = str(switch.dpid)
62
        # This can be a problem because this code is running a thread
63 1
        if dpid in self.resent_flows:
64
            log.debug(f'Flow already resent to the switch {dpid}')
65
            return
66 1
        if dpid in self.stored_flows:
67 1
            flow_list = self.stored_flows[dpid]['flow_list']
68 1
            for flow in flow_list:
69 1
                command = flow['command']
70 1
                flows_dict = {"flows": [flow['flow']]}
71 1
                self._install_flows(command, flows_dict, [switch])
72 1
            self.resent_flows.add(dpid)
73 1
            log.info(f'Flows resent to Switch {dpid}')
74
75 1
    @listen_to('kytos/of_core.flow_stats.received')
76
    def on_flow_stats_check_consistency(self, event):
77
        """Check the consistency of a switch upon receiving flow stats."""
78
        if CONSISTENCY_INTERVAL != 0:
79
            return
80
        switch = event.content['switch']
81
        if switch.is_enabled():
82
            self.check_storehouse_consistency(switch)
83
            if switch.dpid in self.stored_flows:
84
                self.check_switch_consistency(switch)
85
86 1
    def consistency_check(self):
87
        """Check the consistency of flows in each switch."""
88
        switches = self.controller.switches.values()
89
90
        for switch in switches:
91
            # Check if a dpid is a key in 'stored_flows' dictionary
92
            if switch.is_enabled():
93
                self.check_storehouse_consistency(switch)
94
95
                if switch.dpid in self.stored_flows:
96
                    self.check_switch_consistency(switch)
97
98 1
    def check_switch_consistency(self, switch):
99
        """Check consistency of installed flows for a specific switch."""
100 1
        dpid = switch.dpid
101
102
        # Flows stored in storehouse
103 1
        stored_flows = self.stored_flows[dpid]['flow_list']
104
105 1
        serializer = FlowFactory.get_class(switch)
106
107 1
        for stored_flow in stored_flows:
108 1
            command = stored_flow['command']
109 1
            stored_flow_obj = serializer.from_dict(stored_flow['flow'], switch)
110
111 1
            flow = {'flows': [stored_flow['flow']]}
112
113 1
            if stored_flow_obj not in switch.flows:
114 1
                if command == 'add':
115 1
                    log.info('A consistency problem was detected in '
116
                             f'switch {dpid}.')
117 1
                    self._install_flows(command, flow, [switch])
118 1
                    log.info(f'Flow forwarded to switch {dpid} to be '
119
                             'installed.')
120 1
            elif command == 'delete':
121 1
                log.info('A consistency problem was detected in '
122
                         f'switch {dpid}.')
123 1
                command = 'delete_strict'
124 1
                self._install_flows(command, flow, [switch])
125 1
                log.info(f'Flow forwarded to switch {dpid} to be deleted.')
126
127 1
    def check_storehouse_consistency(self, switch):
128
        """Check consistency of installed flows for a specific switch."""
129 1
        dpid = switch.dpid
130
131 1
        for installed_flow in switch.flows:
132 1
            if dpid not in self.stored_flows:
133
                log.info('A consistency problem was detected in '
134
                         f'switch {dpid}.')
135
                flow = {'flows': [installed_flow.as_dict()]}
136
                command = 'delete_strict'
137
                self._install_flows(command, flow, [switch])
138
                log.info(f'Flow forwarded to switch {dpid} to be deleted.')
139
            else:
140 1
                serializer = FlowFactory.get_class(switch)
141 1
                stored_flows = self.stored_flows[dpid]['flow_list']
142 1
                stored_flows_list = [serializer.from_dict(stored_flow['flow'],
143
                                                          switch)
144
                                     for stored_flow in stored_flows]
145
146 1
                if installed_flow not in stored_flows_list:
147 1
                    log.info('A consistency problem was detected in '
148
                             f'switch {dpid}.')
149 1
                    flow = {'flows': [installed_flow.as_dict()]}
150 1
                    command = 'delete_strict'
151 1
                    self._install_flows(command, flow, [switch])
152 1
                    log.info(f'Flow forwarded to switch {dpid} to be deleted.')
153
154
    # pylint: disable=attribute-defined-outside-init
155 1
    def _load_flows(self):
156
        """Load stored flows."""
157 1
        try:
158 1
            data = self.storehouse.get_data()['flow_persistence']
159 1
            if 'id' in data:
160
                del data['id']
161 1
            self.stored_flows = data
162
        except (KeyError, FileNotFoundError) as error:
163
            log.debug(f'There are no flows to load: {error}')
164
        else:
165 1
            log.info('Flows loaded.')
166
167 1
    def _store_changed_flows(self, command, flow, switch):
168
        """Store changed flows.
169
170
        Args:
171
            command: Flow command to be installed
172
            flow: Flows to be stored
173
            switch: Switch target
174
        """
175 1
        stored_flows_box = self.stored_flows.copy()
176
        # if the flow has a destination dpid it can be stored.
177 1
        if not switch:
178
            log.info('The Flow cannot be stored, the destination switch '
179
                     f'have not been specified: {switch}')
180
            return
181 1
        installed_flow = {}
182 1
        flow_list = []
183 1
        installed_flow['command'] = command
184 1
        installed_flow['flow'] = flow
185
186 1
        serializer = FlowFactory.get_class(switch)
187 1
        installed_flow_obj = serializer.from_dict(flow, switch)
188
189 1
        if switch.id not in stored_flows_box:
190
            # Switch not stored, add to box.
191 1
            flow_list.append(installed_flow)
192 1
            stored_flows_box[switch.id] = {'flow_list': flow_list}
193
        else:
194 1
            stored_flows = stored_flows_box[switch.id].get('flow_list', [])
195
            # Check if flow already stored
196 1
            for stored_flow in stored_flows:
197 1
                stored_flow_obj = serializer.from_dict(stored_flow['flow'],
198
                                                       switch)
199 1
                if installed_flow_obj == stored_flow_obj:
200 1
                    if stored_flow['command'] == installed_flow['command']:
201
                        log.debug('Data already stored.')
202
                        return
203
                    # Flow with inconsistency in "command" fields : Remove the
204
                    # old instruction. This happens when there is a stored
205
                    # instruction to install the flow, but the new instruction
206
                    # is to remove it. In this case, the old instruction is
207
                    # removed and the new one is stored.
208 1
                    stored_flow['command'] = installed_flow.get('command')
209 1
                    stored_flows.remove(stored_flow)
210 1
                    break
211
212 1
            stored_flows.append(installed_flow)
213 1
            stored_flows_box[switch.id]['flow_list'] = stored_flows
214
215 1
        stored_flows_box['id'] = 'flow_persistence'
216 1
        self.storehouse.save_flow(stored_flows_box)
217 1
        del stored_flows_box['id']
218 1
        self.stored_flows = stored_flows_box.copy()
219
220 1
    @rest('v2/flows')
221 1
    @rest('v2/flows/<dpid>')
222 1
    def list(self, dpid=None):
223
        """Retrieve all flows from a switch identified by dpid.
224
225
        If no dpid is specified, return all flows from all switches.
226
        """
227 1
        if dpid is None:
228 1
            switches = self.controller.switches.values()
229
        else:
230 1
            switches = [self.controller.get_switch_by_dpid(dpid)]
231
232 1
        switch_flows = {}
233
234 1
        for switch in switches:
235 1
            flows_dict = [flow.as_dict() for flow in switch.flows]
236 1
            switch_flows[switch.dpid] = {'flows': flows_dict}
237
238 1
        return jsonify(switch_flows)
239
240 1
    @rest('v2/flows', methods=['POST'])
241 1
    @rest('v2/flows/<dpid>', methods=['POST'])
242 1
    def add(self, dpid=None):
243
        """Install new flows in the switch identified by dpid.
244
245
        If no dpid is specified, install flows in all switches.
246
        """
247 1
        return self._send_flow_mods_from_request(dpid, "add")
248
249 1
    @rest('v2/delete', methods=['POST'])
250 1
    @rest('v2/delete/<dpid>', methods=['POST'])
251 1
    @rest('v2/flows', methods=['DELETE'])
252 1
    @rest('v2/flows/<dpid>', methods=['DELETE'])
253 1
    def delete(self, dpid=None):
254
        """Delete existing flows in the switch identified by dpid.
255
256
        If no dpid is specified, delete flows from all switches.
257
        """
258 1
        return self._send_flow_mods_from_request(dpid, "delete")
259
260 1
    def _get_all_switches_enabled(self):
261
        """Get a list of all switches enabled."""
262 1
        switches = self.controller.switches.values()
263 1
        return [switch for switch in switches if switch.is_enabled()]
264
265 1
    def _send_flow_mods_from_request(self, dpid, command, flows_dict=None):
266
        """Install FlowsMods from request."""
267 1
        if flows_dict is None:
268 1
            flows_dict = request.get_json()
269 1
            if flows_dict is None:
270 1
                return jsonify({"response": 'flows dict is none.'}), 404
271
272 1
        if dpid:
273 1
            switch = self.controller.get_switch_by_dpid(dpid)
274 1
            if not switch:
275 1
                return jsonify({"response": 'dpid not found.'}), 404
276 1
            elif switch.is_enabled() is False:
277 1
                if command == "delete":
278 1
                    self._install_flows(command, flows_dict, [switch])
279
                else:
280 1
                    return jsonify({"response": 'switch is disabled.'}), 404
281
            else:
282 1
                self._install_flows(command, flows_dict, [switch])
283
        else:
284 1
            self._install_flows(command, flows_dict,
285
                                self._get_all_switches_enabled())
286
287 1
        return jsonify({"response": "FlowMod Messages Sent"})
288
289 1
    def _install_flows(self, command, flows_dict, switches=[]):
290
        """Execute all procedures to install flows in the switches.
291
292
        Args:
293
            command: Flow command to be installed
294
            flows_dict: Dictionary with flows to be installed in the switches.
295
            switches: A list of switches
296
        """
297 1
        for switch in switches:
298 1
            serializer = FlowFactory.get_class(switch)
299 1
            flows = flows_dict.get('flows', [])
300 1
            for flow_dict in flows:
301 1
                flow = serializer.from_dict(flow_dict, switch)
302 1
                if command == "delete":
303
                    flow_mod = flow.as_of_delete_flow_mod()
304 1
                elif command == "delete_strict":
305 1
                    flow_mod = flow.as_of_strict_delete_flow_mod()
306 1
                elif command == "add":
307 1
                    flow_mod = flow.as_of_add_flow_mod()
308
                else:
309
                    raise InvalidCommandError
310 1
                self._send_flow_mod(flow.switch, flow_mod)
311 1
                self._add_flow_mod_sent(flow_mod.header.xid, flow, command)
312
313 1
                self._send_napp_event(switch, flow, command)
314 1
                self._store_changed_flows(command, flow_dict, switch)
315
316 1
    def _add_flow_mod_sent(self, xid, flow, command):
317
        """Add the flow mod to the list of flow mods sent."""
318 1
        if len(self._flow_mods_sent) >= self._flow_mods_sent_max_size:
319
            self._flow_mods_sent.popitem(last=False)
320 1
        self._flow_mods_sent[xid] = (flow, command)
321
322 1
    def _send_flow_mod(self, switch, flow_mod):
323 1
        event_name = 'kytos/flow_manager.messages.out.ofpt_flow_mod'
324
325 1
        content = {'destination': switch.connection,
326
                   'message': flow_mod}
327
328 1
        event = KytosEvent(name=event_name, content=content)
329 1
        self.controller.buffers.msg_out.put(event)
330
331 1
    def _send_napp_event(self, switch, flow, command, **kwargs):
332
        """Send an Event to other apps informing about a FlowMod."""
333 1
        if command == 'add':
334 1
            name = 'kytos/flow_manager.flow.added'
335 1
        elif command in ('delete', 'delete_strict'):
336 1
            name = 'kytos/flow_manager.flow.removed'
337 1
        elif command == 'error':
338 1
            name = 'kytos/flow_manager.flow.error'
339
        else:
340
            raise InvalidCommandError
341 1
        content = {'datapath': switch,
342
                   'flow': flow}
343 1
        content.update(kwargs)
344 1
        event_app = KytosEvent(name, content)
345 1
        self.controller.buffers.app.put(event_app)
346
347 1
    @listen_to('.*.of_core.*.ofpt_error')
348
    def handle_errors(self, event):
349
        """Receive OpenFlow error and send a event.
350
351
        The event is sent only if the error is related to a request made
352
        by flow_manager.
353
        """
354 1
        message = event.content["message"]
355
356 1
        connection = event.source
357 1
        switch = connection.switch
358
359 1
        xid = message.header.xid.value
360 1
        error_type = message.error_type
361 1
        error_code = message.code
362 1
        error_data = message.data.pack()
363
364
        # Get the packet responsible for the error
365 1
        error_packet = connection.protocol.unpack(error_data)
366
367 1
        if message.code == BadActionCode.OFPBAC_BAD_OUT_PORT:
368
            actions = []
369
            if hasattr(error_packet, 'actions'):
370
                # Get actions from the flow mod (OF 1.0)
371
                actions = error_packet.actions
372
            else:
373
                # Get actions from the list of flow mod instructions (OF 1.3)
374
                for instruction in error_packet.instructions:
375
                    actions.extend(instruction.actions)
376
377
            for action in actions:
378
                iface = switch.get_interface_by_port_no(action.port)
379
380
                # Set interface to drop packets forwarded to it
381
                if iface:
382
                    iface.config = PortConfig.OFPPC_NO_FWD
383
384 1
        try:
385 1
            flow, error_command = self._flow_mods_sent[xid]
386
        except KeyError:
387
            pass
388
        else:
389 1
            self._send_napp_event(flow.switch, flow, 'error',
390
                                  error_command=error_command,
391
                                  error_type=error_type, error_code=error_code)
392