-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshared_controller.py
319 lines (270 loc) · 12.3 KB
/
shared_controller.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
import os
import logging
import base64
import json
import ast
import urllib2
from webob import Response
from ryu.base import app_manager
from ryu.controller import ofp_event
from ryu.controller.handler import CONFIG_DISPATCHER
from ryu.controller.handler import set_ev_cls
from ryu.ofproto import ofproto_v1_3
from ryu.lib import ofctl_v1_3
from ryu.app.wsgi import ControllerBase, WSGIApplication
LOG = logging.getLogger('ryu.app.shared_controller')
# supported ofctl versions in this restful app
supported_ofctl = {
ofproto_v1_3.OFP_VERSION: ofctl_v1_3
}
#Ryu IP and port
ryu_IP = 'localhost'
ryu_port = 8080
#load config file
config = os.getenv('SharedControllerAppConfig')
with open(config) as tenants_json:
tenants_data = json.load(tenants_json)
class Tenant(object):
def __init__(self,name,**kwargs):
self.name = name
self.tables = []
for k,v in kwargs.iteritems():
setattr(self,k,v)
for i in xrange(self.nof_table):
self.tables.append(i + self.offset_table)
#User userid and password to generate authtoken
self.authtoken = 'Basic ' + base64.b64encode(self.authkey)
def xlat_switch_to_tenant(self, flow):
flow['table_id'] -= self.offset_table
for action in flow['actions']:
if action.find('GOTO_TABLE:') == -1:
continue
index = flow['actions'].index(action)
action = action.replace('GOTO_TABLE:','')
action = int(action)
action -= self.offset_table
action = str(action)
flow['actions'][index] = 'GOTO_TABLE:'+ action
return flow
def xlat_tenant_to_switch(self,flow):
#in the api to modify flow: if table_id is missing ~ table_id = 0 (default value)
if 'table_id' not in flow:
flow['table_id'] = self.tables[0]
else:
#table_id exists. Translate table_id
flow['table_id'] += self.offset_table
#validate table_id
if flow['table_id'] not in self.tables:
return None #Not acceptable. Table id is out of range
#validate dl_vlan
if 'match' in flow:
if 'dl_vlan' in flow['match']:
if flow['match']['dl_vlan'] not in self.vlans:
return None #Not acceptable. Vlan is out of range
#validate if actions not existing. This is for get flows stats filtered by field.
if 'actions' not in flow:
return flow
#validate if actions is empty. Actions = drop (actions = [])
if len(flow['actions']) == 0:
return flow
for action in flow['actions']:
#Block PUSH_VLAN and POP_VLAN action
if action['type'] in ['PUSH_VLAN','POP_VLAN']:
return None
#validate if vlan_id is in defined range
if ('field' and 'value') in action:
if (action['field'] == 'vlan_vid') and ((action['value'] - 4096) not in self.vlans):
return None
#translate table_id existing in actions
if 'table_id' not in action:
continue
index = flow['actions'].index(action) #Table_id exists in actions
flow['actions'][index]['table_id'] += self.offset_table
if flow['actions'][index]['table_id'] not in self.tables:
return None #Not accepcted. Table id is out of range
return flow
#create global objects of tenants
tenant_list = []
tenant_by_auth = {}
tenant_by_name = {}
for name, data in tenants_data.iteritems():
t = Tenant(name, **data)
tenant_list.append(t)
tenant_by_auth[t.authtoken] = t
tenant_by_name[t.name] = t
def query_ryu(url,data):
list_flows = []
for single_data in data:
req_to_ryu = urllib2.Request(url, single_data, {'Content-Type': 'application/json'})
#error
try:
res_from_ryu = urllib2.urlopen(req_to_ryu)
except urllib2.HTTPError, err:
return err.code
response = res_from_ryu.read()
if len(response) == 0:
continue
flows = json.loads(response)
list_flows.append(flows)
return list_flows
#translate a bundle of flows (a list of dictionaries of single flow)
def xlat_flows_from_ryu(return_flows,dpid,tenant):
xlat_flows = {dpid:[]}
for single_dict in return_flows:
for single_flow in single_dict[dpid]:
xlat_flow = tenant.xlat_switch_to_tenant(single_flow)
xlat_flows[dpid].append(xlat_flow)
return xlat_flows
class StatsController2(ControllerBase):
def __init__(self, req, link, data, **config):
super(StatsController2, self).__init__(req, link, data, **config)
self.waiters = data['waiters']
#Get all dpids
def get_dpids(self, req, **_kwargs):
url = 'http://{}:{}/stats/switches'.format(ryu_IP, ryu_port)
req_to_ryu = urllib2.Request(url)
res_from_ryu = urllib2.urlopen(req_to_ryu)
body_to_tenant = res_from_ryu.read()
return Response(content_type='application/json', body=body_to_tenant) #Response the list of dpids to tenant
#Get flows stats
def get_flow_stats(self, req, dpid, **_kwargs):
if req.body == '':
flow = {}
else:
try:
flow = ast.literal_eval(req.body)
except SyntaxError:
LOG.debug('invalid syntax %s', req.body)
return Response(status=400)
#url of Ryu ofctl_rest API
url = 'http://{}:{}/stats/flow/{}'.format(ryu_IP, ryu_port, dpid)
#Get the header 'Authorization' from request of tenant
header_auth = req.headers['Authorization']
if header_auth not in tenant_by_auth:
return Response(status=403) #Forbidden
tenant = tenant_by_auth[header_auth] #authorized tenant
#Get all flows stats API (GET method)
if (req.method == 'GET'):
data_list_ryu = []
for tableid in tenant.tables:
data_list_ryu.append(json.dumps({"table_id": tableid}))
return_flows = query_ryu(url,data_list_ryu)
if type(return_flows) is not list:
return Response(status=return_flows) #return the error code
xlat_flows = xlat_flows_from_ryu(return_flows,dpid,tenant)
body_to_tenant = json.dumps(xlat_flows)
return Response(content_type='application/json', body=body_to_tenant) #Response the list of flows to tenant
#Get flows stats filtered by fields API (POST method)
elif req.method == 'POST':
if (len(flow) == 0) or ('table_id' not in flow) or (flow['table_id'] == 0xff):
data_list_ryu = []
for tableid in tenant.tables:
flow['table_id'] = tableid
data_req_to_ryu = json.dumps(flow)
data_list_ryu.append(data_req_to_ryu)
return_flows = query_ryu(url,data_list_ryu)
if type(return_flows) is not list:
return Response(status=return_flows) #return the error code
xlat_flows = xlat_flows_from_ryu(return_flows,dpid,tenant)
body_to_tenant = json.dumps(xlat_flows)
return Response(content_type='application/json', body=body_to_tenant) #Response the list of flows to tenant
#specific table_id
xlat_flow = tenant.xlat_tenant_to_switch(flow)
if xlat_flow == None:
return Response(status = 406) #not acceptable
data_to_ryu = json.dumps(xlat_flow)
return_flows = query_ryu(url,(data_to_ryu,))
if type(return_flows) is not list:
return Response(status=return_flows) #return error code
xlat_flows = xlat_flows_from_ryu(return_flows,dpid,tenant)
body_to_tenant = json.dumps(xlat_flows)
return Response(content_type='application/json', body=body_to_tenant)
#Modify flow entry (add/delete/modify)
def mod_flow_entry(self, req, cmd, **_kwargs):
try:
flow = ast.literal_eval(req.body)
except SyntaxError:
LOG.debug('invalid syntax %s', req.body)
return Response(status=400)
header_auth = req.headers['Authorization']
if header_auth not in tenant_by_auth:
return Response(status=403) #Forbidden. Invalid tenant
tenant = tenant_by_auth[header_auth] #authorized tenant
xlat_flow = tenant.xlat_tenant_to_switch(flow)
if xlat_flow == None:
return Response(status=406) #Not acceptable
url = 'http://{}:{}/stats/flowentry/{}'.format(ryu_IP, ryu_port, cmd)
data_to_ryu = json.dumps(xlat_flow)
req_to_ryu = urllib2.Request(url, data_to_ryu, {'Content-Type': 'application/json'})
try:
res_from_ryu = urllib2.urlopen(req_to_ryu)
return Response(status=res_from_ryu.code) #expectation: code = 200
except urllib2.HTTPError, err:
return Response(status=err.code)
#Delete all flows
def delete_flow_entry(self, req, dpid, **_kwargs):
if type(dpid) == str and not dpid.isdigit():
LOG.debug('invalid dpid %s', dpid)
return Response(status=400)
url = 'http://{}:{}/stats/flowentry/delete'.format(ryu_IP, ryu_port)
header_auth = req.headers['Authorization']
if header_auth not in tenant_by_auth:
return Response(status=403) #Forbidden. Invalid tenant
tenant = tenant_by_auth[header_auth] #authorized tenant
data_list_ryu = []
for tableid in tenant.tables:
data_to_ryu = json.dumps({"dpid": dpid, "table_id": tableid})
data_list_ryu.append(data_to_ryu)
response = query_ryu(url,data_list_ryu)
if type(response) is not list:
return Response(status=response) #return error code
return Response(status=200) #successful delete all flows of tenant
class RestStatsApi2(app_manager.RyuApp):
OFP_VERSIONS = [ofproto_v1_3.OFP_VERSION]
_CONTEXTS = {
'wsgi': WSGIApplication
}
def __init__(self, *args, **kwargs):
super(RestStatsApi2, self).__init__(*args, **kwargs)
wsgi = kwargs['wsgi']
self.waiters = {}
self.data = {}
self.data['waiters'] = self.waiters
mapper = wsgi.mapper
wsgi.registory['StatsController2'] = self.data
path = '/sharedcontroller/stats'
uri = path + '/switches'
mapper.connect('stats', uri,
controller=StatsController2, action='get_dpids',
conditions=dict(method=['GET']))
uri = path + '/flow/{dpid}'
mapper.connect('stats', uri,
controller=StatsController2, action='get_flow_stats',
conditions=dict(method=['GET', 'POST']))
uri = path + '/flowentry/{cmd}'
mapper.connect('stats', uri,
controller=StatsController2, action='mod_flow_entry',
conditions=dict(method=['POST']))
uri = path + '/flowentry/clear/{dpid}'
mapper.connect('stats', uri,
controller=StatsController2, action='delete_flow_entry',
conditions=dict(method=['DELETE']))
#wait for switches connect to controller before sending pre-provisioned flows
@set_ev_cls(ofp_event.EventOFPSwitchFeatures, CONFIG_DISPATCHER)
def pre_provision(self, ev):
msg = ev.msg
dp = msg.datapath
ofctl = supported_ofctl.get(dp.ofproto.OFP_VERSION)
url = 'http://{}:{}/stats/switches'.format(ryu_IP, ryu_port)
req1 = urllib2.Request(url)
response = urllib2.urlopen(req1)
dp_list = response.read()
dpid_list = json.loads(dp_list)
#add pre-provisioned flows to switches
url = 'http://{}:{}/stats/flowentry/add'.format(ryu_IP, ryu_port)
for dpid_pre in dpid_list:
for index in xrange(len(tenant_list)):
for vlanid in xrange(len(tenant_list[index].vlans)):
data_pre = json.dumps({"dpid": dpid_pre, "priority": 0, "match": {"dl_vlan":hex(tenant_list[index].vlans[vlanid]| 0x1000)}, "actions": [{"type":"GOTO_TABLE","table_id": tenant_list[index].offset_table}]})
req_pre = urllib2.Request(url, data_pre, {'Content-Type': 'application/json'})
response_pre = urllib2.urlopen(req_pre)