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