Passed
Pull Request — master (#112)
by Carlos
02:22
created

build.main.Main.check_switch_consistency()   A

Complexity

Conditions 5

Size

Total Lines 27
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 5

Importance

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