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

build.main.Main._get_all_switches_enabled()   A

Complexity

Conditions 1

Size

Total Lines 4
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 3
dl 0
loc 4
rs 10
c 0
b 0
f 0
ccs 3
cts 3
cp 1
cc 1
nop 1
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 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
            flow_box['data'] = flows
80
81
            if switch.id not in store_box_updated:
82
                # switch not stored, add to box.
83
                flow_list.append(flow_box)
84
                store_box_updated[switch.id] = {"flow_list": flow_list}
85
                continue
86
87
            # Switch have stored flow, append new flow to flow_list.
88
            stored_flows = store_box_updated[switch.id]['flow_list']
89
            # Check if flow already stored
90
            for flow in stored_flows:
91
                # if already stored, set flag and break
92
                if flow_box['match_storage'] == flow['match_storage']:
93
                    log.info('Data already stored')
94
                    return 0
95
96
            # if flow not stored append to flow_list
97
            stored_flows.append(flow_box)
98
            store_box_updated[switch.id]['flow_list'] = stored_flows
99
100
        store_box_updated['id'] = 'flow_persistence'
101
        self.storehouse.save_flow(store_box_updated)
102
        # print(store_box_updated)
103
        del store_box_updated['id']
104
        self.stored_flows = store_box_updated.copy()
105
        return None
106
107 1
    @rest('v2/flows')
108 1
    @rest('v2/flows/<dpid>')
109 1
    def list(self, dpid=None):
110
        """Retrieve all flows from a switch identified by dpid.
111
112
        If no dpid is specified, return all flows from all switches.
113
        """
114 1
        if dpid is None:
115 1
            switches = self.controller.switches.values()
116
        else:
117 1
            switches = [self.controller.get_switch_by_dpid(dpid)]
118
119 1
        switch_flows = {}
120
121 1
        for switch in switches:
122 1
            flows_dict = [flow.as_dict() for flow in switch.flows]
123 1
            switch_flows[switch.dpid] = {'flows': flows_dict}
124
125 1
        return jsonify(switch_flows)
126
127 1
    @rest('v2/flows', methods=['POST'])
128 1
    @rest('v2/flows/<dpid>', methods=['POST'])
129 1
    def add(self, dpid=None):
130
        """Install new flows in the switch identified by dpid.
131
132
        If no dpid is specified, install flows in all switches.
133
        """
134 1
        return self._send_flow_mods_from_request(dpid, "add")
135
136 1
    @rest('v2/delete', methods=['POST'])
137 1
    @rest('v2/delete/<dpid>', methods=['POST'])
138 1
    @rest('v2/flows', methods=['DELETE'])
139 1
    @rest('v2/flows/<dpid>', methods=['DELETE'])
140 1
    def delete(self, dpid=None):
141
        """Delete existing flows in the switch identified by dpid.
142
143
        If no dpid is specified, delete flows from all switches.
144
        """
145 1
        return self._send_flow_mods_from_request(dpid, "delete")
146
147 1
    def _get_all_switches_enabled(self):
148
        """Get a list of all switches enabled."""
149 1
        switches = self.controller.switches.values()
150 1
        return [switch for switch in switches if switch.is_enabled()]
151
152 1
    def _send_flow_mods_from_request(self, dpid, command):
153
        """Install FlowsMods from request."""
154 1
        flows_dict = request.get_json()
155
156 1
        if flows_dict is None:
157 1
            return jsonify({"response": 'flows dict is none.'}), 404
158
159 1
        if dpid:
160 1
            switch = self.controller.get_switch_by_dpid(dpid)
161 1
            if not switch:
162 1
                return jsonify({"response": 'dpid not found.'}), 404
163 1
            elif switch.is_enabled() is False:
164 1
                return jsonify({"response": 'switch is disabled.'}), 404
165
            else:
166 1
                self._install_flows(command, flows_dict, [switch])
167
        else:
168 1
            self._install_flows(command, flows_dict,
169
                                self._get_all_switches_enabled())
170
171 1
        return jsonify({"response": "FlowMod Messages Sent"})
172
173 1
    def _install_flows(self, command, flows_dict, switches=[]):
174
        """Execute all procedures to install flows in the switches.
175
176
        Args:
177
            command: Flow command to be installed
178
            flows_dict: Dictionary with flows to be installed in the switches.
179
            switches: A list of switches
180
        """
181 1
        for switch in switches:
182 1
            serializer = FlowFactory.get_class(switch)
183 1
            flows = flows_dict.get('flows', [])
184 1
            for flow_dict in flows:
185 1
                flow = serializer.from_dict(flow_dict, switch)
186 1
                if command == "delete":
187
                    flow_mod = flow.as_of_delete_flow_mod()
188 1
                elif command == "add":
189 1
                    flow_mod = flow.as_of_add_flow_mod()
190
                else:
191
                    raise InvalidCommandError
192 1
                self._send_flow_mod(flow.switch, flow_mod)
193 1
                self._add_flow_mod_sent(flow_mod.header.xid, flow)
194
195 1
                self._send_napp_event(switch, flow, command)
196 1
        self._flows_change(command, flows_dict, switches)
197
198 1
    def _add_flow_mod_sent(self, xid, flow):
199
        """Add the flow mod to the list of flow mods sent."""
200 1
        if len(self._flow_mods_sent) >= self._flow_mods_sent_max_size:
201
            self._flow_mods_sent.popitem(last=False)
202 1
        self._flow_mods_sent[xid] = flow
203
204 1
    def _send_flow_mod(self, switch, flow_mod):
205 1
        event_name = 'kytos/flow_manager.messages.out.ofpt_flow_mod'
206
207 1
        content = {'destination': switch.connection,
208
                   'message': flow_mod}
209
210 1
        event = KytosEvent(name=event_name, content=content)
211 1
        self.controller.buffers.msg_out.put(event)
212
213 1
    def _send_napp_event(self, switch, flow, command, **kwargs):
214
        """Send an Event to other apps informing about a FlowMod."""
215 1
        if command == 'add':
216 1
            name = 'kytos/flow_manager.flow.added'
217 1
        elif command == 'delete':
218 1
            name = 'kytos/flow_manager.flow.removed'
219 1
        elif command == 'error':
220 1
            name = 'kytos/flow_manager.flow.error'
221
        else:
222
            raise InvalidCommandError
223 1
        content = {'datapath': switch,
224
                   'flow': flow}
225 1
        content.update(kwargs)
226 1
        event_app = KytosEvent(name, content)
227 1
        self.controller.buffers.app.put(event_app)
228
229 1
    @listen_to('.*.of_core.*.ofpt_error')
230
    def handle_errors(self, event):
231
        """Receive OpenFlow error and send a event.
232
233
        The event is sent only if the error is related to a request made
234
        by flow_manager.
235
        """
236 1
        xid = event.content["message"].header.xid.value
237 1
        error_type = event.content["message"].error_type
238 1
        error_code = event.content["message"].code
239 1
        try:
240 1
            flow = self._flow_mods_sent[xid]
241
        except KeyError:
242
            pass
243
        else:
244 1
            self._send_napp_event(flow.switch, flow, 'error',
245
                                  error_type=error_type, error_code=error_code)
246