Test Failed
Pull Request — master (#96)
by Jose
01:58
created

build.main.Main._load_flows()   A

Complexity

Conditions 4

Size

Total Lines 12
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 4

Importance

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