5 from sfa.util.faults import RecordNotFound, AccountNotEnabled, PermissionError, MissingAuthority, \
6 UnknownSfaType, ExistingRecord
7 from sfa.util.prefixTree import prefixTree
8 from sfa.util.record import SfaRecord
9 from sfa.senslab.table_slab import SfaTable
10 from sfa.util.xrn import Xrn, get_leaf, get_authority, hrn_to_urn, urn_to_hrn
11 from sfa.util.version import version_core
13 from sfa.trust.gid import GID
14 from sfa.trust.credential import Credential
15 from sfa.trust.certificate import Certificate, Keypair, convert_public_key
16 from sfa.trust.gid import create_uuid
18 # The GENI GetVersion call
20 # Bugfix TP 09/11/2011
21 #peers =dict ([ (peername,v._ServerProxy__host) for (peername,v) in api.registries.iteritems()
22 peers =dict ([ (peername,v.get_url()) for (peername,v) in api.registries.iteritems()
23 if peername != api.hrn])
25 return version_core({'interface':'registry',
30 def get_credential(api, xrn, type, is_self=False):
33 hrn = urn_to_hrn(xrn)[0]
35 hrn, type = urn_to_hrn(xrn)
37 # Is this a root or sub authority
38 auth_hrn = api.auth.get_authority(hrn)
39 print>> sys.stderr , " \r\n REGISTRY get_credential auth_hrn:" , auth_hrn,"hrn : ", hrn, " Type : ", type, "is self : " , is_self,"<<"
40 if not auth_hrn or hrn == api.config.SFA_INTERFACE_HRN:
43 auth_info = api.auth.get_auth_info(auth_hrn)
45 print >> sys.stderr , " findObject ", type, hrn
46 records = table.findObjects({'type': type, 'hrn': hrn})
47 print>> sys.stderr , " \r\n ++ REGISTRY get_credential hrn %s records %s " %(hrn, records)
49 raise RecordNotFound(hrn)
52 # verify_cancreate_credential requires that the member lists
53 # (researchers, pis, etc) be filled in
54 api.driver.fill_record_info(record, api.aggregates)
55 record['enabled'] = True
56 print>> sys.stderr , " \r\n ++ REGISTRY get_credential hrn %s record['enabled'] %s is_self %s" %(hrn, record['enabled'], is_self)
57 if record['type']=='user':
58 if not record['enabled']:
59 print>> sys.stderr , " \r\n ++ REGISTRY get_credential hrn %s ACCOUNT Not enabled"
60 raise AccountNotEnabled(": PlanetLab account %s is not enabled. Please contact your site PI" %(record['email']))
63 # if this is a self cred the record's gid is the caller's gid
66 caller_gid = record.get_gid_object()
67 print>>sys.stderr, " \r\n REGISTRY IS SELF OK caller_hrn %s--- \r\n caller_gid %s---------" %(caller_hrn,caller_gid)
69 print>> sys.stderr , " \r\n ++ ELSE "
70 caller_gid = api.auth.client_cred.get_gid_caller()
71 print>> sys.stderr , " \r\n ++ ELSE caller_gid %s record %s" %(caller_gid, record)
72 caller_hrn = caller_gid.get_hrn()
73 print>> sys.stderr , " \r\n ++ ELSE caller_hrn %s " %(caller_hrn)
75 object_hrn = record.get_gid_object().get_hrn()
76 print>> sys.stderr , " \r\n ++ ELSE object_hrn %s " %(object_hrn)
78 rights = api.auth.determine_user_rights(caller_hrn, record)
79 print>> sys.stderr , " \r\n ++ After rights record: %s \r\n ====RIGHTS %s " %(record , rights)
81 # make sure caller has rights to this object
83 raise PermissionError(caller_hrn + " has no rights to " + record['name'])
85 object_gid = GID(string=record['gid'])
86 new_cred = Credential(subject = object_gid.get_subject())
87 new_cred.set_gid_caller(caller_gid)
88 new_cred.set_gid_object(object_gid)
89 new_cred.set_issuer_keys(auth_info.get_privkey_filename(), auth_info.get_gid_filename())
90 #new_cred.set_pubkey(object_gid.get_pubkey())
91 new_cred.set_privileges(rights)
92 new_cred.get_privileges().delegate_all_privileges(True)
93 if 'expires' in record:
94 new_cred.set_expiration(int(record['expires']))
95 auth_kind = "authority,ma,sa"
96 # Parent not necessary, verify with certs
97 #new_cred.set_parent(api.auth.hierarchy.get_auth_cred(auth_hrn, kind=auth_kind))
101 return new_cred.save_to_string(save_parents=True)
104 def resolve(api, xrns, type=None, full=True):
106 # load all known registry names into a prefix tree and attempt to find
107 # the longest matching prefix
108 print >>sys.stderr , '\t\t REGISTRY MANAGER : resolve=========xrns ', xrns
109 if not isinstance(xrns, types.ListType):
111 type = Xrn(xrns).get_type()
113 hrns = [urn_to_hrn(xrn)[0] for xrn in xrns]
114 print >>sys.stderr , '\t\t =========hrns ', hrns
115 # create a dict where key is a registry hrn and its value is a
116 # hrns at that registry (determined by the known prefix tree).
118 print >>sys.stderr, '\r\n REGISTRY MANAGER : resolve xrns ' , xrns #api.__dict__.keys()
119 registries = api.registries
121 registry_hrns = registries.keys()
122 print >>sys.stderr, '\r\n \t\t REGISTRY MANAGER registry_hrns' , registry_hrns
123 tree.load(registry_hrns)
125 registry_hrn = tree.best_match(urn_to_hrn(xrn)[0])
126 print >>sys.stderr, '\t\tREGISTRY MANAGER *****tree.best_match ', registry_hrn
127 if registry_hrn not in xrn_dict:
128 xrn_dict[registry_hrn] = []
129 xrn_dict[registry_hrn].append(xrn)
130 print >>sys.stderr, '\t\tREGISTRY MANAGER *****xrn_dict[registry_hrn] ',xrn_dict[registry_hrn]
132 for registry_hrn in xrn_dict:
133 # skip the hrn without a registry hrn
134 # XX should we let the user know the authority is unknown?
135 print >>sys.stderr, '\t\t registry_hrn in xrn_dict ', registry_hrn
139 # if the best match (longest matching hrn) is not the local registry,
140 # forward the request
141 xrns = xrn_dict[registry_hrn]
142 if registry_hrn != api.hrn:
143 credential = api.getCredential()
144 interface = api.registries[registry_hrn]
145 server = api.server_proxy(interface, credential)
146 peer_records = server.Resolve(xrns, credential)
147 print >>sys.stderr , '\t\t peer_records ', peer_records
148 records.extend([SfaRecord(dict=record).as_dict() for record in peer_records])
150 print >>sys.stderr,'\t\t hrns ' , hrns
151 # try resolving the remaining unfound records at the local registry
152 remaining_hrns = set(hrns).difference([record['hrn'] for record in records])
153 # convert set to list
154 remaining_hrns = [hrn for hrn in remaining_hrns]
155 print >>sys.stderr, '\t\t remaining_hrns', remaining_hrns
157 local_records = table.findObjects({'hrn': remaining_hrns})
159 print >>sys.stderr, '\t\t LOCAL REC !', local_records
160 for rec in local_records:
161 print >>sys.stderr, '\t\t resolve regmanager : rec ', rec
164 print >>sys.stderr, '\r\n \r\n REGISTRY:_FULL', api
165 api.driver.fill_record_info(local_records)
167 # convert local record objects to dicts
168 records.extend([dict(record) for record in local_records])
169 print >>sys.stderr, "\r\n \t\t records extends %s" %(records)
171 raise RecordNotFound(str(hrns))
174 records = filter(lambda rec: rec['type'] in [type], records)
178 def list(api, xrn, origin_hrn=None):
179 hrn, type = urn_to_hrn(xrn)
180 # load all know registry names into a prefix tree and attempt to find
181 # the longest matching prefix
183 registries = api.registries
184 registry_hrns = registries.keys()
186 tree.load(registry_hrns)
187 registry_hrn = tree.best_match(hrn)
189 #if there was no match then this record belongs to an unknow registry
191 raise MissingAuthority(xrn)
192 # if the best match (longest matching hrn) is not the local registry,
193 # forward the request
195 if registry_hrn != api.hrn:
196 credential = api.getCredential()
197 print>>sys.stderr, "Registries : ", registries
198 interface = api.registries[registry_hrn]
199 server = api.server_proxy(interface, credential)
200 record_list = server.List(xrn, credential)
201 records = [SfaRecord(dict=record).as_dict() for record in record_list]
203 # if we still have not found the record yet, try the local registry
205 if not api.auth.hierarchy.auth_exists(hrn):
206 raise MissingAuthority(hrn)
209 records = table.find({'authority': hrn})
214 def register(api, record):
216 #hrn, type = record['hrn'], record['type']
217 hrn = str(record['hrn']).strip("['']")
218 type = str( record['type']).strip("['']")
219 urn = hrn_to_urn(hrn,type)
221 if type not in ['authority', 'slice', 'node', 'user']:
222 raise UnknownSfaType(type)
224 # check if record already exists
226 existing_records = table.find({'type': type, 'hrn': hrn})
228 raise ExistingRecord(hrn)
230 record = SfaRecord(dict = record)
232 print>>sys.stderr, " \r\n \r\n ----------- REGISTRY_MANAGER_SLAN.PY register SfaRecordrecord %s" %(record)
233 #record['authority'] = get_authority(record['hrn'])
234 record['authority'] = get_authority(hrn)
236 #type_of_rec = record['type']
239 #api.auth.verify_object_permission(hrn)
240 api.auth.verify_object_permission( record['hrn'])
241 auth_info = api.auth.get_auth_info(record['authority'])
243 # make sure record has a gid
244 if 'gid' not in record:
246 pkey = Keypair(create=True)
247 if 'key' in record and record['key']:
248 if isinstance(record['key'], types.ListType):
249 pub_key = record['key'][0]
251 pub_key = record['key']
252 pkey = convert_public_key(pub_key)
254 gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey)
255 gid = gid_object.save_to_string(save_parents=True)
258 print>>sys.stderr, " \r\n \r\n ----------- REGISTRY_MANAGER_SLAB.PY record['gid'] %s" %(record['gid'])
259 print>>sys.stderr, " \r\n \r\n ----------- REGISTRY_MANAGER_SLAB.PY register type %s"%(type)
261 if type in ["authority"]:
263 if not api.auth.hierarchy.auth_exists(hrn):
264 api.auth.hierarchy.create_auth(hrn_to_urn(hrn,'authority'))
266 # get the GID from the newly created authority
267 gid = auth_info.get_gid_object()
268 record.set_gid(gid.save_to_string(save_parents=True))
270 #pl_record = api.driver.sfa_fields_to_pl_fields(type, hrn, record)
271 print>>sys.stderr, " \r\n \r\n ----------- REGISTRY_MANAGER_SLAB.PY register : type in [authority ] sfa_fields_to_pl_fields FIELDS A CHANGER"
273 # thierry: ideally we'd like to be able to write api.driver.GetSites
274 # in which case the code would become mostly the same as for pl
275 sites = api.driver.GetSites([pl_record['login_base']])
278 # Error (E0601, register): Using variable 'pl_record' before assignment
279 pointer = api.driver.AddSite( pl_record)
281 pointer = sites[0]['site_id']
283 record.set_pointer(pointer)
284 record['pointer'] = pointer
286 elif (type == "slice"):
287 acceptable_fields=['url', 'instantiation', 'name', 'description']
288 pl_record = api.driver.sfa_fields_to_pl_fields(type, hrn, record)
289 print>>sys.stderr, " \r\n \r\n ----------- REGISTRY_MANAGER_SLAB.PY register slice pl_record %s"%(pl_record)
290 for key in pl_record.keys():
291 if key not in acceptable_fields:
293 slices = api.driver.GetSlices([pl_record['name']])
295 pointer = api.driver.AddSlice(pl_record)
297 pointer = slices[0]['slice_id']
298 record.set_pointer(pointer)
299 record['pointer'] = pointer
301 elif (type == "user"):
302 persons = api.driver.GetPersons([record['email']])
304 print>>sys.stderr, " \r\n \r\n ----------- registry_manager_slab register NO PERSON ADD TO LDAP?"
307 #pointer = api.driver.AddPerson( dict(record))
309 #pointer = persons[0]['person_id']
311 if 'enabled' in record and record['enabled']:
312 api.driver.UpdatePerson(pointer, {'enabled': record['enabled']})
313 # add this persons to the site only if he is being added for the first
314 # time by sfa and doesont already exist in plc
315 if not persons or not persons[0]['site_ids']:
316 login_base = get_leaf(record['authority'])
317 api.driver.AddPersonToSite(pointer, login_base)
319 # What roles should this user have?
320 api.driver.AddRoleToPerson('user', pointer)
323 api.driver.AddPersonKey(pointer, {'key_type' : 'ssh', 'key' : pub_key})
325 #elif (type == "node"):
326 #pl_record = api.driver.sfa_fields_to_pl_fields(type, hrn, record)
327 #login_base = hrn_to_pl_login_base(record['authority'])
328 #nodes = api.driver.GetNodes([pl_record['hostname']])
330 #pointer = api.driver.AddNode(login_base, pl_record)
332 #pointer = nodes[0]['node_id']
334 ##record['pointer'] = pointer
335 ##record.set_pointer(pointer)
336 #record_id = table.insert(record)
337 #record['record_id'] = record_id
339 # update membership for researchers, pis, owners, operators
340 api.driver.update_membership(None, record)
342 return record.get_gid_object().save_to_string(save_parents=True)
344 def update(api, record_dict):
345 new_record = SfaRecord(dict = record_dict)
346 type = new_record['type']
347 hrn = new_record['hrn']
348 urn = hrn_to_urn(hrn,type)
349 api.auth.verify_object_permission(hrn)
351 # make sure the record exists
352 records = table.findObjects({'type': type, 'hrn': hrn})
354 raise RecordNotFound(hrn)
356 record['last_updated'] = time.gmtime()
358 # Update_membership needs the membership lists in the existing record
359 # filled in, so it can see if members were added or removed
360 api.driver.fill_record_info(record)
362 # Use the pointer from the existing record, not the one that the user
363 # gave us. This prevents the user from inserting a forged pointer
364 pointer = record['pointer']
365 # update the PLC information that was specified with the record
367 if (type == "authority"):
368 api.driver.UpdateSite(pointer, new_record)
370 elif type == "slice":
371 pl_record=api.driver.sfa_fields_to_pl_fields(type, hrn, new_record)
372 if 'name' in pl_record:
373 pl_record.pop('name')
374 api.driver.UpdateSlice(pointer, pl_record)
377 # SMBAKER: UpdatePerson only allows a limited set of fields to be
378 # updated. Ideally we should have a more generic way of doing
379 # this. I copied the field names from UpdatePerson.py...
381 all_fields = new_record
382 for key in all_fields.keys():
383 if key in ['first_name', 'last_name', 'title', 'email',
384 'password', 'phone', 'url', 'bio', 'accepted_aup',
386 update_fields[key] = all_fields[key]
387 api.driver.UpdatePerson(pointer, update_fields)
389 if 'key' in new_record and new_record['key']:
390 # must check this key against the previous one if it exists
391 persons = api.driver.GetPersons([pointer], ['key_ids'])
393 keys = person['key_ids']
394 keys = api.driver.GetKeys(person['key_ids'])
396 if isinstance(new_record['key'], types.ListType):
397 new_key = new_record['key'][0]
399 new_key = new_record['key']
401 # Delete all stale keys
403 if new_record['key'] != key['key']:
404 api.driver.DeleteKey(key['key_id'])
408 api.driver.AddPersonKey(pointer, {'key_type': 'ssh', 'key': new_key})
410 # update the openssl key and gid
411 pkey = convert_public_key(new_key)
413 gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey)
414 gid = gid_object.save_to_string(save_parents=True)
416 record = SfaRecord(dict=record)
420 api.driver.UpdateNode(pointer, new_record)
423 raise UnknownSfaType(type)
425 # update membership for researchers, pis, owners, operators
426 api.driver.update_membership(record, new_record)
430 # expecting an Xrn instance
431 def remove(api, xrn, origin_hrn=None):
434 filter = {'hrn': xrn.get_hrn()}
437 if type and type not in ['all', '*']:
438 filter['type'] = type
440 records = table.find(filter)
441 if not records: raise RecordNotFound(hrn)
443 type = record['type']
445 credential = api.getCredential()
446 registries = api.registries
448 # Try to remove the object from the PLCDB of federated agg.
449 # This is attempted before removing the object from the local agg's PLCDB and sfa table
450 if hrn.startswith(api.hrn) and type in ['user', 'slice', 'authority']:
451 for registry in registries:
452 if registry not in [api.hrn]:
454 result=registries[registry].remove_peer_object(credential, record, origin_hrn)
458 persons = api.driver.GetPersons(record['pointer'])
459 # only delete this person if he has site ids. if he doesnt, it probably means
460 # he was just removed from a site, not actually deleted
461 if persons and persons[0]['site_ids']:
462 api.driver.DeletePerson(record['pointer'])
463 elif type == "slice":
464 if api.driver.GetSlices(record['pointer']):
465 api.driver.DeleteSlice(record['pointer'])
467 if api.driver.GetNodes(record['pointer']):
468 api.driver.DeleteNode(record['pointer'])
469 elif type == "authority":
470 if api.driver.GetSites(record['pointer']):
471 api.driver.DeleteSite(record['pointer'])
473 raise UnknownSfaType(type)
479 def remove_peer_object(api, record, origin_hrn=None):
482 def register_peer_object(api, record, origin_hrn=None):