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