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
|
1 |
|
from pyof.v0x01.asynchronous.error_msg import BadActionCode |
6
|
1 |
|
from pyof.v0x01.common.phy_port import PortConfig |
7
|
|
|
|
8
|
1 |
|
from kytos.core import KytosEvent, KytosNApp, log, rest |
9
|
1 |
|
from kytos.core.helpers import listen_to |
10
|
1 |
|
from napps.kytos.flow_manager.storehouse import StoreHouse |
11
|
1 |
|
from napps.kytos.of_core.flow import FlowFactory |
12
|
|
|
|
13
|
1 |
|
from .exceptions import InvalidCommandError |
14
|
1 |
|
from .settings import CONSISTENCY_INTERVAL, FLOWS_DICT_MAX_SIZE |
15
|
|
|
|
16
|
|
|
|
17
|
1 |
|
class Main(KytosNApp): |
18
|
|
|
"""Main class to be used by Kytos controller.""" |
19
|
|
|
|
20
|
1 |
|
def setup(self): |
21
|
|
|
"""Replace the 'init' method for the KytosApp subclass. |
22
|
|
|
|
23
|
|
|
The setup method is automatically called by the run method. |
24
|
|
|
Users shouldn't call this method directly. |
25
|
|
|
""" |
26
|
1 |
|
log.debug("flow-manager starting") |
27
|
1 |
|
self._flow_mods_sent = OrderedDict() |
28
|
1 |
|
self._flow_mods_sent_max_size = FLOWS_DICT_MAX_SIZE |
29
|
|
|
|
30
|
|
|
# Storehouse client to save and restore flow data: |
31
|
1 |
|
self.storehouse = StoreHouse(self.controller) |
32
|
|
|
|
33
|
|
|
# Format of stored flow data: |
34
|
|
|
# {'flow_persistence': {'dpid_str': {'flow_list': [ |
35
|
|
|
# {'command': '<add|delete>', |
36
|
|
|
# 'flow': {flow_dict}}]}}} |
37
|
1 |
|
self.stored_flows = {} |
38
|
1 |
|
self.resent_flows = set() |
39
|
1 |
|
if CONSISTENCY_INTERVAL > 0: |
40
|
1 |
|
self.execute_as_loop(CONSISTENCY_INTERVAL) |
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
|
|
|
if CONSISTENCY_INTERVAL > 0: |
51
|
|
|
self.consistency_check() |
52
|
|
|
|
53
|
1 |
|
def shutdown(self): |
54
|
|
|
"""Shutdown routine of the NApp.""" |
55
|
|
|
log.debug("flow-manager stopping") |
56
|
|
|
|
57
|
1 |
|
@listen_to('kytos/of_core.handshake.completed') |
58
|
|
|
def resend_stored_flows(self, event): |
59
|
|
|
"""Resend stored Flows.""" |
60
|
1 |
|
switch = event.content['switch'] |
61
|
1 |
|
dpid = str(switch.dpid) |
62
|
|
|
# This can be a problem because this code is running a thread |
63
|
1 |
|
if dpid in self.resent_flows: |
64
|
|
|
log.debug(f'Flow already resent to the switch {dpid}') |
65
|
|
|
return |
66
|
1 |
|
if dpid in self.stored_flows: |
67
|
1 |
|
flow_list = self.stored_flows[dpid]['flow_list'] |
68
|
1 |
|
for flow in flow_list: |
69
|
1 |
|
command = flow['command'] |
70
|
1 |
|
flows_dict = {"flows": [flow['flow']]} |
71
|
1 |
|
self._install_flows(command, flows_dict, [switch]) |
72
|
1 |
|
self.resent_flows.add(dpid) |
73
|
1 |
|
log.info(f'Flows resent to Switch {dpid}') |
74
|
|
|
|
75
|
1 |
|
def consistency_check(self): |
76
|
|
|
"""Check the consistency of flows in each switch.""" |
77
|
|
|
switches = self.controller.switches.values() |
78
|
|
|
|
79
|
|
|
for switch in switches: |
80
|
|
|
# Check if a dpid is a key in 'stored_flows' dictionary |
81
|
|
|
if switch.is_enabled(): |
82
|
|
|
self.check_storehouse_consistency(switch) |
83
|
|
|
|
84
|
|
|
if switch.dpid in self.stored_flows: |
85
|
|
|
self.check_switch_consistency(switch) |
86
|
|
|
|
87
|
1 |
|
def check_switch_consistency(self, switch): |
88
|
|
|
"""Check consistency of installed flows for a specific switch.""" |
89
|
1 |
|
dpid = switch.dpid |
90
|
|
|
|
91
|
|
|
# Flows stored in storehouse |
92
|
1 |
|
stored_flows = self.stored_flows[dpid]['flow_list'] |
93
|
|
|
|
94
|
1 |
|
serializer = FlowFactory.get_class(switch) |
95
|
|
|
|
96
|
1 |
|
for stored_flow in stored_flows: |
97
|
1 |
|
command = stored_flow['command'] |
98
|
1 |
|
stored_flow_obj = serializer.from_dict(stored_flow['flow'], switch) |
99
|
|
|
|
100
|
1 |
|
flow = {'flows': [stored_flow['flow']]} |
101
|
|
|
|
102
|
1 |
|
if stored_flow_obj not in switch.flows: |
103
|
1 |
|
if command == 'add': |
104
|
1 |
|
log.info('A consistency problem was detected in ' |
105
|
|
|
f'switch {dpid}.') |
106
|
1 |
|
self._install_flows(command, flow, [switch]) |
107
|
1 |
|
log.info(f'Flow forwarded to switch {dpid} to be ' |
108
|
|
|
'installed.') |
109
|
1 |
|
elif command == 'delete': |
110
|
1 |
|
log.info('A consistency problem was detected in ' |
111
|
|
|
f'switch {dpid}.') |
112
|
1 |
|
command = 'delete_strict' |
113
|
1 |
|
self._install_flows(command, flow, [switch]) |
114
|
1 |
|
log.info(f'Flow forwarded to switch {dpid} to be deleted.') |
115
|
|
|
|
116
|
1 |
|
def check_storehouse_consistency(self, switch): |
117
|
|
|
"""Check consistency of installed flows for a specific switch.""" |
118
|
1 |
|
dpid = switch.dpid |
119
|
|
|
|
120
|
1 |
|
for installed_flow in switch.flows: |
121
|
1 |
|
if dpid not in self.stored_flows: |
122
|
|
|
log.info('A consistency problem was detected in ' |
123
|
|
|
f'switch {dpid}.') |
124
|
|
|
flow = {'flows': [installed_flow.as_dict()]} |
125
|
|
|
command = 'delete_strict' |
126
|
|
|
self._install_flows(command, flow, [switch]) |
127
|
|
|
log.info(f'Flow forwarded to switch {dpid} to be deleted.') |
128
|
|
|
else: |
129
|
1 |
|
serializer = FlowFactory.get_class(switch) |
130
|
1 |
|
stored_flows = self.stored_flows[dpid]['flow_list'] |
131
|
1 |
|
stored_flows_list = [serializer.from_dict(stored_flow['flow'], |
132
|
|
|
switch) |
133
|
|
|
for stored_flow in stored_flows] |
134
|
|
|
|
135
|
1 |
|
if installed_flow not in stored_flows_list: |
136
|
1 |
|
log.info('A consistency problem was detected in ' |
137
|
|
|
f'switch {dpid}.') |
138
|
1 |
|
flow = {'flows': [installed_flow.as_dict()]} |
139
|
1 |
|
command = 'delete_strict' |
140
|
1 |
|
self._install_flows(command, flow, [switch]) |
141
|
1 |
|
log.info(f'Flow forwarded to switch {dpid} to be deleted.') |
142
|
|
|
|
143
|
|
|
# pylint: disable=attribute-defined-outside-init |
144
|
1 |
|
def _load_flows(self): |
145
|
|
|
"""Load stored flows.""" |
146
|
1 |
|
try: |
147
|
1 |
|
data = self.storehouse.get_data()['flow_persistence'] |
148
|
1 |
|
if 'id' in data: |
149
|
|
|
del data['id'] |
150
|
1 |
|
self.stored_flows = data |
151
|
|
|
except (KeyError, FileNotFoundError) as error: |
152
|
|
|
log.debug(f'There are no flows to load: {error}') |
153
|
|
|
else: |
154
|
1 |
|
log.info('Flows loaded.') |
155
|
|
|
|
156
|
1 |
|
def _store_changed_flows(self, command, flow, switch): |
157
|
|
|
"""Store changed flows. |
158
|
|
|
|
159
|
|
|
Args: |
160
|
|
|
command: Flow command to be installed |
161
|
|
|
flow: Flows to be stored |
162
|
|
|
switch: Switch target |
163
|
|
|
""" |
164
|
1 |
|
stored_flows_box = self.stored_flows.copy() |
165
|
|
|
# if the flow has a destination dpid it can be stored. |
166
|
1 |
|
if not switch: |
167
|
|
|
log.info('The Flow cannot be stored, the destination switch ' |
168
|
|
|
f'have not been specified: {switch}') |
169
|
|
|
return |
170
|
1 |
|
installed_flow = {} |
171
|
1 |
|
flow_list = [] |
172
|
1 |
|
installed_flow['command'] = command |
173
|
1 |
|
installed_flow['flow'] = flow |
174
|
|
|
|
175
|
1 |
|
serializer = FlowFactory.get_class(switch) |
176
|
1 |
|
installed_flow_obj = serializer.from_dict(flow, switch) |
177
|
|
|
|
178
|
1 |
|
if switch.id not in stored_flows_box: |
179
|
|
|
# Switch not stored, add to box. |
180
|
1 |
|
flow_list.append(installed_flow) |
181
|
1 |
|
stored_flows_box[switch.id] = {'flow_list': flow_list} |
182
|
|
|
else: |
183
|
1 |
|
stored_flows = stored_flows_box[switch.id].get('flow_list', []) |
184
|
|
|
# Check if flow already stored |
185
|
1 |
|
for stored_flow in stored_flows: |
186
|
1 |
|
stored_flow_obj = serializer.from_dict(stored_flow['flow'], |
187
|
|
|
switch) |
188
|
1 |
|
if installed_flow_obj == stored_flow_obj: |
189
|
1 |
|
if stored_flow['command'] == installed_flow['command']: |
190
|
|
|
log.debug('Data already stored.') |
191
|
|
|
return |
192
|
|
|
# Flow with inconsistency in "command" fields : Remove the |
193
|
|
|
# old instruction. This happens when there is a stored |
194
|
|
|
# instruction to install the flow, but the new instruction |
195
|
|
|
# is to remove it. In this case, the old instruction is |
196
|
|
|
# removed and the new one is stored. |
197
|
1 |
|
stored_flow['command'] = installed_flow.get('command') |
198
|
1 |
|
stored_flows.remove(stored_flow) |
199
|
1 |
|
break |
200
|
|
|
|
201
|
1 |
|
stored_flows.append(installed_flow) |
202
|
1 |
|
stored_flows_box[switch.id]['flow_list'] = stored_flows |
203
|
|
|
|
204
|
1 |
|
stored_flows_box['id'] = 'flow_persistence' |
205
|
1 |
|
self.storehouse.save_flow(stored_flows_box) |
206
|
1 |
|
del stored_flows_box['id'] |
207
|
1 |
|
self.stored_flows = stored_flows_box.copy() |
208
|
|
|
|
209
|
1 |
|
@rest('v2/flows') |
210
|
1 |
|
@rest('v2/flows/<dpid>') |
211
|
1 |
|
def list(self, dpid=None): |
212
|
|
|
"""Retrieve all flows from a switch identified by dpid. |
213
|
|
|
|
214
|
|
|
If no dpid is specified, return all flows from all switches. |
215
|
|
|
""" |
216
|
1 |
|
if dpid is None: |
217
|
1 |
|
switches = self.controller.switches.values() |
218
|
|
|
else: |
219
|
1 |
|
switches = [self.controller.get_switch_by_dpid(dpid)] |
220
|
|
|
|
221
|
1 |
|
switch_flows = {} |
222
|
|
|
|
223
|
1 |
|
for switch in switches: |
224
|
1 |
|
flows_dict = [flow.as_dict() for flow in switch.flows] |
225
|
1 |
|
switch_flows[switch.dpid] = {'flows': flows_dict} |
226
|
|
|
|
227
|
1 |
|
return jsonify(switch_flows) |
228
|
|
|
|
229
|
1 |
|
@rest('v2/flows', methods=['POST']) |
230
|
1 |
|
@rest('v2/flows/<dpid>', methods=['POST']) |
231
|
1 |
|
def add(self, dpid=None): |
232
|
|
|
"""Install new flows in the switch identified by dpid. |
233
|
|
|
|
234
|
|
|
If no dpid is specified, install flows in all switches. |
235
|
|
|
""" |
236
|
1 |
|
return self._send_flow_mods_from_request(dpid, "add") |
237
|
|
|
|
238
|
1 |
|
@rest('v2/delete', methods=['POST']) |
239
|
1 |
|
@rest('v2/delete/<dpid>', methods=['POST']) |
240
|
1 |
|
@rest('v2/flows', methods=['DELETE']) |
241
|
1 |
|
@rest('v2/flows/<dpid>', methods=['DELETE']) |
242
|
1 |
|
def delete(self, dpid=None): |
243
|
|
|
"""Delete existing flows in the switch identified by dpid. |
244
|
|
|
|
245
|
|
|
If no dpid is specified, delete flows from all switches. |
246
|
|
|
""" |
247
|
1 |
|
return self._send_flow_mods_from_request(dpid, "delete") |
248
|
|
|
|
249
|
1 |
|
def _get_all_switches_enabled(self): |
250
|
|
|
"""Get a list of all switches enabled.""" |
251
|
1 |
|
switches = self.controller.switches.values() |
252
|
1 |
|
return [switch for switch in switches if switch.is_enabled()] |
253
|
|
|
|
254
|
1 |
|
def _send_flow_mods_from_request(self, dpid, command, flows_dict=None): |
255
|
|
|
"""Install FlowsMods from request.""" |
256
|
1 |
|
if flows_dict is None: |
257
|
1 |
|
flows_dict = request.get_json() |
258
|
1 |
|
if flows_dict is None: |
259
|
1 |
|
return jsonify({"response": 'flows dict is none.'}), 404 |
260
|
|
|
|
261
|
1 |
|
if dpid: |
262
|
1 |
|
switch = self.controller.get_switch_by_dpid(dpid) |
263
|
1 |
|
if not switch: |
264
|
1 |
|
return jsonify({"response": 'dpid not found.'}), 404 |
265
|
1 |
|
elif switch.is_enabled() is False: |
266
|
1 |
|
if command == "delete": |
267
|
1 |
|
self._install_flows(command, flows_dict, [switch]) |
268
|
|
|
else: |
269
|
1 |
|
return jsonify({"response": 'switch is disabled.'}), 404 |
270
|
|
|
else: |
271
|
1 |
|
self._install_flows(command, flows_dict, [switch]) |
272
|
|
|
else: |
273
|
1 |
|
self._install_flows(command, flows_dict, |
274
|
|
|
self._get_all_switches_enabled()) |
275
|
|
|
|
276
|
1 |
|
return jsonify({"response": "FlowMod Messages Sent"}) |
277
|
|
|
|
278
|
1 |
|
def _install_flows(self, command, flows_dict, switches=[]): |
279
|
|
|
"""Execute all procedures to install flows in the switches. |
280
|
|
|
|
281
|
|
|
Args: |
282
|
|
|
command: Flow command to be installed |
283
|
|
|
flows_dict: Dictionary with flows to be installed in the switches. |
284
|
|
|
switches: A list of switches |
285
|
|
|
""" |
286
|
1 |
|
for switch in switches: |
287
|
1 |
|
serializer = FlowFactory.get_class(switch) |
288
|
1 |
|
flows = flows_dict.get('flows', []) |
289
|
1 |
|
for flow_dict in flows: |
290
|
1 |
|
flow = serializer.from_dict(flow_dict, switch) |
291
|
1 |
|
if command == "delete": |
292
|
|
|
flow_mod = flow.as_of_delete_flow_mod() |
293
|
1 |
|
elif command == "delete_strict": |
294
|
1 |
|
flow_mod = flow.as_of_strict_delete_flow_mod() |
295
|
1 |
|
elif command == "add": |
296
|
1 |
|
flow_mod = flow.as_of_add_flow_mod() |
297
|
|
|
else: |
298
|
|
|
raise InvalidCommandError |
299
|
1 |
|
self._send_flow_mod(flow.switch, flow_mod) |
300
|
1 |
|
self._add_flow_mod_sent(flow_mod.header.xid, flow, command) |
301
|
|
|
|
302
|
1 |
|
self._send_napp_event(switch, flow, command) |
303
|
1 |
|
self._store_changed_flows(command, flow_dict, switch) |
304
|
|
|
|
305
|
1 |
|
def _add_flow_mod_sent(self, xid, flow, command): |
306
|
|
|
"""Add the flow mod to the list of flow mods sent.""" |
307
|
1 |
|
if len(self._flow_mods_sent) >= self._flow_mods_sent_max_size: |
308
|
|
|
self._flow_mods_sent.popitem(last=False) |
309
|
1 |
|
self._flow_mods_sent[xid] = (flow, command) |
310
|
|
|
|
311
|
1 |
|
def _send_flow_mod(self, switch, flow_mod): |
312
|
1 |
|
event_name = 'kytos/flow_manager.messages.out.ofpt_flow_mod' |
313
|
|
|
|
314
|
1 |
|
content = {'destination': switch.connection, |
315
|
|
|
'message': flow_mod} |
316
|
|
|
|
317
|
1 |
|
event = KytosEvent(name=event_name, content=content) |
318
|
1 |
|
self.controller.buffers.msg_out.put(event) |
319
|
|
|
|
320
|
1 |
|
def _send_napp_event(self, switch, flow, command, **kwargs): |
321
|
|
|
"""Send an Event to other apps informing about a FlowMod.""" |
322
|
1 |
|
if command == 'add': |
323
|
1 |
|
name = 'kytos/flow_manager.flow.added' |
324
|
1 |
|
elif command in ('delete', 'delete_strict'): |
325
|
1 |
|
name = 'kytos/flow_manager.flow.removed' |
326
|
1 |
|
elif command == 'error': |
327
|
1 |
|
name = 'kytos/flow_manager.flow.error' |
328
|
|
|
else: |
329
|
|
|
raise InvalidCommandError |
330
|
1 |
|
content = {'datapath': switch, |
331
|
|
|
'flow': flow} |
332
|
1 |
|
content.update(kwargs) |
333
|
1 |
|
event_app = KytosEvent(name, content) |
334
|
1 |
|
self.controller.buffers.app.put(event_app) |
335
|
|
|
|
336
|
1 |
|
@listen_to('.*.of_core.*.ofpt_error') |
337
|
|
|
def handle_errors(self, event): |
338
|
|
|
"""Receive OpenFlow error and send a event. |
339
|
|
|
|
340
|
|
|
The event is sent only if the error is related to a request made |
341
|
|
|
by flow_manager. |
342
|
|
|
""" |
343
|
1 |
|
message = event.content["message"] |
344
|
|
|
|
345
|
1 |
|
connection = event.source |
346
|
1 |
|
switch = connection.switch |
347
|
|
|
|
348
|
1 |
|
xid = message.header.xid.value |
349
|
1 |
|
error_type = message.error_type |
350
|
1 |
|
error_code = message.code |
351
|
1 |
|
error_data = message.data.pack() |
352
|
|
|
|
353
|
|
|
# Get the packet responsible for the error |
354
|
1 |
|
error_packet = connection.protocol.unpack(error_data) |
355
|
|
|
|
356
|
1 |
|
if message.code == BadActionCode.OFPBAC_BAD_OUT_PORT: |
357
|
|
|
actions = [] |
358
|
|
|
if hasattr(error_packet, 'actions'): |
359
|
|
|
# Get actions from the flow mod (OF 1.0) |
360
|
|
|
actions = error_packet.actions |
361
|
|
|
else: |
362
|
|
|
# Get actions from the list of flow mod instructions (OF 1.3) |
363
|
|
|
for instruction in error_packet.instructions: |
364
|
|
|
actions.extend(instruction.actions) |
365
|
|
|
|
366
|
|
|
for action in actions: |
367
|
|
|
iface = switch.get_interface_by_port_no(action.port) |
368
|
|
|
|
369
|
|
|
# Set interface to drop packets forwarded to it |
370
|
|
|
if iface: |
371
|
|
|
iface.config = PortConfig.OFPPC_NO_FWD |
372
|
|
|
|
373
|
1 |
|
try: |
374
|
1 |
|
flow, error_command = self._flow_mods_sent[xid] |
375
|
|
|
except KeyError: |
376
|
|
|
pass |
377
|
|
|
else: |
378
|
1 |
|
self._send_napp_event(flow.switch, flow, 'error', |
379
|
|
|
error_command=error_command, |
380
|
|
|
error_type=error_type, error_code=error_code) |
381
|
|
|
|