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