Passed
Pull Request — master (#112)
by Carlos
03:51 queued 01:20
created

build.main.Main.setup()   A

Complexity

Conditions 4

Size

Total Lines 25
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 4

Importance

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