Passed
Pull Request — master (#90)
by Carlos
07:54 queued 05:31
created

build.main.Main.resend_stored_flows()   B

Complexity

Conditions 5

Size

Total Lines 22
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 5.4558

Importance

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