Passed
Pull Request — master (#90)
by Carlos
02:10
created

build.main.Main._install_flows()   A

Complexity

Conditions 5

Size

Total Lines 24
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 5.0592

Importance

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