Test Failed
Pull Request — master (#90)
by Carlos
03:34
created

build.main.Main._add_flow_mod_sent()   A

Complexity

Conditions 2

Size

Total Lines 5
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

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