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