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

build.main.Main._generate_match_fields()   B

Complexity

Conditions 6

Size

Total Lines 13
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 6

Importance

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