Passed
Pull Request — master (#90)
by
unknown
02:10
created

build.main   B

Complexity

Total Complexity 50

Size/Duplication

Total Lines 276
Duplicated Lines 0 %

Test Coverage

Coverage 86.39%

Importance

Changes 0
Metric Value
eloc 178
dl 0
loc 276
ccs 146
cts 169
cp 0.8639
rs 8.4
c 0
b 0
f 0
wmc 50

17 Methods

Rating   Name   Duplication   Size   Complexity  
A Main.shutdown() 0 3 1
A Main.setup() 0 14 1
A Main.execute() 0 7 1
A Main.list() 0 19 3
B Main._send_flow_mods_from_request() 0 21 6
A Main._send_flow_mod() 0 8 1
A Main.delete() 0 10 1
A Main._get_all_switches_enabled() 0 4 1
A Main._send_napp_event() 0 15 4
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
A Main._load_flows() 0 12 3
B Main.resend_stored_flows() 0 20 5
B Main._generate_match_fields() 0 13 6
B Main._flows_change() 0 41 6

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
        # object to save and load flows
29 1
        self.storehouse = StoreHouse(self.controller)
30 1
        self.stored_flows = {}
31 1
        self.resended_flows = []
32
33 1
    def execute(self):
34
        """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
        """
39
        self._load_flows()
40
41 1
    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
    def resend_stored_flows(self, event):
47
        """Resend stored Flows."""
48 1
        dpid = str(event.content['switch'])
49 1
        switch = self.controller.get_switch_by_dpid(dpid)
50 1
        if dpid in self.resended_flows:
51
            log.debug(f'Flow already resended to Switch {dpid}')
52
            return
53 1
        if dpid in self.stored_flows:
54 1
            try:
55 1
                flow_list = self.stored_flows[dpid]['flow_list']
56
            except KeyError as error:
57
                log.info(f'Error to resend stored flow:{error}')
58
                return
59 1
            for flow in flow_list:
60 1
                command = flow['command']
61 1
                flows_dict = flow['data']
62 1
                self._install_flows(command, flows_dict, [switch])
63 1
            self.resended_flows.append(dpid)
64 1
            log.info(f'Flows resended to Switch {dpid}')
65
66
    # pylint: disable=attribute-defined-outside-init
67 1
    def _load_flows(self):
68
        """Load stored flows."""
69 1
        try:
70 1
            data = self.storehouse.get_data()['flow_persistence']
71 1
            if 'id' in data:
72
                del data['id']
73 1
            self.stored_flows = data
74
75
        except (KeyError) as error:
76
            log.info(f'There are no flows to load : {error}')
77
            return
78 1
        log.info('Flows loaded.')
79
80 1
    @staticmethod
81
    def _generate_match_fields(flows):
82
        """Generate flow match fields."""
83 1
        match_fields = {}
84 1
        for fields in flows['flows']:
85 1
            if 'priority' in fields:
86 1
                match_fields['priority'] = fields['priority']
87 1
            if 'cookie' in fields:
88 1
                match_fields['cookie'] = fields['cookie']
89 1
            if 'match' in fields:
90 1
                for field, value in fields['match'].items():
91 1
                    match_fields[field] = value
92 1
        return match_fields
93
94 1
    def _flows_change(self, command, flows, switches):
95
        """Store changed flows."""
96 1
        store_box_updated = self.stored_flows.copy()
97 1
        for switch in switches:
98 1
            new_flow = {}
99 1
            flow_list = []
100 1
            new_flow['command'] = command
101
            # The fields to check if the flow is already stored.
102 1
            new_flow['match_fields'] = self._generate_match_fields(flows)
103 1
            new_flow['data'] = flows
104
105 1
            if switch.id not in store_box_updated:
106
                # Switch not stored, add to box.
107 1
                flow_list.append(new_flow)
108 1
                store_box_updated[switch.id] = {"flow_list": flow_list}
109 1
                continue
110
111 1
            stored_flows = store_box_updated[switch.id]['flow_list']
112
113
            # Check if flow already stored
114 1
            for stored_flow in stored_flows:
115 1
                if new_flow['match_fields'] == stored_flow['match_fields']:
116
                    if new_flow['command'] == stored_flow['command']:
117
                        log.info('Data already stored')
118
                        return
119
                    else:
120
                        # Command conflict. Remove the old flow.
121
                        # Example: Instruction to add new flow but exist
122
                        # a stored instruction to remove this flow.
123
                        # Remove old, and save the new instruction.
124
                        stored_flow['command'] = new_flow['command']
125
                        stored_flows.remove(stored_flow)
126
                        break
127
128 1
            stored_flows.append(new_flow)
129 1
            store_box_updated[switch.id]['flow_list'] = stored_flows
130
131 1
        store_box_updated['id'] = 'flow_persistence'
132 1
        self.storehouse.save_flow(store_box_updated)
133 1
        del store_box_updated['id']
134 1
        self.stored_flows = store_box_updated.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
186 1
        if flows_dict is None:
187 1
            return jsonify({"response": 'flows dict is none.'}), 404
188
189 1
        if dpid:
190 1
            switch = self.controller.get_switch_by_dpid(dpid)
191 1
            if not switch:
192 1
                return jsonify({"response": 'dpid not found.'}), 404
193 1
            elif switch.is_enabled() is False:
194 1
                return jsonify({"response": 'switch is disabled.'}), 404
195
            else:
196 1
                self._install_flows(command, flows_dict, [switch])
197
        else:
198 1
            self._install_flows(command, flows_dict,
199
                                self._get_all_switches_enabled())
200
201 1
        return jsonify({"response": "FlowMod Messages Sent"})
202
203 1
    def _install_flows(self, command, flows_dict, switches=[]):
204
        """Execute all procedures to install flows in the switches.
205
206
        Args:
207
            command: Flow command to be installed
208
            flows_dict: Dictionary with flows to be installed in the switches.
209
            switches: A list of switches
210
        """
211 1
        for switch in switches:
212 1
            serializer = FlowFactory.get_class(switch)
213 1
            flows = flows_dict.get('flows', [])
214 1
            for flow_dict in flows:
215 1
                flow = serializer.from_dict(flow_dict, switch)
216 1
                if command == "delete":
217
                    flow_mod = flow.as_of_delete_flow_mod()
218 1
                elif command == "add":
219 1
                    flow_mod = flow.as_of_add_flow_mod()
220
                else:
221
                    raise InvalidCommandError
222 1
                self._send_flow_mod(flow.switch, flow_mod)
223 1
                self._add_flow_mod_sent(flow_mod.header.xid, flow)
224
225 1
                self._send_napp_event(switch, flow, command)
226 1
        self._flows_change(command, flows_dict, switches)
227
228 1
    def _add_flow_mod_sent(self, xid, flow):
229
        """Add the flow mod to the list of flow mods sent."""
230 1
        if len(self._flow_mods_sent) >= self._flow_mods_sent_max_size:
231
            self._flow_mods_sent.popitem(last=False)
232 1
        self._flow_mods_sent[xid] = flow
233
234 1
    def _send_flow_mod(self, switch, flow_mod):
235 1
        event_name = 'kytos/flow_manager.messages.out.ofpt_flow_mod'
236
237 1
        content = {'destination': switch.connection,
238
                   'message': flow_mod}
239
240 1
        event = KytosEvent(name=event_name, content=content)
241 1
        self.controller.buffers.msg_out.put(event)
242
243 1
    def _send_napp_event(self, switch, flow, command, **kwargs):
244
        """Send an Event to other apps informing about a FlowMod."""
245 1
        if command == 'add':
246 1
            name = 'kytos/flow_manager.flow.added'
247 1
        elif command == 'delete':
248 1
            name = 'kytos/flow_manager.flow.removed'
249 1
        elif command == 'error':
250 1
            name = 'kytos/flow_manager.flow.error'
251
        else:
252
            raise InvalidCommandError
253 1
        content = {'datapath': switch,
254
                   'flow': flow}
255 1
        content.update(kwargs)
256 1
        event_app = KytosEvent(name, content)
257 1
        self.controller.buffers.app.put(event_app)
258
259 1
    @listen_to('.*.of_core.*.ofpt_error')
260
    def handle_errors(self, event):
261
        """Receive OpenFlow error and send a event.
262
263
        The event is sent only if the error is related to a request made
264
        by flow_manager.
265
        """
266 1
        xid = event.content["message"].header.xid.value
267 1
        error_type = event.content["message"].error_type
268 1
        error_code = event.content["message"].code
269 1
        try:
270 1
            flow = self._flow_mods_sent[xid]
271
        except KeyError:
272
            pass
273
        else:
274 1
            self._send_napp_event(flow.switch, flow, 'error',
275
                                  error_type=error_type, error_code=error_code)
276