fixed a bug
[myslice.git] / portal / actions.py
1 from django.http                 import HttpResponse
2 from manifold.core.query         import Query
3 from manifold.manifoldapi        import execute_query
4 from portal.models               import PendingUser, PendingSlice
5 import json
6
7 # Get the list of authorities
8
9 def authority_get_pis(request, authority_hrn):
10     query = Query.get('authority').filter_by('authority_hrn', '==', authority_hrn).select('pi_users')
11     results = execute_query(request, query)
12     # NOTE: temporarily commented. Because results is giving empty list. 
13     # Needs more debugging
14     #if not results:
15     #    raise Exception, "Authority not found: %s" % authority_hrn
16     #result, = results
17     #return result['pi_users']
18     return results
19
20 def authority_get_pi_emails(request,authority_hrn):
21     pi_users = authority_get_pis(request,authority_hrn)
22     pi_user_hrns = [ hrn for x in pi_users for hrn in x['pi_users'] ]
23     query = Query.get('user').filter_by('user_hrn', 'included', pi_user_hrns).select('email')
24     results = execute_query(request,query)
25     print "mails",  [result['email'] for result in results]
26     return [result['email'] for result in results]
27
28 # SFA add record (user, slice)
29
30 def sfa_add_user(user_params):
31     # sfi.py add --xrn=fed4fire.upmc.timur_friedman --type=user --key=/root/.sfi/timur.pub --email=timur.friedman@lip6.fr --extra=first_name=Timur --extra=last_name=Friedman --extra=enabled=true
32     # user_params: xrn type key email + first_name last_name enabled
33     query = Query.create('user').set(user_params).select('user_hrn')
34     results = execute_query(query)
35     if not results:
36         raise Exception, "Failed creating SFA user: %s" % user_params['user_hrn']
37     result, = results
38     return result['user_hrn']
39
40 def sfa_add_slice(slice_params):
41     pass
42
43 # Propose hrn
44
45 def manifold_add_user(request, user_params):
46     # user_params: email, password e.g., user_params = {'email':'aa@aa.com','password':'demo'}
47     query = Query.create('local:user').set(user_params).select('email')
48     results = execute_query(request,query)
49     if not results:
50         raise Exception, "Failed creating manifold user: %s" % user_params['email']
51     result, = results
52     return result['email']
53
54 def manifold_update_user(request, user_params):
55     # user_params: password, config e.g., 
56     query = Query.update('local:user').filter_by('email', '==', request.user.email).set(user_params).select('email')
57     results = execute_query(request,query)
58     # NOTE: results remains empty and goes to Exception. However, it updates the manifold DB.
59     # That's why I commented the exception part. -- Yasin 
60     #if not results:
61     #    raise Exception, "Failed updating manifold user: %s" % user_params['email']
62     #result, = results
63     return results
64
65 def manifold_add_account(request, account_params):
66     query = Query.create('local:account').set(account_params).select(['user', 'platform'])
67     results = execute_query(request,query)
68     if not results:
69         raise Exception, "Failed creating manifold account on platform %s for user: %s" % (account_params['platform'], account_params['user'])
70     result, = results
71     return (result['user'], result['platform'])
72
73 def manifold_update_account(request,account_params):
74     # account_params: config
75     query = Query.update('local:account').filter_by('platform', '==', 'myslice').set(account_params).select('user_id')
76     results = execute_query(request,query)
77     # NOTE: results remains empty and goes to Exception. However, it updates the manifold DB.
78     # That's why I commented the exception part. -- Yasin 
79     #if not results:
80     #    raise Exception, "Failed updating manifold account: config %s" % account_params['config']
81     #result, = results
82     return results
83
84
85 def make_request_user(user):
86     request = {}
87     request['type'] = 'user'
88     request['id'] = user.id
89     request['timestamp'] = 'TODO' # XXX in DB ?
90     request['authority_hrn'] = user.authority_hrn
91     request['first_name'] = user.first_name
92     request['last_name'] = user.last_name
93     request['email'] = user.email
94     return request
95
96 def make_request_slice(slice):
97     request = {}
98     request['type'] = 'slice'
99     request['id'] = slice.id
100     request['timestamp'] = 'TODO' # XXX in DB ?
101     request['authority_hrn'] = slice.authority_hrn
102     request['number_of_nodes'] = slice.number_of_nodes
103     request['type_of_nodes'] = slice.type_of_nodes
104     request['purpose'] = slice.purpose
105     return request
106
107 def make_requests(pending_users, pending_slices):
108     print "pending users =", pending_users
109     print "pending slices =", pending_slices
110
111     requests = []
112     for user in pending_users:
113         requests.append(make_request_user(user))
114     for slice in pending_slices:
115         requests.append(make_request_slice(slice))
116     return requests   
117
118 def get_request_by_id(ids):
119     sorted_ids = { 'user': [], 'slice': [] }
120     for type__id in ids:
121         type, id = type__id.split('__')
122         sorted_ids[type].append(id)
123         
124     if not ids:
125         pending_users  = PendingUser.objects.all()
126         pending_slices = PendingSlice.objects.all()
127     else:
128         pending_users  = PendingUser.objects.filter(id__in=sorted_ids['user']).all()
129         pending_slices = PendingSlice.objects.filter(id__in=sorted_ids['slice']).all()
130
131     return make_requests(pending_users, pending_slices)
132
133 def get_request_by_authority(authority_hrns):
134     if not authority_hrns:
135         pending_users  = PendingUser.objects.all()
136         pending_slices = PendingSlice.objects.all()
137     else:
138         pending_users  = PendingUser.objects.filter(authority_hrn__in=authority_hrns).all()
139         pending_slices = PendingSlice.objects.filter(authority_hrn__in=authority_hrns).all()
140
141     return make_requests(pending_users, pending_slices)
142     
143 SFA_USER_KEYS         = ['xrn', 'type', 'key', 'first_name', 'last_name', 'email']
144 SFA_SLICE_KEYS        = []
145 MANIFOLD_USER_KEYS    = ['email', 'password']
146 MANIFOLD_ACCOUNT_KEYS = []
147
148 def portal_validate_request(request_ids):
149     status = {}
150
151     if not isinstance(request_ids, list):
152         request_ids = [request_ids]
153
154     requests = get_request_by_id(request_ids)
155     for request in requests:
156         # type, id, timestamp, details, allowed -- MISSING: authority_hrn
157         # CAREFUL about details
158         # user  : first name, last name, email, password, keypair
159         # slice : number of nodes, type of nodes, purpose
160         
161         request_status = {}
162
163         if request['type'] == 'user':
164             try:
165                 sfa_user_params = { key: request[key] for key in SFA_USER_KEYS }
166                 sfa_user_params['enabled'] = True
167                 # XXX # sfa_add_user(sfa_user_params)
168                 request_status['SFA user'] = {'status': True }
169             except Exception, e:
170                 request_status['SFA user'] = {'status': False, 'description': str(e)}
171
172             try:
173                 manifold_user_params = { key: request[key] for key in MANIFOLD_USER_KEYS }
174                 # XXX # manifold_add_user(manifold_user_params)
175                 request_status['MySlice user'] = {'status': True }
176             except Exception, e:
177                 request_status['MySlice user'] = {'status': False, 'description': str(e)}
178
179             # XXX
180             #manifold_account_params = { key: request[key] for key in MANIFOLD_ACCOUNT_KEYS }
181             #manifold_add_account(manifold_account_params)
182             request_status['MySlice testbed accounts'] = {'status': False }
183
184         elif request['type'] == 'slice':
185             try:
186                 sfa_slice_params = { key: request[key] for key in SFA_SLICE_KEYS }
187                 # XXX # sfa_add_slice(sfa_slice_params)
188                 request_status['SFA slice'] = {'status': True }
189             except Exception, e:
190                 request_status['SFA slice'] = {'status': False, 'description': str(e)}
191
192         status['%s__%s' % (request['type'], request['id'])] = request_status
193
194     # XXX remove from database succeeded actions
195
196     return status
197
198
199 def validate_action(*args, **kwargs):
200     ids = filter(None, kwargs['id'].split('/'))
201     status = portal_validate_request(ids)
202     json_answer = json.dumps(status)
203     return HttpResponse (json_answer, mimetype="application/json")
204
205 # Django and ajax
206 # http://djangosnippets.org/snippets/942/