Passed
Pull Request — master (#117)
by Carlos
02:59
created

build.main.Main._send_flow_mods_from_request()   B

Complexity

Conditions 7

Size

Total Lines 23
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 7

Importance

Changes 0
Metric Value
cc 7
eloc 17
nop 4
dl 0
loc 23
ccs 16
cts 16
cp 1
crap 7
rs 8
c 0
b 0
f 0
1
"""kytos/flow_manager NApp installs, lists and deletes switch flows."""
2 1
from collections import OrderedDict
3 1
from copy import deepcopy
4
5 1
from flask import jsonify, request
6 1
from pyof.v0x01.asynchronous.error_msg import BadActionCode
7 1
from pyof.v0x01.common.phy_port import PortConfig
8
9 1
from kytos.core import KytosEvent, KytosNApp, log, rest
10 1
from kytos.core.helpers import listen_to
11 1
from napps.kytos.flow_manager.match import match_flow
12 1
from napps.kytos.flow_manager.storehouse import StoreHouse
13 1
from napps.kytos.of_core.flow import FlowFactory
14
15 1
from .exceptions import InvalidCommandError
16 1
from .settings import CONSISTENCY_INTERVAL, FLOWS_DICT_MAX_SIZE
17
18
19 1
class Main(KytosNApp):
20
    """Main class to be used by Kytos controller."""
21
22 1
    def setup(self):
23
        """Replace the 'init' method for the KytosApp subclass.
24
25
        The setup method is automatically called by the run method.
26
        Users shouldn't call this method directly.
27
        """
28 1
        log.debug("flow-manager starting")
29 1
        self._flow_mods_sent = OrderedDict()
30 1
        self._flow_mods_sent_max_size = FLOWS_DICT_MAX_SIZE
31
32
        # Storehouse client to save and restore flow data:
33 1
        self.storehouse = StoreHouse(self.controller)
34
35
        # Format of stored flow data:
36
        # {'flow_persistence': {'dpid_str': {'flow_list': [
37
        #                                     {'command': '<add|delete>',
38
        #                                      'flow': {flow_dict}}]}}}
39 1
        self.stored_flows = {}
40 1
        self.resent_flows = set()
41 1
        if CONSISTENCY_INTERVAL > 0:
42 1
            self.execute_as_loop(CONSISTENCY_INTERVAL)
43
44 1
    def execute(self):
45
        """Run once on NApp 'start' or in a loop.
46
47
        The execute method is called by the run method of KytosNApp class.
48
        Users shouldn't call this method directly.
49
        """
50
        self._load_flows()
51
52
        if CONSISTENCY_INTERVAL > 0:
53
            self.consistency_check()
54
55 1
    def shutdown(self):
56
        """Shutdown routine of the NApp."""
57
        log.debug("flow-manager stopping")
58
59 1
    @listen_to('kytos/of_core.handshake.completed')
60
    def resend_stored_flows(self, event):
61
        """Resend stored Flows."""
62 1
        switch = event.content['switch']
63 1
        dpid = str(switch.dpid)
64
        # This can be a problem because this code is running a thread
65 1
        if dpid in self.resent_flows:
66
            log.debug(f'Flow already resent to the switch {dpid}')
67
            return
68 1
        if dpid in self.stored_flows:
69 1
            flow_list = self.stored_flows[dpid]['flow_list']
70 1
            for flow in flow_list:
71 1
                command = flow['command']
72 1
                flows_dict = {"flows": [flow['flow']]}
73 1
                self._install_flows(command, flows_dict, [switch])
74 1
            self.resent_flows.add(dpid)
75 1
            log.info(f'Flows resent to Switch {dpid}')
76
77 1
    def consistency_check(self):
78
        """Check the consistency of flows in each switch."""
79
        switches = self.controller.switches.values()
80
81
        for switch in switches:
82
            # Check if a dpid is a key in 'stored_flows' dictionary
83
            if switch.is_enabled():
84
                self.check_storehouse_consistency(switch)
85
86
                if switch.dpid in self.stored_flows:
87
                    self.check_switch_consistency(switch)
88
89 1
    def check_switch_consistency(self, switch):
90
        """Check consistency of installed flows for a specific switch."""
91 1
        dpid = switch.dpid
92
93
        # Flows stored in storehouse
94 1
        stored_flows = self.stored_flows[dpid]['flow_list']
95
96 1
        serializer = FlowFactory.get_class(switch)
97
98 1
        for stored_flow in stored_flows:
99 1
            command = stored_flow['command']
100 1
            stored_flow_obj = serializer.from_dict(stored_flow['flow'], switch)
101
102 1
            flow = {'flows': [stored_flow['flow']]}
103
104 1
            if stored_flow_obj not in switch.flows:
105 1
                if command == 'add':
106 1
                    log.info('A consistency problem was detected in '
107
                             f'switch {dpid}.')
108 1
                    self._install_flows(command, flow, [switch])
109 1
                    log.info(f'Flow forwarded to switch {dpid} to be '
110
                             'installed.')
111 1
            elif command == 'delete':
112 1
                log.info('A consistency problem was detected in '
113
                         f'switch {dpid}.')
114 1
                command = 'delete_strict'
115 1
                self._install_flows(command, flow, [switch])
116 1
                log.info(f'Flow forwarded to switch {dpid} to be deleted.')
117
118 1
    def check_storehouse_consistency(self, switch):
119
        """Check consistency of installed flows for a specific switch."""
120 1
        dpid = switch.dpid
121
122 1
        for installed_flow in switch.flows:
123 1
            if dpid not in self.stored_flows:
124
                log.info('A consistency problem was detected in '
125
                         f'switch {dpid}.')
126
                flow = {'flows': [installed_flow.as_dict()]}
127
                command = 'delete_strict'
128
                self._install_flows(command, flow, [switch])
129
                log.info(f'Flow forwarded to switch {dpid} to be deleted.')
130
            else:
131 1
                serializer = FlowFactory.get_class(switch)
132 1
                stored_flows = self.stored_flows[dpid]['flow_list']
133 1
                stored_flows_list = [serializer.from_dict(stored_flow['flow'],
134
                                                          switch)
135
                                     for stored_flow in stored_flows]
136
137 1
                if installed_flow not in stored_flows_list:
138 1
                    log.info('A consistency problem was detected in '
139
                             f'switch {dpid}.')
140 1
                    flow = {'flows': [installed_flow.as_dict()]}
141 1
                    command = 'delete_strict'
142 1
                    self._install_flows(command, flow, [switch])
143 1
                    log.info(f'Flow forwarded to switch {dpid} to be deleted.')
144
145
    # pylint: disable=attribute-defined-outside-init
146 1
    def _load_flows(self):
147
        """Load stored flows."""
148 1
        try:
149 1
            data = self.storehouse.get_data()['flow_persistence']
150 1
            if 'id' in data:
151
                del data['id']
152 1
            self.stored_flows = data
153
        except (KeyError, FileNotFoundError) as error:
154
            log.debug(f'There are no flows to load: {error}')
155
        else:
156 1
            log.info('Flows loaded.')
157
158 1
    def _store_changed_flows(self, command, flow, switch):
159
        """Store changed flows.
160
161
        Args:
162
            command: Flow command to be installed
163
            flow: Flows to be stored
164
            switch: Switch target
165
        """
166 1
        stored_flows_box = deepcopy(self.stored_flows)
167
        # if the flow has a destination dpid it can be stored.
168 1
        if not switch:
169
            log.info('The Flow cannot be stored, the destination switch '
170
                     f'have not been specified: {switch}')
171
            return
172 1
        installed_flow = {}
173 1
        flow_list = []
174 1
        installed_flow['command'] = command
175 1
        installed_flow['flow'] = flow
176 1
        deleted_flows = []
177
178 1
        serializer = FlowFactory.get_class(switch)
179 1
        installed_flow_obj = serializer.from_dict(flow, switch)
180
181 1
        if switch.id not in stored_flows_box:
182
            # Switch not stored, add to box.
183 1
            flow_list.append(installed_flow)
184 1
            stored_flows_box[switch.id] = {'flow_list': flow_list}
185
        else:
186 1
            stored_flows = stored_flows_box[switch.id].get('flow_list', [])
187
            # Check if flow already stored
188 1
            for stored_flow in stored_flows:
189 1
                stored_flow_obj = serializer.from_dict(stored_flow['flow'],
190
                                                       switch)
191
192 1
                version = switch.connection.protocol.version
193
194 1
                if installed_flow['command'] == 'delete':
195
                    # No strict match
196 1
                    if match_flow(flow, version, stored_flow['flow']):
197 1
                        deleted_flows.append(stored_flow)
198
199 1
                elif installed_flow_obj == stored_flow_obj:
200 1
                    if stored_flow['command'] == installed_flow['command']:
201
                        log.debug('Data already stored.')
202
                        return
203
                    # Flow with inconsistency in "command" fields : Remove the
204
                    # old instruction. This happens when there is a stored
205
                    # instruction to install the flow, but the new instruction
206
                    # is to remove it. In this case, the old instruction is
207
                    # removed and the new one is stored.
208 1
                    stored_flow['command'] = installed_flow.get('command')
209 1
                    deleted_flows.append(stored_flow)
210 1
                    break
211
212
            # if installed_flow['command'] != 'delete':
213 1
            stored_flows.append(installed_flow)
214 1
            for i in deleted_flows:
215 1
                stored_flows.remove(i)
216 1
            stored_flows_box[switch.id]['flow_list'] = stored_flows
217
218 1
        stored_flows_box['id'] = 'flow_persistence'
219 1
        self.storehouse.save_flow(stored_flows_box)
220 1
        del stored_flows_box['id']
221 1
        self.stored_flows = deepcopy(stored_flows_box)
222
223 1
    @rest('v2/flows')
224 1
    @rest('v2/flows/<dpid>')
225 1
    def list(self, dpid=None):
226
        """Retrieve all flows from a switch identified by dpid.
227
228
        If no dpid is specified, return all flows from all switches.
229
        """
230 1
        if dpid is None:
231 1
            switches = self.controller.switches.values()
232
        else:
233 1
            switches = [self.controller.get_switch_by_dpid(dpid)]
234
235 1
        switch_flows = {}
236
237 1
        for switch in switches:
238 1
            flows_dict = [flow.as_dict() for flow in switch.flows]
239 1
            switch_flows[switch.dpid] = {'flows': flows_dict}
240
241 1
        return jsonify(switch_flows)
242
243 1
    @rest('v2/flows', methods=['POST'])
244 1
    @rest('v2/flows/<dpid>', methods=['POST'])
245 1
    def add(self, dpid=None):
246
        """Install new flows in the switch identified by dpid.
247
248
        If no dpid is specified, install flows in all switches.
249
        """
250 1
        return self._send_flow_mods_from_request(dpid, "add")
251
252 1
    @rest('v2/delete', methods=['POST'])
253 1
    @rest('v2/delete/<dpid>', methods=['POST'])
254 1
    @rest('v2/flows', methods=['DELETE'])
255 1
    @rest('v2/flows/<dpid>', methods=['DELETE'])
256 1
    def delete(self, dpid=None):
257
        """Delete existing flows in the switch identified by dpid.
258
259
        If no dpid is specified, delete flows from all switches.
260
        """
261 1
        return self._send_flow_mods_from_request(dpid, "delete")
262
263 1
    def _get_all_switches_enabled(self):
264
        """Get a list of all switches enabled."""
265 1
        switches = self.controller.switches.values()
266 1
        return [switch for switch in switches if switch.is_enabled()]
267
268 1
    def _send_flow_mods_from_request(self, dpid, command, flows_dict=None):
269
        """Install FlowsMods from request."""
270 1
        if flows_dict is None:
271 1
            flows_dict = request.get_json()
272 1
            if flows_dict is None:
273 1
                return jsonify({"response": 'flows dict is none.'}), 404
274
275 1
        if dpid:
276 1
            switch = self.controller.get_switch_by_dpid(dpid)
277 1
            if not switch:
278 1
                return jsonify({"response": 'dpid not found.'}), 404
279 1
            elif switch.is_enabled() is False:
280 1
                if command == "delete":
281 1
                    self._install_flows(command, flows_dict, [switch])
282
                else:
283 1
                    return jsonify({"response": 'switch is disabled.'}), 404
284
            else:
285 1
                self._install_flows(command, flows_dict, [switch])
286
        else:
287 1
            self._install_flows(command, flows_dict,
288
                                self._get_all_switches_enabled())
289
290 1
        return jsonify({"response": "FlowMod Messages Sent"})
291
292 1
    def _install_flows(self, command, flows_dict, switches=[]):
293
        """Execute all procedures to install flows in the switches.
294
295
        Args:
296
            command: Flow command to be installed
297
            flows_dict: Dictionary with flows to be installed in the switches.
298
            switches: A list of switches
299
        """
300 1
        for switch in switches:
301 1
            serializer = FlowFactory.get_class(switch)
302 1
            flows = flows_dict.get('flows', [])
303 1
            for flow_dict in flows:
304 1
                flow = serializer.from_dict(flow_dict, switch)
305 1
                if command == "delete":
306
                    flow_mod = flow.as_of_delete_flow_mod()
307 1
                elif command == "delete_strict":
308 1
                    flow_mod = flow.as_of_strict_delete_flow_mod()
309 1
                elif command == "add":
310 1
                    flow_mod = flow.as_of_add_flow_mod()
311
                else:
312
                    raise InvalidCommandError
313 1
                self._send_flow_mod(flow.switch, flow_mod)
314 1
                self._add_flow_mod_sent(flow_mod.header.xid, flow, command)
315
316 1
                self._send_napp_event(switch, flow, command)
317 1
                self._store_changed_flows(command, flow_dict, switch)
318
319 1
    def _add_flow_mod_sent(self, xid, flow, command):
320
        """Add the flow mod to the list of flow mods sent."""
321 1
        if len(self._flow_mods_sent) >= self._flow_mods_sent_max_size:
322
            self._flow_mods_sent.popitem(last=False)
323 1
        self._flow_mods_sent[xid] = (flow, command)
324
325 1
    def _send_flow_mod(self, switch, flow_mod):
326 1
        event_name = 'kytos/flow_manager.messages.out.ofpt_flow_mod'
327
328 1
        content = {'destination': switch.connection,
329
                   'message': flow_mod}
330
331 1
        event = KytosEvent(name=event_name, content=content)
332 1
        self.controller.buffers.msg_out.put(event)
333
334 1
    def _send_napp_event(self, switch, flow, command, **kwargs):
335
        """Send an Event to other apps informing about a FlowMod."""
336 1
        if command == 'add':
337 1
            name = 'kytos/flow_manager.flow.added'
338 1
        elif command in ('delete', 'delete_strict'):
339 1
            name = 'kytos/flow_manager.flow.removed'
340 1
        elif command == 'error':
341 1
            name = 'kytos/flow_manager.flow.error'
342
        else:
343
            raise InvalidCommandError
344 1
        content = {'datapath': switch,
345
                   'flow': flow}
346 1
        content.update(kwargs)
347 1
        event_app = KytosEvent(name, content)
348 1
        self.controller.buffers.app.put(event_app)
349
350 1
    @listen_to('.*.of_core.*.ofpt_error')
351
    def handle_errors(self, event):
352
        """Receive OpenFlow error and send a event.
353
354
        The event is sent only if the error is related to a request made
355
        by flow_manager.
356
        """
357 1
        message = event.content["message"]
358
359 1
        connection = event.source
360 1
        switch = connection.switch
361
362 1
        xid = message.header.xid.value
363 1
        error_type = message.error_type
364 1
        error_code = message.code
365 1
        error_data = message.data.pack()
366
367
        # Get the packet responsible for the error
368 1
        error_packet = connection.protocol.unpack(error_data)
369
370 1
        if message.code == BadActionCode.OFPBAC_BAD_OUT_PORT:
371
            actions = []
372
            if hasattr(error_packet, 'actions'):
373
                # Get actions from the flow mod (OF 1.0)
374
                actions = error_packet.actions
375
            else:
376
                # Get actions from the list of flow mod instructions (OF 1.3)
377
                for instruction in error_packet.instructions:
378
                    actions.extend(instruction.actions)
379
380
            for action in actions:
381
                iface = switch.get_interface_by_port_no(action.port)
382
383
                # Set interface to drop packets forwarded to it
384
                if iface:
385
                    iface.config = PortConfig.OFPPC_NO_FWD
386
387 1
        try:
388 1
            flow, error_command = self._flow_mods_sent[xid]
389
        except KeyError:
390
            pass
391
        else:
392 1
            self._send_napp_event(flow.switch, flow, 'error',
393
                                  error_command=error_command,
394
                                  error_type=error_type, error_code=error_code)
395