Test Failed
Pull Request — master (#127)
by Carlos
02:13
created

build.main.cast_fields()   B

Complexity

Conditions 6

Size

Total Lines 14
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 6

Importance

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