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