Test Failed
Pull Request — master (#90)
by
unknown
01:20
created

build.main   B

Complexity

Total Complexity 51

Size/Duplication

Total Lines 279
Duplicated Lines 0 %

Test Coverage

Coverage 92.71%

Importance

Changes 0
Metric Value
eloc 179
dl 0
loc 279
rs 7.92
c 0
b 0
f 0
ccs 89
cts 96
cp 0.9271
wmc 51

17 Methods

Rating   Name   Duplication   Size   Complexity  
A Main.list() 0 19 3
A Main._load_flows() 0 12 4
B Main._send_flow_mods_from_request() 0 21 6
A Main._send_flow_mod() 0 8 1
A Main.delete() 0 10 1
B Main.resend_stored_flows() 0 22 5
A Main._get_all_switches_enabled() 0 4 1
B Main._generate_match_fields() 0 13 6
A Main._send_napp_event() 0 15 4
A Main.shutdown() 0 3 1
B Main._store_changed_flows() 0 42 6
A Main.setup() 0 14 1
A Main.execute() 0 7 1
A Main._install_flows() 0 24 5
A Main.handle_errors() 0 17 3
A Main.add() 0 8 1
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 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
        # object to save and load flows
29
        self.storehouse = StoreHouse(self.controller)
30
        self.stored_flows = {}
31
        self.resended_flows = set()
32
33
    def execute(self):
34 1
        """Run once on NApp 'start' or in a loop.
35
36
        The execute method is called by the run method of KytosNApp class.
37
        Users shouldn't call this method directly.
38 1
        """
39 1
        self._load_flows()
40 1
41
    def shutdown(self):
42
        """Shutdown routine of the NApp."""
43
        log.debug("flow-manager stopping")
44
45 1
    @listen_to('kytos/topology.port.created')
46 1
    def resend_stored_flows(self, event):
47
        """Resend stored Flows."""
48 1
        dpid = str(event.content['switch'])
49
        switch = self.controller.get_switch_by_dpid(dpid)
50 1
        # This can be a problem because this code is running a thread
51
        if dpid in self.resended_flows:
52 1
            log.debug(f'Flow already resended to Switch {dpid}')
53 1
            return None
54 1
        if dpid in self.stored_flows:
55
            try:
56 1
                flow_list = self.stored_flows[dpid]['flow_list']
57
            except KeyError as error:
58 1
                log.info(f'Error to resend stored flow: {error}')
59 1
                return None
60 1
            for flow in flow_list:
61
                command = flow.get('command')
62
                flows_dict = flow.get('data')
63
                self._install_flows(command, flows_dict, [switch])
64
            self.resended_flows.add(dpid)
65 1
            log.info(f'Flows resended to Switch {dpid}')
66
        return None
67 1
68 1
    # pylint: disable=attribute-defined-outside-init
69 1
    def _load_flows(self):
70 1
        """Load stored flows."""
71 1
        try:
72
            data = self.storehouse.get_data()['flow_persistence']
73
            if 'id' in data:
74
                del data['id']
75
            self.stored_flows = data
76 1
77
        except (KeyError) as error:
78 1
            log.info(f'There are no flows to load : {error}')
79
        else:
80 1
            log.info('Flows loaded.')
81 1
82
    @staticmethod
83 1
    def _generate_match_fields(flows):
84
        """Generate flow match fields."""
85 1
        match_fields = {}
86
        for fields in flows['flows']:
87 1
            if 'priority' in fields:
88 1
                match_fields['priority'] = fields.get('priority')
89
            if 'cookie' in fields:
90 1
                match_fields['cookie'] = fields.get('cookie')
91 1
            if 'match' in fields:
92 1
                for field, value in fields['match'].items():
93 1
                    match_fields[field] = value
94 1
        return match_fields
95 1
96
    def _store_changed_flows(self, command, flows, switches):
97 1
        """Store changed flows."""
98
        store_box_updated = self.stored_flows.copy()
99 1
        for switch in switches:
100
            new_flow = {}
101
            flow_list = []
102 1
            new_flow['command'] = command
103
            # The fields to check if the flow is already stored.
104 1
            new_flow['match_fields'] = self._generate_match_fields(flows)
105
            new_flow['data'] = flows
106
107
            if switch.id not in store_box_updated:
108
                # Switch not stored, add to box.
109
                flow_list.append(new_flow)
110
                store_box_updated[switch.id] = {"flow_list": flow_list}
111
                continue
112 1
113 1
            stored_flows = store_box_updated[switch.id]['flow_list']
114 1
115 1
            # Check if flow already stored
116 1
            for stored_flow in stored_flows:
117 1
                if new_flow['match_fields'] == stored_flow['match_fields']:
118
                    if new_flow['command'] == stored_flow['command']:
119 1
                        log.debug('Data already stored.')
120 1
                        return None
121
                    else:
122
                        # Command conflict. Remove the old flow.
123 1
                        # Example: Instruction to add new flow but exist
124 1
                        # a stored instruction to remove this flow.
125
                        # Remove old, and save the new instruction.
126 1
                        stored_flow['command'] = new_flow.get('command')
127
                        stored_flows.remove(stored_flow)
128 1
                        break
129
130 1
            stored_flows.append(new_flow)
131
            store_box_updated[switch.id]['flow_list'] = stored_flows
132 1
133
        store_box_updated['id'] = 'flow_persistence'
134 1
        self.storehouse.save_flow(store_box_updated)
135 1
        del store_box_updated['id']
136
        self.stored_flows = store_box_updated.copy()
137 1
        return None
138
139
    @rest('v2/flows')
140 1
    @rest('v2/flows/<dpid>')
141 1
    def list(self, dpid=None):
142
        """Retrieve all flows from a switch identified by dpid.
143 1
144
        If no dpid is specified, return all flows from all switches.
145 1
        """
146 1
        if dpid is None:
147 1
            switches = self.controller.switches.values()
148 1
        else:
149 1
            switches = [self.controller.get_switch_by_dpid(dpid)]
150 1
151
        switch_flows = {}
152
153 1
        for switch in switches:
154
            flows_dict = [flow.as_dict() for flow in switch.flows]
155 1
            switch_flows[switch.dpid] = {'flows': flows_dict}
156 1
157 1
        return jsonify(switch_flows)
158
159 1
    @rest('v2/flows', methods=['POST'])
160
    @rest('v2/flows/<dpid>', methods=['POST'])
161
    def add(self, dpid=None):
162
        """Install new flows in the switch identified by dpid.
163
164
        If no dpid is specified, install flows in all switches.
165
        """
166 1
        return self._send_flow_mods_from_request(dpid, "add")
167 1
168 1
    @rest('v2/delete', methods=['POST'])
169 1
    @rest('v2/delete/<dpid>', methods=['POST'])
170 1
    @rest('v2/flows', methods=['DELETE'])
171
    @rest('v2/flows/<dpid>', methods=['DELETE'])
172
    def delete(self, dpid=None):
173
        """Delete existing flows in the switch identified by dpid.
174 1
175
        If no dpid is specified, delete flows from all switches.
176
        """
177
        return self._send_flow_mods_from_request(dpid, "delete")
178
179
    def _get_all_switches_enabled(self):
180
        """Get a list of all switches enabled."""
181
        switches = self.controller.switches.values()
182
        return [switch for switch in switches if switch.is_enabled()]
183
184
    def _send_flow_mods_from_request(self, dpid, command, flows_dict=None):
185
        """Install FlowsMods from request."""
186
        if flows_dict is None:
187
            flows_dict = request.get_json()
188
189
        if flows_dict is None:
190
            return jsonify({"response": 'flows dict is none.'}), 404
191
192
        if dpid:
193
            switch = self.controller.get_switch_by_dpid(dpid)
194
            if not switch:
195
                return jsonify({"response": 'dpid not found.'}), 404
196
            elif switch.is_enabled() is False:
197
                return jsonify({"response": 'switch is disabled.'}), 404
198
            else:
199
                self._install_flows(command, flows_dict, [switch])
200
        else:
201
            self._install_flows(command, flows_dict,
202
                                self._get_all_switches_enabled())
203
204
        return jsonify({"response": "FlowMod Messages Sent"})
205
206
    def _install_flows(self, command, flows_dict, switches=[]):
207
        """Execute all procedures to install flows in the switches.
208
209
        Args:
210
            command: Flow command to be installed
211
            flows_dict: Dictionary with flows to be installed in the switches.
212
            switches: A list of switches
213
        """
214
        for switch in switches:
215
            serializer = FlowFactory.get_class(switch)
216
            flows = flows_dict.get('flows', [])
217
            for flow_dict in flows:
218
                flow = serializer.from_dict(flow_dict, switch)
219
                if command == "delete":
220
                    flow_mod = flow.as_of_delete_flow_mod()
221
                elif command == "add":
222
                    flow_mod = flow.as_of_add_flow_mod()
223
                else:
224
                    raise InvalidCommandError
225
                self._send_flow_mod(flow.switch, flow_mod)
226
                self._add_flow_mod_sent(flow_mod.header.xid, flow)
227
228
                self._send_napp_event(switch, flow, command)
229
        self._store_changed_flows(command, flows_dict, switches)
230
231
    def _add_flow_mod_sent(self, xid, flow):
232
        """Add the flow mod to the list of flow mods sent."""
233
        if len(self._flow_mods_sent) >= self._flow_mods_sent_max_size:
234
            self._flow_mods_sent.popitem(last=False)
235
        self._flow_mods_sent[xid] = flow
236
237
    def _send_flow_mod(self, switch, flow_mod):
238
        event_name = 'kytos/flow_manager.messages.out.ofpt_flow_mod'
239
240
        content = {'destination': switch.connection,
241
                   'message': flow_mod}
242
243
        event = KytosEvent(name=event_name, content=content)
244
        self.controller.buffers.msg_out.put(event)
245
246
    def _send_napp_event(self, switch, flow, command, **kwargs):
247
        """Send an Event to other apps informing about a FlowMod."""
248
        if command == 'add':
249
            name = 'kytos/flow_manager.flow.added'
250
        elif command == 'delete':
251
            name = 'kytos/flow_manager.flow.removed'
252
        elif command == 'error':
253
            name = 'kytos/flow_manager.flow.error'
254
        else:
255
            raise InvalidCommandError
256
        content = {'datapath': switch,
257
                   'flow': flow}
258
        content.update(kwargs)
259
        event_app = KytosEvent(name, content)
260
        self.controller.buffers.app.put(event_app)
261
262
    @listen_to('.*.of_core.*.ofpt_error')
263
    def handle_errors(self, event):
264
        """Receive OpenFlow error and send a event.
265
266
        The event is sent only if the error is related to a request made
267
        by flow_manager.
268
        """
269
        xid = event.content["message"].header.xid.value
270
        error_type = event.content["message"].error_type
271
        error_code = event.content["message"].code
272
        try:
273
            flow = self._flow_mods_sent[xid]
274
        except KeyError:
275
            pass
276
        else:
277
            self._send_napp_event(flow.switch, flow, 'error',
278
                                  error_type=error_type, error_code=error_code)
279