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

build.main.Main.check_storehouse_consistency()   B

Complexity

Conditions 5

Size

Total Lines 31
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 5.3906

Importance

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