Passed
Push — master ( 5bb45b...07a00f )
by Humberto
02:40
created

build.main   B

Complexity

Total Complexity 45

Size/Duplication

Total Lines 279
Duplicated Lines 0 %

Test Coverage

Coverage 89.24%

Importance

Changes 0
Metric Value
eloc 168
dl 0
loc 279
ccs 141
cts 158
cp 0.8924
rs 8.8
c 0
b 0
f 0
wmc 45

16 Methods

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