Passed
Pull Request — master (#90)
by
unknown
02:11
created

build.main.Main.setup()   A

Complexity

Conditions 1

Size

Total Lines 13
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 6
nop 1
dl 0
loc 13
ccs 6
cts 6
cp 1
crap 1
rs 10
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 StoreHouseClient
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 = StoreHouseClient(self.controller)
30 1
        self.stored_flows = {}
31
32 1
    def execute(self):
33
        """Run once on NApp 'start' or in a loop.
34
35
        The execute method is called by the run method of KytosNApp class.
36
        Users shouldn't call this method directly.
37
        """
38
        self._load_flows()
39
40 1
    def shutdown(self):
41
        """Shutdown routine of the NApp."""
42
        log.debug("flow-manager stopping")
43
44
    # pylint: disable=attribute-defined-outside-init
45 1
    def _load_flows(self):
46
        """Load stored flows."""
47
        try:
48
            data = self.storehouse.get_data()['flow_persistence']
49
            del data['id']
50
            self.stored_flows = data
51
52
        except (KeyError) as error:
53
            log.info(f'Error:{error}')
54
            log.info('Not has persisted flows to load.')
55
            # self.flows_stored = {}
56
            return
57
        log.info('Flow box loaded.')
58
59 1
    def _flows_change(self, command, flows, switches):
60
        """Flows change, store Flows. Persist all flows."""
61
        store_box_updated = self.stored_flows.copy()
62
        for switch in switches:
63
            flow_box = {}
64
            flow_list = []
65
            # match fields to an stored flow
66
            match_storage_fields = {}
67
            match_storage_fields['command'] = command
68
69
            for fields in flows['flows']:
70
                if 'priority' in fields:
71
                    match_storage_fields['priority'] = fields['priority']
72
                if 'cookie' in fields:
73
                    match_storage_fields['cookie'] = fields['cookie']
74
                if 'match' in fields:
75
                    for field, value in fields['match'].items():
76
                        match_storage_fields[field] = value
77
78
            flow_box['match_storage'] = match_storage_fields
79
80
            flow_box['data'] = flows
81
            flow_list.append(flow_box)
82
83
            flag_match_stored_flow = 0
84
            # Switch have stored flow, append new flow to flow_list.
85
            if switch.id in self.stored_flows:
86
                stored_flows = self.stored_flows[switch.id]['flow_list']
87
                # Check if flow already stored
88
                for stored in stored_flows:
89
                    # if already stored, set flag and break
90
                    if flow_box['match_storage'] == stored['match_storage']:
91
                        flag_match_stored_flow = 1
92
                        break
93
94
                # if flow not stored append to flow_list
95
                if flag_match_stored_flow == 0:
96
                    temp_list = store_box_updated[switch.id]['flow_list']
97
                    temp_list.append(flow_list)
98
                    store_box_updated[switch.id]['flow_list'] = temp_list
99
100
            else:
101
                # switch not stored, add to box.
102
                store_box_updated[switch.id] = {"flow_list": flow_list}
103
104
        store_box_updated['id'] = 'flow_persistence'
105
        self.storehouse.save_flow(store_box_updated)
106
        self.flows_stored = store_box_updated.copy()
107
108 1
    @rest('v2/flows')
109 1
    @rest('v2/flows/<dpid>')
110 1
    def list(self, dpid=None):
111
        """Retrieve all flows from a switch identified by dpid.
112
113
        If no dpid is specified, return all flows from all switches.
114
        """
115 1
        if dpid is None:
116 1
            switches = self.controller.switches.values()
117
        else:
118 1
            switches = [self.controller.get_switch_by_dpid(dpid)]
119
120 1
        switch_flows = {}
121
122 1
        for switch in switches:
123 1
            flows_dict = [flow.as_dict() for flow in switch.flows]
124 1
            switch_flows[switch.dpid] = {'flows': flows_dict}
125
126 1
        return jsonify(switch_flows)
127
128 1
    @rest('v2/flows', methods=['POST'])
129 1
    @rest('v2/flows/<dpid>', methods=['POST'])
130 1
    def add(self, dpid=None):
131
        """Install new flows in the switch identified by dpid.
132
133
        If no dpid is specified, install flows in all switches.
134
        """
135 1
        return self._send_flow_mods_from_request(dpid, "add")
136
137 1
    @rest('v2/delete', methods=['POST'])
138 1
    @rest('v2/delete/<dpid>', methods=['POST'])
139 1
    @rest('v2/flows', methods=['DELETE'])
140 1
    @rest('v2/flows/<dpid>', methods=['DELETE'])
141 1
    def delete(self, dpid=None):
142
        """Delete existing flows in the switch identified by dpid.
143
144
        If no dpid is specified, delete flows from all switches.
145
        """
146 1
        return self._send_flow_mods_from_request(dpid, "delete")
147
148 1
    def _get_all_switches_enabled(self):
149
        """Get a list of all switches enabled."""
150 1
        switches = self.controller.switches.values()
151 1
        return [switch for switch in switches if switch.is_enabled()]
152
153 1
    def _send_flow_mods_from_request(self, dpid, command):
154
        """Install FlowsMods from request."""
155 1
        flows_dict = request.get_json()
156
157 1
        if flows_dict is None:
158 1
            return jsonify({"response": 'flows dict is none.'}), 404
159
160 1
        if dpid:
161 1
            switch = self.controller.get_switch_by_dpid(dpid)
162 1
            if not switch:
163 1
                return jsonify({"response": 'dpid not found.'}), 404
164 1
            elif switch.is_enabled() is False:
165 1
                return jsonify({"response": 'switch is disabled.'}), 404
166
            else:
167 1
                self._install_flows(command, flows_dict, [switch])
168
        else:
169 1
            self._install_flows(command, flows_dict,
170
                                self._get_all_switches_enabled())
171
172 1
        return jsonify({"response": "FlowMod Messages Sent"})
173
174 1
    def _install_flows(self, command, flows_dict, switches=[]):
175
        """Execute all procedures to install flows in the switches.
176
177
        Args:
178
            command: Flow command to be installed
179
            flows_dict: Dictionary with flows to be installed in the switches.
180
            switches: A list of switches
181
        """
182 1
        for switch in switches:
183 1
            serializer = FlowFactory.get_class(switch)
184 1
            flows = flows_dict.get('flows', [])
185 1
            for flow_dict in flows:
186 1
                flow = serializer.from_dict(flow_dict, switch)
187 1
                if command == "delete":
188
                    flow_mod = flow.as_of_delete_flow_mod()
189 1
                elif command == "add":
190 1
                    flow_mod = flow.as_of_add_flow_mod()
191
                else:
192
                    raise InvalidCommandError
193 1
                self._send_flow_mod(flow.switch, flow_mod)
194 1
                self._add_flow_mod_sent(flow_mod.header.xid, flow)
195
196 1
                self._send_napp_event(switch, flow, command)
197 1
        self._flows_change(command, flows_dict, switches)
198
199 1
    def _add_flow_mod_sent(self, xid, flow):
200
        """Add the flow mod to the list of flow mods sent."""
201 1
        if len(self._flow_mods_sent) >= self._flow_mods_sent_max_size:
202
            self._flow_mods_sent.popitem(last=False)
203 1
        self._flow_mods_sent[xid] = flow
204
205 1
    def _send_flow_mod(self, switch, flow_mod):
206 1
        event_name = 'kytos/flow_manager.messages.out.ofpt_flow_mod'
207
208 1
        content = {'destination': switch.connection,
209
                   'message': flow_mod}
210
211 1
        event = KytosEvent(name=event_name, content=content)
212 1
        self.controller.buffers.msg_out.put(event)
213
214 1
    def _send_napp_event(self, switch, flow, command, **kwargs):
215
        """Send an Event to other apps informing about a FlowMod."""
216 1
        if command == 'add':
217 1
            name = 'kytos/flow_manager.flow.added'
218 1
        elif command == 'delete':
219 1
            name = 'kytos/flow_manager.flow.removed'
220 1
        elif command == 'error':
221 1
            name = 'kytos/flow_manager.flow.error'
222
        else:
223
            raise InvalidCommandError
224 1
        content = {'datapath': switch,
225
                   'flow': flow}
226 1
        content.update(kwargs)
227 1
        event_app = KytosEvent(name, content)
228 1
        self.controller.buffers.app.put(event_app)
229
230 1
    @listen_to('.*.of_core.*.ofpt_error')
231
    def handle_errors(self, event):
232
        """Receive OpenFlow error and send a event.
233
234
        The event is sent only if the error is related to a request made
235
        by flow_manager.
236
        """
237 1
        xid = event.content["message"].header.xid.value
238 1
        error_type = event.content["message"].error_type
239 1
        error_code = event.content["message"].code
240 1
        try:
241 1
            flow = self._flow_mods_sent[xid]
242
        except KeyError:
243
            pass
244
        else:
245 1
            self._send_napp_event(flow.switch, flow, 'error',
246
                                  error_type=error_type, error_code=error_code)
247