Test Failed
Pull Request — master (#96)
by Jose
02:32
created

build.main   D

Complexity

Total Complexity 59

Size/Duplication

Total Lines 347
Duplicated Lines 0 %

Test Coverage

Coverage 92.71%

Importance

Changes 0
Metric Value
eloc 214
dl 0
loc 347
rs 4.08
c 0
b 0
f 0
ccs 89
cts 96
cp 0.9271
wmc 59

19 Methods

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

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