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