Test Failed
Pull Request — master (#90)
by Humberto
01:54
created

build.main.Main._generate_match_fields()   B

Complexity

Conditions 6

Size

Total Lines 14
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 6

Importance

Changes 0
Metric Value
cc 6
eloc 13
nop 1
dl 0
loc 14
ccs 10
cts 10
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
6 1
from kytos.core import KytosEvent, KytosNApp, log, rest
7 1
from kytos.core.helpers import listen_to
8 1
from napps.kytos.flow_manager.storehouse import StoreHouse
9
from napps.kytos.of_core.flow import FlowFactory
10 1
11 1
from .exceptions import InvalidCommandError
12
from .settings import FLOWS_DICT_MAX_SIZE
13
14 1
15
class Main(KytosNApp):
16
    """Main class to be used by Kytos controller."""
17 1
18
    def setup(self):
19
        """Replace the 'init' method for the KytosApp subclass.
20
21
        The setup method is automatically called by the run method.
22
        Users shouldn't call this method directly.
23 1
        """
24 1
        log.debug("flow-manager starting")
25 1
        self._flow_mods_sent = OrderedDict()
26
        self._flow_mods_sent_max_size = FLOWS_DICT_MAX_SIZE
27 1
28
        # Storehouse client to save and restore flow data:
29
        self.storehouse = StoreHouse(self.controller)
30
        
31
        # Format of stored flow data:
32
        # {'flow_persistence': {'dpid_str': {'flow_list': [
33
        #                                     {'command': '<add|delete>',
34 1
        #                                      'flow': {flow_dict}}]}}}
35
        self.stored_flows = {}        
36
        self.resent_flows = set()
37
38 1
    def execute(self):
39 1
        """Run once on NApp 'start' or in a loop.
40 1
41
        The execute method is called by the run method of KytosNApp class.
42
        Users shouldn't call this method directly.
43
        """
44
        self._load_flows()
45 1
46 1
    def shutdown(self):
47
        """Shutdown routine of the NApp."""
48 1
        log.debug("flow-manager stopping")
49
50 1
    @listen_to('kytos/topology.port.created')
51
    def resend_stored_flows(self, event):
52 1
        """Resend stored Flows."""
53 1
        dpid = str(event.content['switch'])
54 1
        switch = self.controller.get_switch_by_dpid(dpid)
55
        # This can be a problem because this code is running a thread
56 1
        if dpid in self.resent_flows:
57
            log.info(f'Flow already resended to Switch {dpid}')
58 1
            return
59 1
        if dpid in self.stored_flows:
60 1
            flow_list = self.stored_flows[dpid]['flow_list']
61
            for flow in flow_list:
62
                command = flow['command']
63
                flows_dict = {"flows": [flow['flow']]}
64
                self._install_flows(command, flows_dict, [switch])
65 1
            self.resent_flows.add(dpid)
66
            log.info(f'Flows resent to Switch {dpid}')
67 1
68 1
    # pylint: disable=attribute-defined-outside-init
69 1
    def _load_flows(self):
70 1
        """Load stored flows."""
71 1
        try:
72
            data = self.storehouse.get_data()['flow_persistence']
73
            if 'id' in data:
74
                del data['id']
75
            self.stored_flows = data
76 1
77
        except KeyError as error:
78 1
            log.debug(f'There are no flows to load: {error}')
79
        else:
80 1
            log.info('Flows loaded.')
81 1
82
    @staticmethod
83 1
    def _generate_match_fields(flows):
84
        """Generate flow match fields."""
85 1
        match_fields = {}
86
        flow = flows['flow']
87 1
        for field in flow:
88 1
            if 'priority' in field:
89
                match_fields['priority'] = flow['priority']
90 1
            if 'cookie' in field:
91 1
                match_fields['cookie'] = flow['cookie']
92 1
            if 'match' in field:
93 1
                for m_field, value in flow['match'].items():
94 1
                    match_fields[m_field] = value
95 1
        return match_fields
96
97 1
    def _is_equal_flows(self, flow_1, flow_2):
98
        """Check if two flows are equal."""
99 1
        flow_1_match_fields = self._generate_match_fields(flow_1)
100
        flow_2_match_fields = self._generate_match_fields(flow_2)
101
        if flow_1_match_fields == flow_2_match_fields:
102 1
            return True
103
        return False
104 1
105
    def _store_changed_flows(self, command, flow, switch):
106
        """Store changed flows.
107
108
        Args:
109
            command: Flow command to be installed
110
            flow: Flows to be stored
111
            switch: Switch target
112 1
        """
113 1
        stored_flows_box = self.stored_flows.copy()
114 1
        # if the flow has a destination dpid it can be stored.
115 1
        if not switch:
116 1
            log.info('The Flow cannot be stored, the destination switch '
117 1
                     f'have not been specified: {switch}')
118
            return
119 1
120 1
        new_flow = {}
121
        flow_list = []
122
        new_flow['command'] = command
123 1
        new_flow['flow'] = flow
124 1
125
        if switch.id not in stored_flows_box:
126 1
            # Switch not stored, add to box.
127
            flow_list.append(new_flow)
128 1
            stored_flows_box[switch.id] = {"flow_list": flow_list}
129
        else:
130 1
            stored_flows = stored_flows_box[switch.id].get('flow_list', [])
131
            # Check if flow already stored
132 1
            for stored_flow in stored_flows:
133
                if self._is_equal_flows(new_flow, stored_flow):
134 1
                    if stored_flow['command'] == new_flow['command']:
135 1
                        log.debug('Data already stored.')
136
                        return
137 1
                    # Command conflict. Remove the old instruction.
138
                    # There is a stored instruction to install the flow,
139
                    # but the new instruction is to remove it.
140 1
                    # In this case, remove the old instruction
141 1
                    # and store the new.
142
                    stored_flow['command'] = new_flow.get('command')
143 1
                    stored_flows.remove(stored_flow)
144
                    break
145 1
146 1
            stored_flows.append(new_flow)
147 1
            stored_flows_box[switch.id]['flow_list'] = stored_flows
148 1
149 1
        stored_flows_box['id'] = 'flow_persistence'
150 1
        self.storehouse.save_flow(stored_flows_box)
151
        del stored_flows_box['id']
152
        self.stored_flows = stored_flows_box.copy()
153 1
154
    @rest('v2/flows')
155 1
    @rest('v2/flows/<dpid>')
156 1
    def list(self, dpid=None):
157 1
        """Retrieve all flows from a switch identified by dpid.
158
159 1
        If no dpid is specified, return all flows from all switches.
160
        """
161
        if dpid is None:
162
            switches = self.controller.switches.values()
163
        else:
164
            switches = [self.controller.get_switch_by_dpid(dpid)]
165
166 1
        switch_flows = {}
167 1
168 1
        for switch in switches:
169 1
            flows_dict = [flow.as_dict() for flow in switch.flows]
170 1
            switch_flows[switch.dpid] = {'flows': flows_dict}
171
172
        return jsonify(switch_flows)
173
174 1
    @rest('v2/flows', methods=['POST'])
175
    @rest('v2/flows/<dpid>', methods=['POST'])
176
    def add(self, dpid=None):
177
        """Install new flows in the switch identified by dpid.
178
179
        If no dpid is specified, install flows in all switches.
180
        """
181
        return self._send_flow_mods_from_request(dpid, "add")
182
183
    @rest('v2/delete', methods=['POST'])
184
    @rest('v2/delete/<dpid>', methods=['POST'])
185
    @rest('v2/flows', methods=['DELETE'])
186
    @rest('v2/flows/<dpid>', methods=['DELETE'])
187
    def delete(self, dpid=None):
188
        """Delete existing flows in the switch identified by dpid.
189
190
        If no dpid is specified, delete flows from all switches.
191
        """
192
        return self._send_flow_mods_from_request(dpid, "delete")
193
194
    def _get_all_switches_enabled(self):
195
        """Get a list of all switches enabled."""
196
        switches = self.controller.switches.values()
197
        return [switch for switch in switches if switch.is_enabled()]
198
199
    def _send_flow_mods_from_request(self, dpid, command, flows_dict=None):
200
        """Install FlowsMods from request."""
201
        if flows_dict is None:
202
            flows_dict = request.get_json()
203
            if flows_dict is None:
204
                return jsonify({"response": 'flows dict is none.'}), 404
205
206
        if dpid:
207
            switch = self.controller.get_switch_by_dpid(dpid)
208
            if not switch:
209
                return jsonify({"response": 'dpid not found.'}), 404
210
            elif switch.is_enabled() is False:
211
                return jsonify({"response": 'switch is disabled.'}), 404
212
            else:
213
                self._install_flows(command, flows_dict, [switch])
214
        else:
215
            self._install_flows(command, flows_dict,
216
                                self._get_all_switches_enabled())
217
218
        return jsonify({"response": "FlowMod Messages Sent"})
219
220
    def _install_flows(self, command, flows_dict, switches=[]):
221
        """Execute all procedures to install flows in the switches.
222
223
        Args:
224
            command: Flow command to be installed
225
            flows_dict: Dictionary with flows to be installed in the switches.
226
            switches: A list of switches
227
        """
228
        for switch in switches:
229
            serializer = FlowFactory.get_class(switch)
230
            flows = flows_dict.get('flows', [])
231
            for flow_dict in flows:
232
                flow = serializer.from_dict(flow_dict, switch)
233
                if command == "delete":
234
                    flow_mod = flow.as_of_delete_flow_mod()
235
                elif command == "add":
236
                    flow_mod = flow.as_of_add_flow_mod()
237
                else:
238
                    raise InvalidCommandError
239
                self._send_flow_mod(flow.switch, flow_mod)
240
                self._add_flow_mod_sent(flow_mod.header.xid, flow, command)
241
242
                self._send_napp_event(switch, flow, command)
243
                self._store_changed_flows(command, flow_dict, switch)
244
245
    def _add_flow_mod_sent(self, xid, flow, command):
246
        """Add the flow mod to the list of flow mods sent."""
247
        if len(self._flow_mods_sent) >= self._flow_mods_sent_max_size:
248
            self._flow_mods_sent.popitem(last=False)
249
        self._flow_mods_sent[xid] = (flow, command)
250
251
    def _send_flow_mod(self, switch, flow_mod):
252
        event_name = 'kytos/flow_manager.messages.out.ofpt_flow_mod'
253
254
        content = {'destination': switch.connection,
255
                   'message': flow_mod}
256
257
        event = KytosEvent(name=event_name, content=content)
258
        self.controller.buffers.msg_out.put(event)
259
260
    def _send_napp_event(self, switch, flow, command, **kwargs):
261
        """Send an Event to other apps informing about a FlowMod."""
262
        if command == 'add':
263
            name = 'kytos/flow_manager.flow.added'
264
        elif command == 'delete':
265
            name = 'kytos/flow_manager.flow.removed'
266
        elif command == 'error':
267
            name = 'kytos/flow_manager.flow.error'
268
        else:
269
            raise InvalidCommandError
270
        content = {'datapath': switch,
271
                   'flow': flow}
272
        content.update(kwargs)
273
        event_app = KytosEvent(name, content)
274
        self.controller.buffers.app.put(event_app)
275
276
    @listen_to('.*.of_core.*.ofpt_error')
277
    def handle_errors(self, event):
278
        """Receive OpenFlow error and send a event.
279
280
        The event is sent only if the error is related to a request made
281
        by flow_manager.
282
        """
283
        xid = event.content["message"].header.xid.value
284
        error_type = event.content["message"].error_type
285
        error_code = event.content["message"].code
286
        try:
287
            flow, error_command = self._flow_mods_sent[xid]
288
        except KeyError:
289
            pass
290
        else:
291
            self._send_napp_event(flow.switch, flow, 'error',
292
                                  error_command=error_command,
293
                                  error_type=error_type, error_code=error_code)
294