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

build.main.Main._send_flow_mod()   A

Complexity

Conditions 1

Size

Total Lines 8
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

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