bug-fix
[sfa.git] / sfa / managers / registry_manager_pl.py
1 import types
2 import time 
3 from sfa.server.registry import Registries
4 from sfa.util.prefixTree import prefixTree
5 from sfa.util.record import SfaRecord
6 from sfa.util.table import SfaTable
7 from sfa.util.record import SfaRecord
8 from sfa.trust.gid import GID 
9 from sfa.util.namespace import *
10 from sfa.trust.credential import *
11 from sfa.trust.certificate import *
12 from sfa.util.faults import *
13
14 def get_credential(api, xrn, type, is_self=False):
15     # convert xrn to hrn     
16     if type:
17         hrn = urn_to_hrn(xrn)[0]
18     else:
19         hrn, type = urn_to_hrn(xrn)
20     # Is this a root or sub authority
21     auth_hrn = api.auth.get_authority(hrn)
22     if not auth_hrn or hrn == api.config.SFA_INTERFACE_HRN:
23         auth_hrn = hrn
24     # get record info
25     auth_info = api.auth.get_auth_info(auth_hrn)
26     table = SfaTable()
27     records = table.findObjects({'type': type, 'hrn': hrn})
28     if not records:
29         raise RecordNotFound(hrn)
30     record = records[0]
31
32     # verify_cancreate_credential requires that the member lists
33     # (researchers, pis, etc) be filled in
34     api.fill_record_info(record)
35     if record['type']=='user':
36        if not record['enabled']:
37           raise AccountNotEnabled(": PlanetLab account %s is not enabled. Please contact your site PI" %(record['email']))
38
39     # get the callers gid
40     # if this is a self cred the record's gid is the caller's gid
41     if is_self:
42         caller_hrn = hrn
43         caller_gid = record.get_gid_object()
44     else:
45         caller_gid = api.auth.client_cred.get_gid_caller() 
46         caller_hrn = caller_gid.get_hrn()
47     
48     object_hrn = record.get_gid_object().get_hrn()
49     rights = api.auth.determine_user_rights(caller_hrn, record)
50     # make sure caller has rights to this object
51     if rights.is_empty():
52         raise PermissionError(caller_hrn + " has no rights to " + record['name'])
53
54     object_gid = GID(string=record['gid'])
55     new_cred = Credential(subject = object_gid.get_subject())
56     new_cred.set_gid_caller(caller_gid)
57     new_cred.set_gid_object(object_gid)
58     new_cred.set_issuer(key=auth_info.get_pkey_object(), subject=auth_hrn)
59     new_cred.set_pubkey(object_gid.get_pubkey())
60     new_cred.set_privileges(rights)
61     new_cred.set_delegate(True)
62     auth_kind = "authority,ma,sa"
63     new_cred.set_parent(api.auth.hierarchy.get_auth_cred(auth_hrn, kind=auth_kind))
64     new_cred.encode()
65     new_cred.sign()
66
67     return new_cred.save_to_string(save_parents=True)
68
69 def resolve(api, xrns, type=None, origin_hrn=None):
70
71     # load all know registry names into a prefix tree and attempt to find
72     # the longest matching prefix
73     if not isinstance(xrns, types.ListType):
74         xrns = [xrns]
75     hrns = [urn_to_hrn(xrn)[0] for xrn in xrns] 
76     # create a dict whre key is an registry hrn and its value is a
77     # hrns at that registry (determined by the known prefix tree).  
78     xrn_dict = {}
79     registries = Registries(api)
80     tree = prefixTree()
81     registry_hrns = registries.keys()
82     tree.load(registry_hrns)
83     for xrn in xrns:
84         registry_hrn = tree.best_match(urn_to_hrn(xrn)[0])
85         if registry_hrn not in xrn_dict:
86             xrn_dict[registry_hrn] = []
87         xrn_dict[registry_hrn].append(xrn)
88         
89     records = [] 
90     for registry_hrn in xrn_dict:
91         # skip the hrn without a registry hrn
92         # XX should we let the user know the authority is unknown?       
93         if not registry_hrn:
94             continue
95
96         # if the best match (longest matching hrn) is not the local registry,
97         # forward the request
98         xrns = xrn_dict[registry_hrn]
99         if registry_hrn != api.hrn:
100             credential = api.getCredential()
101             peer_records = registries[registry_hrn].resolve(credential, xrns, origin_hrn)
102             records.extend([SfaRecord(dict=record).as_dict() for record in peer_records])
103
104     # try resolving the remaining unfound records at the local registry
105     remaining_hrns = set(hrns).difference([record['hrn'] for record in records])
106     # convert set to list
107     remaining_hrns = [hrn for hrn in remaining_hrns] 
108     table = SfaTable()
109     local_records = table.findObjects({'hrn': remaining_hrns})
110     for record in local_records:
111         try:
112             api.fill_record_info(record)
113             records.append(dict(record))
114         except PlanetLabRecordDoesNotExist:
115             # silently drop the ones that are missing in PL
116             print >> log, "ignoring SFA record ", record['hrn'], \
117                               " because pl record does not exist"    
118             table.remove(record)
119
120     if not records:
121         raise RecordNotFound(str(hrns))
122
123     if type:
124         records = filter(lambda rec: rec['type'] in [type], records)
125
126     return records
127
128 def list(api, xrn, origin_hrn=None):
129     hrn, type = urn_to_hrn(xrn)
130     # load all know registry names into a prefix tree and attempt to find
131     # the longest matching prefix
132     records = []
133     registries = Registries(api)
134     registry_hrns = registries.keys()
135     tree = prefixTree()
136     tree.load(registry_hrns)
137     registry_hrn = tree.best_match(hrn)
138     
139     #if there was no match then this record belongs to an unknow registry
140     if not registry_hrn:
141         raise MissingAuthority(xrn)
142     
143     # if the best match (longest matching hrn) is not the local registry,
144     # forward the request
145     records = []    
146     if registry_hrn != api.hrn:
147         credential = api.getCredential()
148         record_list = registries[registry_hrn].list(credential, xrn, origin_hrn)
149         records = [SfaRecord(dict=record).as_dict() for record in record_list]
150     
151     # if we still havnt found the record yet, try the local registry
152     if not records:
153         if not api.auth.hierarchy.auth_exists(hrn):
154             raise MissingAuthority(hrn)
155
156         table = SfaTable()
157         records = table.find({'authority': hrn})
158
159     return records
160
161
162 def register(api, record):
163
164     hrn, type = record['hrn'], record['type']
165
166     # validate the type
167     if type not in ['authority', 'slice', 'node', 'user']:
168         raise UnknownSfaType(type) 
169     
170     # check if record already exists
171     table = SfaTable()
172     existing_records = table.find({'type': type, 'hrn': hrn})
173     if existing_records:
174         raise ExistingRecord(hrn)
175        
176     record = SfaRecord(dict = record)
177     record['authority'] = get_authority(record['hrn'])
178     type = record['type']
179     hrn = record['hrn']
180     api.auth.verify_object_permission(hrn)
181     auth_info = api.auth.get_auth_info(record['authority'])
182     pub_key = None
183     # make sure record has a gid
184     if 'gid' not in record:
185         uuid = create_uuid()
186         pkey = Keypair(create=True)
187         if 'key' in record and record['key']:
188             if isinstance(record['key'], types.ListType):
189                 pub_key = record['key'][0]
190             else:
191                 pub_key = record['key']
192             pkey = convert_public_key(pub_key)
193
194         gid_object = api.auth.hierarchy.create_gid(hrn, uuid, pkey)
195         gid = gid_object.save_to_string(save_parents=True)
196         record['gid'] = gid
197         record.set_gid(gid)
198
199     if type in ["authority"]:
200         # update the tree
201         if not api.auth.hierarchy.auth_exists(hrn):
202             api.auth.hierarchy.create_auth(hrn)
203
204         # get the GID from the newly created authority
205         gid = auth_info.get_gid_object()
206         record.set_gid(gid.save_to_string(save_parents=True))
207         pl_record = api.sfa_fields_to_pl_fields(type, hrn, record)
208         sites = api.plshell.GetSites(api.plauth, [pl_record['login_base']])
209         if not sites:
210             pointer = api.plshell.AddSite(api.plauth, pl_record)
211         else:
212             pointer = sites[0]['site_id']
213
214         record.set_pointer(pointer)
215         record['pointer'] = pointer
216
217     elif (type == "slice"):
218         acceptable_fields=['url', 'instantiation', 'name', 'description']
219         pl_record = api.sfa_fields_to_pl_fields(type, hrn, record)
220         for key in pl_record.keys():
221             if key not in acceptable_fields:
222                 pl_record.pop(key)
223         slices = api.plshell.GetSlices(api.plauth, [pl_record['name']])
224         if not slices:
225              pointer = api.plshell.AddSlice(api.plauth, pl_record)
226         else:
227              pointer = slices[0]['slice_id']
228         record.set_pointer(pointer)
229         record['pointer'] = pointer
230
231     elif  (type == "user"):
232         persons = api.plshell.GetPersons(api.plauth, [record['email']])
233         if not persons:
234             pointer = api.plshell.AddPerson(api.plauth, dict(record))
235         else:
236             pointer = persons[0]['person_id']
237
238         if 'enabled' in record and record['enabled']:
239             api.plshell.UpdatePerson(api.plauth, pointer, {'enabled': record['enabled']})
240         # add this persons to the site only if he is being added for the first
241         # time by sfa and doesont already exist in plc
242         if not persons or not persons[0]['site_ids']:
243             login_base = get_leaf(record['authority'])
244             api.plshell.AddPersonToSite(api.plauth, pointer, login_base)
245
246         # What roles should this user have?
247         api.plshell.AddRoleToPerson(api.plauth, 'user', pointer)
248         # Add the user's key
249         if pub_key:
250             api.plshell.AddPersonKey(api.plauth, pointer, {'key_type' : 'ssh', 'key' : pub_key})
251
252     elif (type == "node"):
253         pl_record = api.sfa_fields_to_pl_fields(type, hrn, record)
254         login_base = hrn_to_pl_login_base(record['authority'])
255         nodes = api.plshell.GetNodes(api.plauth, [pl_record['hostname']])
256         if not nodes:
257             pointer = api.plshell.AddNode(api.plauth, login_base, pl_record)
258         else:
259             pointer = nodes[0]['node_id']
260
261     record['pointer'] = pointer
262     record.set_pointer(pointer)
263     record_id = table.insert(record)
264     record['record_id'] = record_id
265
266     # update membership for researchers, pis, owners, operators
267     api.update_membership(None, record)
268
269     return record.get_gid_object().save_to_string(save_parents=True)
270
271 def update(api, record_dict):
272     new_record = SfaRecord(dict = record_dict)
273     type = new_record['type']
274     hrn = new_record['hrn']
275     api.auth.verify_object_permission(hrn)
276     table = SfaTable()
277     # make sure the record exists
278     records = table.findObjects({'type': type, 'hrn': hrn})
279     if not records:
280         raise RecordNotFound(hrn)
281     record = records[0]
282     record['last_updated'] = time.gmtime()
283
284     # Update_membership needs the membership lists in the existing record
285     # filled in, so it can see if members were added or removed
286     api.fill_record_info(record)
287
288     # Use the pointer from the existing record, not the one that the user
289     # gave us. This prevents the user from inserting a forged pointer
290     pointer = record['pointer']
291     # update the PLC information that was specified with the record
292
293     if (type == "authority"):
294         api.plshell.UpdateSite(api.plauth, pointer, new_record)
295
296     elif type == "slice":
297         pl_record=api.sfa_fields_to_pl_fields(type, hrn, new_record)
298         if 'name' in pl_record:
299             pl_record.pop('name')
300             api.plshell.UpdateSlice(api.plauth, pointer, pl_record)
301
302     elif type == "user":
303         # SMBAKER: UpdatePerson only allows a limited set of fields to be
304         #    updated. Ideally we should have a more generic way of doing
305         #    this. I copied the field names from UpdatePerson.py...
306         update_fields = {}
307         all_fields = new_record
308         for key in all_fields.keys():
309             if key in ['first_name', 'last_name', 'title', 'email',
310                        'password', 'phone', 'url', 'bio', 'accepted_aup',
311                        'enabled']:
312                 update_fields[key] = all_fields[key]
313         api.plshell.UpdatePerson(api.plauth, pointer, update_fields)
314
315         if 'key' in new_record and new_record['key']:
316             # must check this key against the previous one if it exists
317             persons = api.plshell.GetPersons(api.plauth, [pointer], ['key_ids'])
318             person = persons[0]
319             keys = person['key_ids']
320             keys = api.plshell.GetKeys(api.plauth, person['key_ids'])
321             key_exists = False
322             if isinstance(new_record['key'], types.ListType):
323                 new_key = new_record['key'][0]
324             else:
325                 new_key = new_record['key']
326             
327             # Delete all stale keys
328             for key in keys:
329                 if new_record['key'] != key['key']:
330                     api.plshell.DeleteKey(api.plauth, key['key_id'])
331                 else:
332                     key_exists = True
333             if not key_exists:
334                 api.plshell.AddPersonKey(api.plauth, pointer, {'key_type': 'ssh', 'key': new_key})
335
336             # update the openssl key and gid
337             pkey = convert_public_key(new_key)
338             uuid = create_uuid()
339             gid_object = api.auth.hierarchy.create_gid(hrn, uuid, pkey)
340             gid = gid_object.save_to_string(save_parents=True)
341             record['gid'] = gid
342             record = SfaRecord(dict=record)
343             table.update(record)
344
345     elif type == "node":
346         api.plshell.UpdateNode(api.plauth, pointer, new_record)
347
348     else:
349         raise UnknownSfaType(type)
350
351     # update membership for researchers, pis, owners, operators
352     api.update_membership(record, new_record)
353     
354     return 1 
355
356 def remove(api, xrn, type, origin_hrn=None):
357     # convert xrn to hrn     
358     if type:
359         hrn = urn_to_hrn(xrn)[0]
360     else:
361         hrn, type = urn_to_hrn(xrn)    
362
363     table = SfaTable()
364     filter = {'hrn': hrn}
365     if type not in ['all', '*']:
366         filter['type'] = type
367     records = table.find(filter)
368     if not records:
369         raise RecordNotFound(hrn)
370     record = records[0]
371     type = record['type']
372
373     credential = api.getCredential()
374     registries = Registries(api)
375
376     # Try to remove the object from the PLCDB of federated agg.
377     # This is attempted before removing the object from the local agg's PLCDB and sfa table
378     if hrn.startswith(api.hrn) and type in ['user', 'slice', 'authority']:
379         for registry in registries:
380             if registry not in [api.hrn]:
381                 try:
382                     result=registries[registry].remove_peer_object(credential, record, origin_hrn)
383                 except:
384                     pass
385     if type == "user":
386         persons = api.plshell.GetPersons(api.plauth, record['pointer'])
387         # only delete this person if he has site ids. if he doesnt, it probably means
388         # he was just removed from a site, not actually deleted
389         if persons and persons[0]['site_ids']:
390             api.plshell.DeletePerson(api.plauth, record['pointer'])
391     elif type == "slice":
392         if api.plshell.GetSlices(api.plauth, record['pointer']):
393             api.plshell.DeleteSlice(api.plauth, record['pointer'])
394     elif type == "node":
395         if api.plshell.GetNodes(api.plauth, record['pointer']):
396             api.plshell.DeleteNode(api.plauth, record['pointer'])
397     elif type == "authority":
398         if api.plshell.GetSites(api.plauth, record['pointer']):
399             api.plshell.DeleteSite(api.plauth, record['pointer'])
400     else:
401         raise UnknownSfaType(type)
402
403     table.remove(record)
404
405     return 1
406
407 def remove_peer_object(api, record, origin_hrn=None):
408     pass
409
410 def register_peer_object(api, record, origin_hrn=None):
411     pass