REST: SFA interface GetVersion and ListResources
[myslice.git] / rest / sfa_api.py
1 from sfa.trust.certificate      import Keypair, Certificate
2 from sfa.client.sfaserverproxy  import SfaServerProxy
3 from sfa.client.return_value    import ReturnValue
4 from sfa.util.xrn               import Xrn, get_leaf, get_authority, hrn_to_urn, urn_to_hrn
5 from manifold.core.query        import Query
6 from manifold.models            import db
7 from manifold.models.platform   import Platform
8 from manifold.models.user       import User
9
10 from django.shortcuts           import render_to_response
11
12 from unfold.loginrequired       import LoginRequiredView
13
14 from rest import ObjectRequest, error
15
16 from string import join
17
18 from django.http import HttpResponse
19 from rest import error
20 import os,json
21
22 import ConfigParser 
23
24 def dispatch(request, method):
25     Config = ConfigParser.ConfigParser()
26     Config.read(os.getcwd() + "/myslice/monitor.ini")
27
28     # hardcoded user to be replaced by auth
29     user_email = "loic.baron@lip6.fr"
30
31     # Get this as parameters
32     slice_hrn = "fed4fire.upmc.berlin"
33     urn = hrn_to_urn(slice_hrn, "slice")
34     #urn = hrn_to_urn("fed4fire.upmc.loic_baron", "user")
35
36     platforms = list()
37     options   = list()
38     rspec = ''
39     results = dict()
40
41     if request.method == 'POST':
42         req_items = request.POST
43     elif request.method == 'GET':
44         req_items = request.GET
45
46     for el in req_items.items():
47         if el[0].startswith('rspec'):
48             rspec += el[1]
49         if el[0].startswith('platform'):
50             platforms += req_items.getlist('platform[]')
51         elif el[0].startswith('options'):
52             options += req_items.getlist('options[]')
53
54     if len(platforms)==0:
55         platforms.append('myslice')
56     #results = {'method':method,'platforms':platforms,'rspec':rspec,'options':options}
57
58     from manifoldapi.manifoldapi    import execute_admin_query
59     for pf in platforms:
60         platform = get_platform_config(pf)
61         print platform
62         if 'sm' in platform and len(platform['sm']) > 0:
63             print 'sm'
64             server_url = platform['sm']
65         if 'rm' in platform and len(platform['rm']) > 0:
66             print 'rm'
67             server_url = platform['rm']
68         if 'registry' in platform and len(platform['registry']) > 0:
69             print 'registry'
70             server_url = platform['registry']
71     
72         if not Config.has_option('monitor', 'cert') :
73              return HttpResponse(json.dumps({'error' : '-1'}), content_type="application/json")
74
75         cert = os.path.abspath(Config.get('monitor', 'cert'))
76         if not os.path.isfile(cert) :
77              return HttpResponse(json.dumps({'error' : '-1'}), content_type="application/json")
78
79         if not Config.has_option('monitor', 'pkey') :
80              return HttpResponse(json.dumps({'error' : '-2'}), content_type="application/json")
81
82         pkey = os.path.abspath(Config.get('monitor', 'pkey'))
83         if not os.path.isfile(pkey) :
84              return HttpResponse(json.dumps({'error' : '-2'}), content_type="application/json")
85  
86         server = SfaServerProxy(server_url, pkey, cert)
87
88         # Get user config from Manifold
89         user_config = get_user_config(user_email, pf)
90         if 'delegated_user_credential' in user_config:
91             user_cred = user_config['delegated_user_credential']
92         else:
93             user_cred = {}
94
95         #if 'delegated_slice_credentials' in user_config:
96         #    for slice_name, cred in user_config['delegated_slice_credentials']:
97         #        if slice_name == slice_param
98
99         if method == "GetVersion": 
100             result = server.GetVersion()
101         elif method == "ListResources":
102             api_options = {}
103             #api_options ['call_id'] = unique_call_id()
104             api_options['geni_rspec_version'] = {'type': 'GENI', 'version': '3'}
105             result = server.ListResources([user_cred], api_options)
106         elif method == "Describe":
107             api_options = {}
108             #api_options ['call_id'] = unique_call_id()
109             api_options['geni_rspec_version'] = {'type': 'GENI', 'version': '3'}
110             result = server.Describe([urn] ,[object_cred], api_options)
111
112         else:
113             return HttpResponse(json.dumps({'error' : '-3','msg':'method not supported yet'}), content_type="application/json")
114
115         results[pf] = result
116
117     return HttpResponse(json.dumps(results), content_type="application/json")
118
119 def get_user_account(user_email, platform_name):
120     """
121     Returns the user configuration for a given platform.
122     This function does not resolve references.
123     """
124     user = db.query(User).filter(User.email == user_email).one()
125     platform = db.query(Platform).filter(Platform.platform == platform_name).one()
126     accounts = [a for a in user.accounts if a.platform == platform]
127     if not accounts:
128         raise Exception, "this account does not exist"
129
130     if accounts[0].auth_type == 'reference':
131         pf = json.loads(accounts[0].config)['reference_platform']
132         return get_user_account(user_email, pf)
133
134     return accounts[0]
135
136 def get_user_config(user_email, platform_name):
137     account = get_user_account(user_email, platform_name)
138     return json.loads(account.config) if account.config else {}
139
140 def get_platform_config(platform_name):
141     platform = db.query(Platform).filter(Platform.platform == platform_name).one()
142     return json.loads(platform.config) if platform.config else {}