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