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

build.main.Main._send_napp_event()   A

Complexity

Conditions 4

Size

Total Lines 15
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 4.0092

Importance

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