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

build.main.Main._is_flows_equal()   A

Complexity

Conditions 2

Size

Total Lines 7
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2.0185

Importance

Changes 0
Metric Value
cc 2
eloc 6
nop 3
dl 0
loc 7
rs 10
c 0
b 0
f 0
ccs 5
cts 6
cp 0.8333
crap 2.0185
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
        #             {"command":<add|delete>}
33
        #             "flow":{flow_dict},
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
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['command']
67 1
                flows_dict = {"flows": [flow['flow']]}
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
72
    # pylint: disable=attribute-defined-outside-init
73 1
    def _load_flows(self):
74
        """Load stored flows."""
75 1
        try:
76 1
            data = self.storehouse.get_data()['flow_persistence']
77 1
            if 'id' in data:
78
                del data['id']
79 1
            self.stored_flows = data
80
81
        except KeyError as error:
82
            log.debug(f'There are no flows to load: {error}')
83
        else:
84 1
            log.info('Flows loaded.')
85
86 1
    @staticmethod
87
    def _generate_match_fields(flows):
88
        """Generate flow match fields."""
89 1
        match_fields = {}
90 1
        flow = flows.get('flow')
91 1
        print(flow)
92 1
        for field in flow:
93 1
            if 'priority' in field:
94 1
                match_fields['priority'] = flow['priority']
95 1
            if 'cookie' in field:
96 1
                match_fields['cookie'] = flow['cookie']
97 1
            if 'match' in field:
98 1
                for m_field, value in flow['match'].items():
99 1
                    match_fields[m_field] = value
100 1
        return match_fields
101
102 1
    def _is_flows_equal(self, flow_1, flow_2):
103
        """Check if two flows are equal."""
104 1
        flow_1_match_fields = self._generate_match_fields(flow_1)
105 1
        flow_2_match_fields = self._generate_match_fields(flow_2)
106 1
        if flow_1_match_fields == flow_2_match_fields:
107
            return True
108 1
        return False
109
110 1
    def _store_changed_flows(self, command, flow, switch):
111
        """Store changed flows.
112
113
        Args:
114
            command: Flow command to be installed
115
            flow: Flows to be stored
116
            switch: Switch target
117
        """
118 1
        stored_flows_box = self.stored_flows.copy()
119
        # if the flow has a destination dpid it can be stored.
120 1
        if not switch:
121
            log.info('The Flow cannot be stored, the destination switch '
122
                     f'have not been specified: {switch}')
123
            return
124
125 1
        new_flow = {}
126 1
        flow_list = []
127 1
        new_flow['command'] = command
128 1
        new_flow['flow'] = flow
129
130 1
        if switch.id not in stored_flows_box:
131
            # Switch not stored, add to box.
132 1
            flow_list.append(new_flow)
133 1
            stored_flows_box[switch.id] = {"flow_list": flow_list}
134
        else:
135 1
            stored_flows = stored_flows_box[switch.id].get('flow_list', [])
136
            # Check if flow already stored
137 1
            for stored_flow in stored_flows:
138 1
                if self._is_flows_equal(new_flow, stored_flow):
139
                    if stored_flow['command'] == new_flow['command']:
140
                        log.debug('Data already stored.')
141
                        return
142
                    # Command conflict. Remove the old flow.
143
                    # Stored instruction to install a flow but, the new is to
144
                    # remove.
145
                    stored_flow['command'] = new_flow.get('command')
146
                    stored_flows.remove(stored_flow)
147
                    break
148
149 1
            stored_flows.append(new_flow)
150 1
            stored_flows_box[switch.id]['flow_list'] = stored_flows
151
152 1
        stored_flows_box['id'] = 'flow_persistence'
153 1
        self.storehouse.save_flow(stored_flows_box)
154 1
        del stored_flows_box['id']
155 1
        self.stored_flows = stored_flows_box.copy()
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, command)
244
245 1
                self._send_napp_event(switch, flow, command)
246 1
                self._store_changed_flows(command, flow_dict, switch)
247
248 1
    def _add_flow_mod_sent(self, xid, flow, command):
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, command)
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, error_command = self._flow_mods_sent[xid]
291
        except KeyError:
292
            pass
293
        else:
294 1
            self._send_napp_event(flow.switch, flow, 'error',
295
                                  error_command=error_command,
296
                                  error_type=error_type, error_code=error_code)
297