Test Failed
Pull Request — master (#96)
by Jose
03:45
created

build.main.Main._send_flow_mod()   A

Complexity

Conditions 1

Size

Total Lines 8
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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