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

build.main.Main._is_equal_flows()   A

Complexity

Conditions 2

Size

Total Lines 7
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2.0116

Importance

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