plugins.scheduler: scheduler almost working
[unfold.git] / portal / actions.py
1 from django.http                 import HttpResponse
2 from manifold.core.query         import Query
3 from manifold.manifoldapi        import execute_query,execute_admin_query
4 from portal.models               import PendingUser, PendingSlice
5 import json
6
7 # Thierry: moving this right into the code so 
8 # most people can use myslice without having to install sfa
9 # XXX tmp sfa dependency, should be moved to SFA gateway
10 #from sfa.util.xrn                import Xrn 
11
12
13 # Get the list of authorities
14
15 def authority_get_pis(request, authority_hrn):
16     query = Query.get('authority').filter_by('authority_hrn', '==', authority_hrn).select('pi_users')
17     results = execute_query(request, query)
18     # NOTE: temporarily commented. Because results is giving empty list. 
19     # Needs more debugging
20     #if not results:
21     #    raise Exception, "Authority not found: %s" % authority_hrn
22     #result, = results
23     #return result['pi_users']
24     return results
25
26 def authority_get_pi_emails(request, authority_hrn):
27     return ['jordan.auge@lip6.fr', 'loic.baron@lip6.fr']
28
29     pi_users = authority_get_pis(request,authority_hrn)
30     pi_user_hrns = [ hrn for x in pi_users for hrn in x['pi_users'] ]
31     query = Query.get('user').filter_by('user_hrn', 'included', pi_user_hrns).select('email')
32     results = execute_query(request, query)
33     print "mails",  [result['email'] for result in results]
34     return [result['email'] for result in results]
35
36 # SFA add record (user, slice)
37
38 def sfa_add_user(request, user_params):
39     query = Query.create('user').set(user_params).select('user_hrn')
40     results = execute_query(request, query)
41     if not results:
42         raise Exception, "Could not create %s. Already exists ?" % user_params['hrn']
43     return results
44
45 def sfa_add_slice(request, slice_params):
46     query = Query.create('slice').set(slice_params).select('slice_hrn')
47     results = execute_query(request, query)
48     if not results:
49         raise Exception, "Could not create %s. Already exists ?" % slice_params['hrn']
50     return results
51
52 # Propose hrn
53
54 def manifold_add_user(request, user_params):
55     # user_params: email, password e.g., user_params = {'email':'aa@aa.com','password':'demo'}
56     query = Query.create('local:user').set(user_params).select('email')
57     results = execute_admin_query(request, query)
58     if not results:
59         raise Exception, "Failed creating manifold user: %s" % user_params['email']
60     result, = results
61     return result['email']
62
63 def manifold_update_user(request, user_params):
64     # user_params: password, config e.g., 
65     query = Query.update('local:user').filter_by('email', '==', request.user.email).set(user_params).select('email')
66     results = execute_query(request,query)
67     # NOTE: results remains empty and goes to Exception. However, it updates the manifold DB.
68     # That's why I commented the exception part. -- Yasin 
69     #if not results:
70     #    raise Exception, "Failed updating manifold user: %s" % user_params['email']
71     #result, = results
72     return results
73
74 def manifold_add_account(request, account_params):
75     query = Query.create('local:account').set(account_params).select(['user', 'platform'])
76     results = execute_admin_query(request,query)
77     if not results:
78         raise Exception, "Failed creating manifold account on platform %s for user: %s" % (account_params['platform'], account_params['user'])
79     result, = results
80     return result['user_id']
81
82 def manifold_update_account(request,account_params):
83     # account_params: config
84     query = Query.update('local:account').filter_by('platform', '==', 'myslice').set(account_params).select('user_id')
85     results = execute_query(request,query)
86     # NOTE: results remains empty and goes to Exception. However, it updates the manifold DB.
87     # That's why I commented the exception part. -- Yasin 
88     #if not results:
89     #    raise Exception, "Failed updating manifold account: config %s" % account_params['config']
90     #result, = results
91     return results
92
93
94 def make_request_user(user):
95     request = {}
96     request['type']          = 'user'
97     request['id']            = user.id
98     request['timestamp']     = user.created # XXX in DB ?
99     request['authority_hrn'] = user.authority_hrn
100     request['first_name']    = user.first_name
101     request['last_name']     = user.last_name
102     request['email']         = user.email
103     request['login']         = user.login
104     request['keypair']       = user.keypair
105     return request
106
107 def make_request_slice(slice):
108     request = {}
109     request['type'] = 'slice'
110     request['id'] = slice.id
111     request['timestamp'] = slice.created
112     request['authority_hrn'] = slice.authority_hrn
113     request['slice_name'] = slice.slice_name
114     request['number_of_nodes'] = slice.number_of_nodes
115     request['type_of_nodes'] = slice.type_of_nodes
116     request['purpose'] = slice.purpose
117     return request
118
119 def make_requests(pending_users, pending_slices):
120     print "pending users =", pending_users
121     print "pending slices =", pending_slices
122
123     requests = []
124     for user in pending_users:
125         requests.append(make_request_user(user))
126     for slice in pending_slices:
127         requests.append(make_request_slice(slice))
128     return requests   
129
130 def get_request_by_id(ids):
131     sorted_ids = { 'user': [], 'slice': [] }
132     for type__id in ids:
133         type, id = type__id.split('__')
134         sorted_ids[type].append(id)
135         
136     if not ids:
137         pending_users  = PendingUser.objects.all()
138         pending_slices = PendingSlice.objects.all()
139     else:
140         pending_users  = PendingUser.objects.filter(id__in=sorted_ids['user']).all()
141         pending_slices = PendingSlice.objects.filter(id__in=sorted_ids['slice']).all()
142
143     return make_requests(pending_users, pending_slices)
144
145 def get_request_by_authority(authority_hrns):
146     if not authority_hrns:
147         pending_users  = PendingUser.objects.all()
148         pending_slices = PendingSlice.objects.all()
149     else:
150         pending_users  = PendingUser.objects.filter(authority_hrn__in=authority_hrns).all()
151         pending_slices = PendingSlice.objects.filter(authority_hrn__in=authority_hrns).all()
152
153     return make_requests(pending_users, pending_slices)
154     
155 # XXX Is it in sync with the form fields ?
156
157 def portal_validate_request(wsgi_request, request_ids):
158     status = {}
159
160     if not isinstance(request_ids, list):
161         request_ids = [request_ids]
162
163     requests = get_request_by_id(request_ids)
164     for request in requests:
165         # type, id, timestamp, details, allowed -- MISSING: authority_hrn
166         # CAREFUL about details
167         # user  : first name, last name, email, password, keypair
168         # slice : number of nodes, type of nodes, purpose
169         
170         request_status = {}
171
172         print "REQUEST", request
173         if request['type'] == 'user':
174
175             try:
176                 hrn = "%s.%s" % (request['authority_hrn'], request['login'])
177                 # XXX tmp sfa dependency
178                 from sfa.util.xrn import Xrn 
179                 urn = Xrn(hrn, request['type']).get_urn()
180
181                 sfa_user_params = {
182                     'hrn'        : hrn, 
183                     'urn'        : urn,
184                     'type'       : request['type'],
185                     'keys'       : [json.loads(request['keypair'])['user_public_key']],
186                     'first_name' : request['first_name'],
187                     'last_name'  : request['last_name'],
188                     'email'      : request['email'],
189                     #'slices'    : None,
190                     #'researcher': None,
191                     #'pi'        : None,
192                     'enabled'    : True
193                 }
194                 # ignored in request: id, timestamp, password
195
196                 sfa_add_user(wsgi_request, sfa_user_params)
197
198                 # XXX Remove from database
199
200
201                 request_status['SFA user'] = {'status': True }
202
203             except Exception, e:
204                 request_status['SFA user'] = {'status': False, 'description': str(e)}
205
206             # MANIFOLD user should be added beforehand, during registration
207             #try:
208             #    manifold_user_params = { key: request[key] for key in MANIFOLD_USER_KEYS }
209             #    # XXX # manifold_add_user(manifold_user_params)
210             #    request_status['MySlice user'] = {'status': True }
211             #except Exception, e:
212             #    request_status['MySlice user'] = {'status': False, 'description': str(e)}
213
214             # XXX
215             #manifold_account_params = { key: request[key] for key in MANIFOLD_ACCOUNT_KEYS }
216             #manifold_add_account(manifold_account_params)
217             #request_status['MySlice testbed accounts'] = {'status': False }
218
219         elif request['type'] == 'slice':
220             try:
221                 hrn = "%s.%s" % (request['authority_hrn'], request['slice_name'])
222                 # XXX tmp sfa dependency
223                 from sfa.util.xrn import Xrn 
224                 urn = Xrn(hrn, request['type']).get_urn()
225
226                 sfa_slice_params = {
227                     'hrn'        : hrn, 
228                     'urn'        : urn,
229                     'type'       : request['type'],
230                     #'slices'    : None,
231                     #'researcher': None,
232                     #'pi'        : None,
233                     'enabled'    : True
234                 }
235                 # ignored in request: id, timestamp,  number_of_nodes, type_of_nodes, purpose
236
237                 sfa_add_slice(wsgi_request, sfa_slice_params)
238
239                 # XXX Remove from database
240
241             
242                 request_status['SFA slice'] = {'status': True }
243
244             except Exception, e:
245                 request_status['SFA slice'] = {'status': False, 'description': str(e)}
246
247         status['%s__%s' % (request['type'], request['id'])] = request_status
248
249     return status
250
251
252 def validate_action(request, **kwargs):
253     ids = filter(None, kwargs['id'].split('/'))
254     status = portal_validate_request(request, ids)
255     json_answer = json.dumps(status)
256     return HttpResponse (json_answer, mimetype="application/json")
257
258 # Django and ajax
259 # http://djangosnippets.org/snippets/942/