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

build.main.Main.shutdown()   A

Complexity

Conditions 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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