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

build.main.Main._resolve_inconsistency()   A

Complexity

Conditions 1

Size

Total Lines 5
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

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