Passed
Pull Request — master (#126)
by
unknown
02:42
created

build.main.Main.handle_errors()   B

Complexity

Conditions 8

Size

Total Lines 45
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 14.1606

Importance

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