5 from time import mktime
8 from django.shortcuts import render_to_response
9 from django.http import HttpResponse
11 from sfa.trust.certificate import Keypair, Certificate
12 from sfa.client.sfaserverproxy import SfaServerProxy
13 from sfa.client.return_value import ReturnValue
14 from sfa.util.xrn import Xrn, get_leaf, get_authority, hrn_to_urn, urn_to_hrn
16 from manifold.core.query import Query
17 from manifold.models import db
18 from manifold.models.platform import Platform
19 from manifold.models.user import User
21 from unfold.loginrequired import LoginRequiredView
23 from myslice.settings import logger, config
25 from rest.json_encoder import MyEncoder
27 def dispatch(request, method):
40 if request.method == 'POST':
41 req_items = request.POST
42 elif request.method == 'GET':
43 req_items = request.GET
45 for el in req_items.items():
46 if el[0].startswith('rspec'):
48 elif el[0].startswith('platform'):
49 platforms += req_items.getlist('platform[]')
50 #elif el[0].startswith('options'):
51 # options += req_items.getlist('options[]')
52 elif el[0].startswith('hrn'):
54 elif el[0].startswith('urn'):
56 elif el[0].startswith('type'):
58 elif el[0].startswith('recursive'):
63 elif el[0].startswith('display'):
66 results = sfa_client(request, method, hrn, urn, object_type, recursive, options, platforms)
68 if display == 'table':
69 return render_to_response('table-default.html', {'data' : data, 'fields' : columns, 'id' : '@component_id', 'options' : None})
71 return HttpResponse(json.dumps(results, cls=MyEncoder), content_type="application/json")
73 def get_user_account(user_email, platform_name):
75 Returns the user configuration for a given platform.
76 This function does not resolve references.
78 user = db.query(User).filter(User.email == user_email).one()
79 platform = db.query(Platform).filter(Platform.platform == platform_name).one()
80 accounts = [a for a in user.accounts if a.platform == platform]
82 raise Exception, "this account does not exist"
84 if accounts[0].auth_type == 'reference':
85 pf = json.loads(accounts[0].config)['reference_platform']
86 return get_user_account(user_email, pf)
90 def sfa_client(request, method, hrn=None, urn=None, object_type=None, rspec=None, recursive=None, options=None, platforms=None, admin=False):
92 Config = ConfigParser.ConfigParser()
93 Config.read(os.getcwd() + "/myslice/myslice/monitor.ini")
96 user_email, admin_password = config.manifold_admin_user_password()
98 #logger.debug(request.session['user']['email'])
99 user_email = request.session['user']['email']
107 if object_type is None:
111 if recursive is None:
115 if platforms is None:
118 if method not in ['GetVersion','ListResources']:
121 hrn = urn_to_hrn(urn)
123 urn = hrn_to_urn(hrn, object_type)
126 raise Exception, "Provide urn OR hrn + type as parameters of method %s" % method
128 if len(platforms)==0:
129 platforms = get_platforms()
130 #platforms.append('myslice')
131 #results = {'method':method,'platforms':platforms,'rspec':rspec,'options':options}
138 api_options['geni_rspec_version'] = {'type': 'GENI', 'version': '3'}
139 api_options['list_leases'] = 'all'
141 from manifoldapi.manifoldapi import execute_admin_query
143 platform = get_platform_config(pf)
144 logger.debug("platform={}".format(platform))
145 if 'sm' in platform and len(platform['sm']) > 0:
148 server_url = platform['sm']
149 if 'rm' in platform and len(platform['rm']) > 0:
152 server_url = platform['rm']
153 if 'registry' in platform and len(platform['registry']) > 0:
154 logger.debug('registry')
156 server_url = platform['registry']
158 if not Config.has_option('monitor', 'cert') :
159 #return HttpResponse(json.dumps({'error' : '-1'}), content_type="application/json")
160 return {'error' : '-1', 'msg': 'monitor.ini has no cert configured'}
162 cert = os.path.abspath(Config.get('monitor', 'cert'))
163 if not os.path.isfile(cert) :
164 #return HttpResponse(json.dumps({'error' : '-1'}), content_type="application/json")
165 return {'error' : '-1', 'msg': 'check cert file at %s'%cert}
167 if not Config.has_option('monitor', 'pkey') :
168 #return HttpResponse(json.dumps({'error' : '-2'}), content_type="application/json")
169 return {'error' : '-2'}
171 pkey = os.path.abspath(Config.get('monitor', 'pkey'))
172 if not os.path.isfile(pkey) :
173 #return HttpResponse(json.dumps({'error' : '-2'}), content_type="application/json")
174 return {'error' : '-2'}
176 server = SfaServerProxy(server_url, pkey, cert)
179 # Get user config from Manifold
180 user_config = get_user_config(user_email, pf)
181 if 'delegated_user_credential' in user_config:
182 user_cred = user_config['delegated_user_credential']
183 elif 'user_credential' in user_config:
184 user_cred = user_config['user_credential']
189 if 'delegated_%s_credentials'%object_type in user_config:
190 for obj_name, cred in user_config['delegated_%s_credentials'%object_type].items():
193 elif '%s_credentials'%object_type in user_config:
194 for obj_name, cred in user_config['%s_credentials'%object_type].items():
199 if method == "GetVersion":
200 result = server.GetVersion()
204 if method == "ListResources":
205 result = server.ListResources([user_cred], api_options)
206 dict_result = xmltodict.parse(result['value'])
207 result['json'] = json.dumps(dict_result)
208 if isinstance(dict_result['rspec']['node'], list):
209 columns.extend(dict_result['rspec']['node'][0].keys())
211 columns.extend(dict_result['rspec']['node'].keys())
213 elif method == "Describe":
214 version = server.GetVersion()
215 logger.debug(version['geni_api'])
217 if version['geni_api'] == 2:
218 # ListResources(slice_hrn)
219 api_options['geni_slice_urn'] = urn
220 result = server.ListResources([object_cred], api_options)
221 dict_result = xmltodict.parse(result['value'])
222 # else GetVersion = v3
224 result = server.Describe([urn] ,[object_cred], api_options)
225 dict_result = xmltodict.parse(result['value']['geni_rspec'])
227 result['json'] = json.dumps(dict_result)
228 if isinstance(dict_result['rspec']['node'], list):
229 columns.extend(dict_result['rspec']['node'][0].keys())
231 columns.extend(dict_result['rspec']['node'].keys())
233 elif method == 'Renew':
234 # Renew till 1 month from now
235 d = datetime.datetime.utcnow() + datetime.timedelta(365/12)
236 date = d.isoformat("T") + "Z"
237 result = server.Renew([urn] ,[object_cred], date, api_options)
238 elif method == 'Delete':
239 result = server.Delete([urn] ,[object_cred], api_options)
240 elif method == 'Allocate':
242 # CreateSliver(slice_hrn)
243 # else GetVersion = v3
244 api_options['call_id'] = unique_call_id()
245 # List of users comes from the Registry
246 api_options['sfa_users'] = sfa_users
247 api_options['geni_users'] = geni_users
248 result = server.Allocate([urn] ,[object_cred], rspec, api_options)
249 elif method == 'Provision':
251 # Nothing it is not supported by v2 AMs
252 api_options['call_id'] = unique_call_id()
253 # List of users comes from the Registry
254 api_options['sfa_users'] = sfa_users
255 api_options['geni_users'] = geni_users
256 result = server.Provision([urn] ,[object_cred], api_options)
257 elif method == 'Status':
258 result = server.Status([urn] ,[object_cred], api_options)
259 elif method == 'PerformOperationalAction':
261 # Nothing it is not supported by v2 AMs
262 result = server.PerformOperationalAction([urn] ,[object_cred], action, api_options)
263 elif method == 'Shutdown':
264 result = server.Shutdown(urn ,[object_cred], api_options)
266 #return HttpResponse(json.dumps({'error' : '-3','msg':'method not supported by AM'}), content_type="application/json")
267 logger.debug('method %s not handled by AM' % method)
272 record_dict = {'urn': urn, 'hrn': hrn, 'type': object_type}
275 api_options['recursive'] = recursive
276 result = server.List(hrn, user_cred, api_options)
278 result = filter_records(object_type, result)
279 elif method == "Resolve":
281 # details can be True or False
282 api_options['details']=True
283 result = server.Resolve(hrn, user_cred, api_options)
285 result = filter_records(object_type, result)
286 elif method == "Register":
287 # record_dict must be crafted
288 # auth_cred must be selected in the list of auth_creds from user's account
289 result = server.Register(record_dict, auth_cred)
290 elif method == "Update":
291 # record_dict must be crafted
292 # object_cred must be selected in the list of creds for the object type
293 # from user's account
294 result = server.Update(record_dict, object_cred)
295 elif method == "Remove":
297 # auth_cred must be selected in the list of auth_creds from user's account
298 # object_type is required
299 result = server.Remove(hrn, auth_cred, object_type)
301 #return HttpResponse(json.dumps({'error' : '-3','msg':'method not supported by Registry'}), content_type="application/json")
302 logger.debug('method %s not handled by Registry' % method)
307 if isinstance(dict_result['rspec']['node'], list):
308 data = data + dict_result['rspec']['node']
310 data.append(dict_result['rspec']['node'])
313 logger.error(traceback.format_exc())
315 results[pf] = {'error':'-3', 'error_msg': str(e)}
317 results['columns'] = columns
320 def get_user_config(user_email, platform_name):
321 account = get_user_account(user_email, platform_name)
322 return json.loads(account.config) if account.config else {}
326 platforms = db.query(Platform).filter(Platform.gateway_type == 'sfa', Platform.disabled == 0).all()
328 ret.append(p.platform)
332 def get_platform_config(platform_name):
333 platform = db.query(Platform).filter(Platform.platform == platform_name).one()
334 return json.loads(platform.config) if platform.config else {}
336 def filter_records(type, records):
337 filtered_records = []
338 for record in records:
339 if (record['type'] == type) or (type == "all"):
340 filtered_records.append(record)
341 return filtered_records