d3c1a95e506fa2566754e63f02bbe98fb61d731b
[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     # XX Preload this into the api module
80     registries = Registries(api)
81     tree = prefixTree()
82     registry_hrns = registries.keys()
83     tree.load(registry_hrns)
84     for xrn in xrns:
85         registry_hrn = tree.best_match(urn_to_hrn(xrn)[0])
86         if registry_hrn not in xrn_dict:
87             xrn_dict[registry_hrn] = []
88         xrn_dict[registry_hrn].append(xrn)
89         
90     records = [] 
91     for registry_hrn in xrn_dict:
92         # skip the hrn without a registry hrn
93         # XX should we let the user know the authority is unknown?       
94         if not registry_hrn:
95             continue
96
97         # if the best match (longest matching hrn) is not the local registry,
98         # forward the request
99         xrns = xrn_dict[registry_hrn]
100         if registry_hrn != api.hrn:
101             credential = api.getCredential()
102             peer_records = registries[registry_hrn].resolve(credential, xrns, origin_hrn)
103             records.extend([SfaRecord(dict=record).as_dict() for record in peer_records])
104
105     # try resolving the remaining unfound records at the local registry
106     remaining_hrns = set(hrns).difference([record['hrn'] for record in records])
107     # convert set to list
108     remaining_hrns = [hrn for hrn in remaining_hrns] 
109     table = SfaTable()
110     local_records = table.findObjects({'hrn': remaining_hrns})
111     api.fill_record_info(local_records)
112     records.extend(local_records)
113     if not records:
114         raise RecordNotFound(str(hrns))
115
116     if type:
117         records = filter(lambda rec: rec['type'] in [type], records)
118
119     return records
120
121 def list(api, xrn, origin_hrn=None):
122     hrn, type = urn_to_hrn(xrn)
123     # load all know registry names into a prefix tree and attempt to find
124     # the longest matching prefix
125     records = []
126     registries = Registries(api)
127     registry_hrns = registries.keys()
128     tree = prefixTree()
129     tree.load(registry_hrns)
130     registry_hrn = tree.best_match(hrn)
131     
132     #if there was no match then this record belongs to an unknow registry
133     if not registry_hrn:
134         raise MissingAuthority(xrn)
135     
136     # if the best match (longest matching hrn) is not the local registry,
137     # forward the request
138     records = []    
139     if registry_hrn != api.hrn:
140         credential = api.getCredential()
141         record_list = registries[registry_hrn].list(credential, xrn, origin_hrn)
142         records = [SfaRecord(dict=record).as_dict() for record in record_list]
143     
144     # if we still havnt found the record yet, try the local registry
145     if not records:
146         if not api.auth.hierarchy.auth_exists(hrn):
147             raise MissingAuthority(hrn)
148
149         table = SfaTable()
150         records = table.find({'authority': hrn})
151
152     return records
153
154
155 def register(api, record):
156
157     hrn, type = record['hrn'], record['type']
158
159     # validate the type
160     if type not in ['authority', 'slice', 'node', 'user']:
161         raise UnknownSfaType(type) 
162     
163     # check if record already exists
164     table = SfaTable()
165     existing_records = table.find({'type': type, 'hrn': hrn})
166     if existing_records:
167         raise ExistingRecord(hrn)
168        
169     record = SfaRecord(dict = record)
170     record['authority'] = get_authority(record['hrn'])
171     type = record['type']
172     hrn = record['hrn']
173     api.auth.verify_object_permission(hrn)
174     auth_info = api.auth.get_auth_info(record['authority'])
175     pub_key = None
176     # make sure record has a gid
177     if 'gid' not in record:
178         uuid = create_uuid()
179         pkey = Keypair(create=True)
180         if 'key' in record and record['key']:
181             if isinstance(record['key'], types.ListType):
182                 pub_key = record['key'][0]
183             else:
184                 pub_key = record['key']
185             pkey = convert_public_key(pub_key)
186
187         gid_object = api.auth.hierarchy.create_gid(hrn, uuid, pkey)
188         gid = gid_object.save_to_string(save_parents=True)
189         record['gid'] = gid
190         record.set_gid(gid)
191
192     if type in ["authority"]:
193         # update the tree
194         if not api.auth.hierarchy.auth_exists(hrn):
195             api.auth.hierarchy.create_auth(hrn)
196
197         # get the GID from the newly created authority
198         gid = auth_info.get_gid_object()
199         record.set_gid(gid.save_to_string(save_parents=True))
200         pl_record = api.sfa_fields_to_pl_fields(type, hrn, record)
201         sites = api.plshell.GetSites(api.plauth, [pl_record['login_base']])
202         if not sites:
203             pointer = api.plshell.AddSite(api.plauth, pl_record)
204         else:
205             pointer = sites[0]['site_id']
206
207         record.set_pointer(pointer)
208         record['pointer'] = pointer
209
210     elif (type == "slice"):
211         acceptable_fields=['url', 'instantiation', 'name', 'description']
212         pl_record = api.sfa_fields_to_pl_fields(type, hrn, record)
213         for key in pl_record.keys():
214             if key not in acceptable_fields:
215                 pl_record.pop(key)
216         slices = api.plshell.GetSlices(api.plauth, [pl_record['name']])
217         if not slices:
218              pointer = api.plshell.AddSlice(api.plauth, pl_record)
219         else:
220              pointer = slices[0]['slice_id']
221         record.set_pointer(pointer)
222         record['pointer'] = pointer
223
224     elif  (type == "user"):
225         persons = api.plshell.GetPersons(api.plauth, [record['email']])
226         if not persons:
227             pointer = api.plshell.AddPerson(api.plauth, dict(record))
228         else:
229             pointer = persons[0]['person_id']
230
231         if 'enabled' in record and record['enabled']:
232             api.plshell.UpdatePerson(api.plauth, pointer, {'enabled': record['enabled']})
233         # add this persons to the site only if he is being added for the first
234         # time by sfa and doesont already exist in plc
235         if not persons or not persons[0]['site_ids']:
236             login_base = get_leaf(record['authority'])
237             api.plshell.AddPersonToSite(api.plauth, pointer, login_base)
238
239         # What roles should this user have?
240         api.plshell.AddRoleToPerson(api.plauth, 'user', pointer)
241         # Add the user's key
242         if pub_key:
243             api.plshell.AddPersonKey(api.plauth, pointer, {'key_type' : 'ssh', 'key' : pub_key})
244
245     elif (type == "node"):
246         pl_record = api.sfa_fields_to_pl_fields(type, hrn, record)
247         login_base = hrn_to_pl_login_base(record['authority'])
248         nodes = api.plshell.GetNodes(api.plauth, [pl_record['hostname']])
249         if not nodes:
250             pointer = api.plshell.AddNode(api.plauth, login_base, pl_record)
251         else:
252             pointer = nodes[0]['node_id']
253
254     record['pointer'] = pointer
255     record.set_pointer(pointer)
256     record_id = table.insert(record)
257     record['record_id'] = record_id
258
259     # update membership for researchers, pis, owners, operators
260     api.update_membership(None, record)
261
262     return record.get_gid_object().save_to_string(save_parents=True)
263
264 def update(api, record_dict):
265     new_record = SfaRecord(dict = record_dict)
266     type = new_record['type']
267     hrn = new_record['hrn']
268     api.auth.verify_object_permission(hrn)
269     table = SfaTable()
270     # make sure the record exists
271     records = table.findObjects({'type': type, 'hrn': hrn})
272     if not records:
273         raise RecordNotFound(hrn)
274     record = records[0]
275     record['last_updated'] = time.gmtime()
276
277     # Update_membership needs the membership lists in the existing record
278     # filled in, so it can see if members were added or removed
279     api.fill_record_info(record)
280
281     # Use the pointer from the existing record, not the one that the user
282     # gave us. This prevents the user from inserting a forged pointer
283     pointer = record['pointer']
284     # update the PLC information that was specified with the record
285
286     if (type == "authority"):
287         api.plshell.UpdateSite(api.plauth, pointer, new_record)
288
289     elif type == "slice":
290         pl_record=api.sfa_fields_to_pl_fields(type, hrn, new_record)
291         if 'name' in pl_record:
292             pl_record.pop('name')
293             api.plshell.UpdateSlice(api.plauth, pointer, pl_record)
294
295     elif type == "user":
296         # SMBAKER: UpdatePerson only allows a limited set of fields to be
297         #    updated. Ideally we should have a more generic way of doing
298         #    this. I copied the field names from UpdatePerson.py...
299         update_fields = {}
300         all_fields = new_record
301         for key in all_fields.keys():
302             if key in ['first_name', 'last_name', 'title', 'email',
303                        'password', 'phone', 'url', 'bio', 'accepted_aup',
304                        'enabled']:
305                 update_fields[key] = all_fields[key]
306         api.plshell.UpdatePerson(api.plauth, pointer, update_fields)
307
308         if 'key' in new_record and new_record['key']:
309             # must check this key against the previous one if it exists
310             persons = api.plshell.GetPersons(api.plauth, [pointer], ['key_ids'])
311             person = persons[0]
312             keys = person['key_ids']
313             keys = api.plshell.GetKeys(api.plauth, person['key_ids'])
314             key_exists = False
315             if isinstance(new_record['key'], types.ListType):
316                 new_key = new_record['key'][0]
317             else:
318                 new_key = new_record['key']
319             
320             # Delete all stale keys
321             for key in keys:
322                 if new_record['key'] != key['key']:
323                     api.plshell.DeleteKey(api.plauth, key['key_id'])
324                 else:
325                     key_exists = True
326             if not key_exists:
327                 api.plshell.AddPersonKey(api.plauth, pointer, {'key_type': 'ssh', 'key': new_key})
328
329             # update the openssl key and gid
330             pkey = convert_public_key(new_key)
331             uuid = create_uuid()
332             gid_object = api.auth.hierarchy.create_gid(hrn, uuid, pkey)
333             gid = gid_object.save_to_string(save_parents=True)
334             record['gid'] = gid
335             record = SfaRecord(dict=record)
336             table.update(record)
337
338     elif type == "node":
339         api.plshell.UpdateNode(api.plauth, pointer, new_record)
340
341     else:
342         raise UnknownSfaType(type)
343
344     # update membership for researchers, pis, owners, operators
345     api.update_membership(record, new_record)
346     
347     return 1 
348
349 def remove(api, xrn, type, origin_hrn=None):
350     # convert xrn to hrn     
351     if type:
352         hrn = urn_to_hrn(xrn)[0]
353     else:
354         hrn, type = urn_to_hrn(xrn)    
355
356     table = SfaTable()
357     filter = {'hrn': hrn}
358     if type not in ['all', '*']:
359         filter['type'] = type
360     records = table.find(filter)
361     if not records:
362         raise RecordNotFound(hrn)
363     record = records[0]
364     type = record['type']
365
366     credential = api.getCredential()
367     registries = Registries(api)
368
369     # Try to remove the object from the PLCDB of federated agg.
370     # This is attempted before removing the object from the local agg's PLCDB and sfa table
371     if hrn.startswith(api.hrn) and type in ['user', 'slice', 'authority']:
372         for registry in registries:
373             if registry not in [api.hrn]:
374                 try:
375                     result=registries[registry].remove_peer_object(credential, record, origin_hrn)
376                 except:
377                     pass
378     if type == "user":
379         persons = api.plshell.GetPersons(api.plauth, record['pointer'])
380         # only delete this person if he has site ids. if he doesnt, it probably means
381         # he was just removed from a site, not actually deleted
382         if persons and persons[0]['site_ids']:
383             api.plshell.DeletePerson(api.plauth, record['pointer'])
384     elif type == "slice":
385         if api.plshell.GetSlices(api.plauth, record['pointer']):
386             api.plshell.DeleteSlice(api.plauth, record['pointer'])
387     elif type == "node":
388         if api.plshell.GetNodes(api.plauth, record['pointer']):
389             api.plshell.DeleteNode(api.plauth, record['pointer'])
390     elif type == "authority":
391         if api.plshell.GetSites(api.plauth, record['pointer']):
392             api.plshell.DeleteSite(api.plauth, record['pointer'])
393     else:
394         raise UnknownSfaType(type)
395
396     table.remove(record)
397
398     return 1
399
400 def remove_peer_object(api, record, origin_hrn=None):
401     pass
402
403 def register_peer_object(api, record, origin_hrn=None):
404     pass