Passed
Push — master ( ba1141...da4202 )
by Humberto
04:01
created

build.main.Main._add_flow_mod_sent()   A

Complexity

Conditions 2

Size

Total Lines 5
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2.0625

Importance

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