Passed
Pull Request — master (#125)
by
unknown
02:26
created

build.main.Main.on_flow_stats_check_consistency()   A

Complexity

Conditions 4

Size

Total Lines 10
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 14.7187

Importance

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