5 from sfa.util.faults import *
6 from sfa.util.prefixTree import prefixTree
7 from sfa.util.record import SfaRecord
8 from sfa.senslab.table_slab import SfaTable
9 from sfa.util.record import SfaRecord
10 from sfa.trust.gid import GID
11 from sfa.util.xrn import Xrn, get_leaf, get_authority, hrn_to_urn, urn_to_hrn
12 from sfa.util.plxrn import hrn_to_pl_login_base
13 from sfa.trust.credential import Credential
14 from sfa.trust.certificate import Certificate, Keypair
15 from sfa.trust.gid import create_uuid
16 from sfa.util.version import version_core
17 from sfa.senslab.api import *
20 # The GENI GetVersion call
23 peers =dict ([ (peername,v._ServerProxy__host) for (peername,v) in api.registries.iteritems()
24 if peername != api.hrn])
26 return version_core({'interface':'registry',
31 def get_credential(api, xrn, type, is_self=False):
34 hrn = urn_to_hrn(xrn)[0]
36 hrn, type = urn_to_hrn(xrn)
38 # Is this a root or sub authority
39 auth_hrn = api.auth.get_authority(hrn)
40 print>> sys.stderr , " \r\n REGISTRY get_credential auth_hrn:" , auth_hrn,"hrn : ", hrn, " Type : ", type, "is self : " , is_self,"<<"
41 if not auth_hrn or hrn == api.config.SFA_INTERFACE_HRN:
44 auth_info = api.auth.get_auth_info(auth_hrn)
46 print >> sys.stderr , " findObject ", type, hrn
47 records = table.findObjects({'type': type, 'hrn': hrn})
48 print>> sys.stderr , " \r\n ++ REGISTRY get_credential hrn %s records %s " %(hrn, records)
50 raise RecordNotFound(hrn)
53 # verify_cancreate_credential requires that the member lists
54 # (researchers, pis, etc) be filled in
55 api.fill_record_info(record)
56 record['enabled'] = True
57 print>> sys.stderr , " \r\n ++ REGISTRY get_credential hrn %s record['enabled'] %s is_self %s" %(hrn, record['enabled'], is_self)
58 if record['type']=='user':
59 if not record['enabled']:
60 print>> sys.stderr , " \r\n ++ REGISTRY get_credential hrn %s ACCOUNT Not enabled"
61 raise AccountNotEnabled(": PlanetLab account %s is not enabled. Please contact your site PI" %(record['email']))
64 # if this is a self cred the record's gid is the caller's gid
67 caller_gid = record.get_gid_object()
68 print>>sys.stderr, " \r\n REGISTRY IS SELF OK caller_hrn %s--- \r\n caller_gid %s---------" %(caller_hrn,caller_gid)
70 print>> sys.stderr , " \r\n ++ ELSE "
71 caller_gid = api.auth.client_cred.get_gid_caller()
72 print>> sys.stderr , " \r\n ++ ELSE caller_gid %s record %s" %(caller_gid, record)
73 caller_hrn = caller_gid.get_hrn()
74 print>> sys.stderr , " \r\n ++ ELSE caller_hrn %s " %(caller_hrn)
76 object_hrn = record.get_gid_object().get_hrn()
77 print>> sys.stderr , " \r\n ++ ELSE object_hrn %s " %(object_hrn)
79 rights = api.auth.determine_user_rights(caller_hrn, record)
80 print>> sys.stderr , " \r\n ++ After rights record: %s \r\n ====RIGHTS %s " %(record , rights)
82 # make sure caller has rights to this object
84 raise PermissionError(caller_hrn + " has no rights to " + record['name'])
86 object_gid = GID(string=record['gid'])
87 new_cred = Credential(subject = object_gid.get_subject())
88 new_cred.set_gid_caller(caller_gid)
89 new_cred.set_gid_object(object_gid)
90 new_cred.set_issuer_keys(auth_info.get_privkey_filename(), auth_info.get_gid_filename())
91 #new_cred.set_pubkey(object_gid.get_pubkey())
92 new_cred.set_privileges(rights)
93 new_cred.get_privileges().delegate_all_privileges(True)
94 if 'expires' in record:
95 new_cred.set_expiration(int(record['expires']))
96 auth_kind = "authority,ma,sa"
97 # Parent not necessary, verify with certs
98 #new_cred.set_parent(api.auth.hierarchy.get_auth_cred(auth_hrn, kind=auth_kind))
102 return new_cred.save_to_string(save_parents=True)
105 def resolve(api, xrns, type=None, full=True):
107 # load all known registry names into a prefix tree and attempt to find
108 # the longest matching prefix
109 print >>sys.stderr , '\t\t REGISTRY MANAGER : resolve=========xrns ', xrns
110 if not isinstance(xrns, types.ListType):
112 type = Xrn(xrns).get_type()
114 hrns = [urn_to_hrn(xrn)[0] for xrn in xrns]
115 print >>sys.stderr , '\t\t =========hrns ', hrns
116 # create a dict where key is a registry hrn and its value is a
117 # hrns at that registry (determined by the known prefix tree).
119 print >>sys.stderr, '\r\n REGISTRY MANAGER : resolve xrns ' , xrns #api.__dict__.keys()
120 registries = api.registries
122 registry_hrns = registries.keys()
123 print >>sys.stderr, '\r\n \t\t REGISTRY MANAGER registry_hrns' , registry_hrns
124 tree.load(registry_hrns)
126 registry_hrn = tree.best_match(urn_to_hrn(xrn)[0])
127 print >>sys.stderr, '\t\tREGISTRY MANAGER *****tree.best_match ', registry_hrn
128 if registry_hrn not in xrn_dict:
129 xrn_dict[registry_hrn] = []
130 xrn_dict[registry_hrn].append(xrn)
131 print >>sys.stderr, '\t\tREGISTRY MANAGER *****xrn_dict[registry_hrn] ',xrn_dict[registry_hrn]
134 for registry_hrn in xrn_dict:
135 # skip the hrn without a registry hrn
136 # XX should we let the user know the authority is unknown?
137 print >>sys.stderr, '\t\t registry_hrn in xrn_dict ', registry_hrn
141 # if the best match (longest matching hrn) is not the local registry,
142 # forward the request
143 xrns = xrn_dict[registry_hrn]
144 if registry_hrn != api.hrn:
145 credential = api.getCredential()
146 peer_records = registries[registry_hrn].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])
154 # convert set to list
155 remaining_hrns = [hrn for hrn in remaining_hrns]
156 print >>sys.stderr, '\t\t remaining_hrns', remaining_hrns
158 local_records = table.findObjects({'hrn': remaining_hrns})
160 print >>sys.stderr, '\t\t LOCAL REC !', local_records
161 for rec in local_records:
162 print >>sys.stderr, '\t\t resolve regmanager : rec ', rec
165 print >>sys.stderr, '\r\n \r\n REGISTRY:_FULL', api
166 api.fill_record_info(local_records)
169 # convert local record objects to dicts
170 records.extend([dict(record) for record in local_records])
171 print >>sys.stderr, "\r\n \t\t records extends %s" %(records)
173 raise RecordNotFound(str(hrns))
176 records = filter(lambda rec: rec['type'] in [type], records)
180 def list(api, xrn, origin_hrn=None):
181 hrn, type = urn_to_hrn(xrn)
182 # load all know registry names into a prefix tree and attempt to find
183 # the longest matching prefix
185 registries = api.registries
186 registry_hrns = registries.keys()
188 tree.load(registry_hrns)
189 registry_hrn = tree.best_match(hrn)
191 #if there was no match then this record belongs to an unknow registry
193 raise MissingAuthority(xrn)
195 # if the best match (longest matching hrn) is not the local registry,
196 # forward the request
198 if registry_hrn != api.hrn:
199 credential = api.getCredential()
200 record_list = registries[registry_hrn].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 = str(record['hrn']).strip("['']")
217 #type_of_rec = str( record['type']).strip("['']")
219 type_of_rec =record['type']
221 urn = hrn_to_urn(hrn,type_of_rec)
224 if type_of_rec not in ['authority', 'slice', 'node', 'user']:
225 raise UnknownSfaType(type_of_rec)
227 # check if record already exists
229 existing_records = table.find({'type': type_of_rec, 'hrn': hrn})
231 raise ExistingRecord(hrn)
233 record = SfaRecord(dict = record)
235 print>>sys.stderr, " \r\n \r\n ----------- REGISTRY_MANAGER_SLAN.PY register SfaRecordrecord %s" %(record)
236 #record['authority'] = get_authority(record['hrn'])
237 record['authority'] = get_authority(hrn)
239 type_of_rec = record['type']
242 api.auth.verify_object_permission(hrn)
243 #myapi.auth.verify_object_permission( record['hrn'])
244 auth_info = api.auth.get_auth_info(record['authority'])
249 # make sure record has a gid
250 if 'gid' not in record:
252 pkey = Keypair(create=True)
253 if 'key' in record and record['key']:
254 if isinstance(record['key'], types.ListType):
255 pub_key = record['key'][0]
257 pub_key = record['key']
258 pkey = convert_public_key(pub_key)
260 gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey)
261 gid = gid_object.save_to_string(save_parents=True)
264 print>>sys.stderr, " \r\n \r\n ----------- REGISTRY_MANAGER_SLAB.PY record['gid'] %s" %(record['gid'])
265 print>>sys.stderr, " \r\n \r\n ----------- REGISTRY_MANAGER_SLAB.PY register type_of_rec %s"%(type_of_rec)
267 if type_of_rec in ["authority"]:
270 if not api.auth.hierarchy.auth_exists(hrn):
271 api.auth.hierarchy.create_auth(hrn_to_urn(hrn,'authority'))
273 # get the GID from the newly created authority
274 gid = auth_info.get_gid_object()
275 record.set_gid(gid.save_to_string(save_parents=True))
277 #pl_record = api.sfa_fields_to_pl_fields(type, hrn, record)
278 print>>sys.stderr, " \r\n \r\n ----------- REGISTRY_MANAGER_SLAB.PY register : type_of_rec in [authority ] sfa_fields_to_pl_fields FIELDS A CHANGER"
280 sites = api.oar.GetSites( [pl_record['login_base']])
282 pointer = api.oar.AddSite( pl_record)
284 pointer = sites[0]['site_id']
286 record.set_pointer(pointer)
287 record['pointer'] = pointer
289 elif (type_of_rec == "slice"):
290 acceptable_fields=['url', 'instantiation', 'name', 'description']
291 pl_record = api.sfa_fields_to_pl_fields(type_of_rec, hrn, record)
292 print>>sys.stderr, " \r\n \r\n ----------- REGISTRY_MANAGER_SLAB.PY register slice pl_record %s"%(pl_record)
293 for key in pl_record.keys():
294 if key not in acceptable_fields:
296 slices = api.users.GetSlices( [pl_record['name']])
298 pointer = api.users.AddSlice(pl_record)
300 pointer = slices[0]['slice_id']
301 record.set_pointer(pointer)
302 record['pointer'] = pointer
304 elif (type_of_rec == "user"):
305 persons = api.users.GetPersons( [record['email']])
307 print>>sys.stderr, " \r\n \r\n ----------- registry_manager_slab register NO PERSON ADD TO LDAP?"
310 #pointer = api.users.AddPerson( dict(record))
312 #pointer = persons[0]['person_id']
314 if 'enabled' in record and record['enabled']:
315 api.users.UpdatePerson( pointer, {'enabled': record['enabled']})
316 # add this persons to the site only if he is being added for the first
317 # time by sfa and doesont already exist in plc
318 if not persons or not persons[0]['site_ids']:
319 login_base = get_leaf(record['authority'])
320 api.users.AddPersonToSite( pointer, login_base)
322 # What roles should this user have?
323 api.users.AddRoleToPerson( 'user', pointer)
326 api.users.AddPersonKey( pointer, {'key_type' : 'ssh', 'key' : pub_key})
328 #elif (type == "node"):
329 #pl_record = api.sfa_fields_to_pl_fields(type, hrn, record)
330 #login_base = hrn_to_pl_login_base(record['authority'])
331 #nodes = api.oar.GetNodes( [pl_record['hostname']])
333 #pointer = api.oar.AddNode(login_base, pl_record)
335 #pointer = nodes[0]['node_id']
337 ##record['pointer'] = pointer
338 ##record.set_pointer(pointer)
339 #record_id = table.insert(record)
340 #record['record_id'] = record_id
342 # update membership for researchers, pis, owners, operators
343 api.update_membership(None, record)
345 return record.get_gid_object().save_to_string(save_parents=True)
347 def update(api, record_dict):
348 new_record = SfaRecord(dict = record_dict)
349 type = new_record['type']
350 hrn = new_record['hrn']
351 urn = hrn_to_urn(hrn,type)
352 api.auth.verify_object_permission(hrn)
354 # make sure the record exists
355 records = table.findObjects({'type': type, 'hrn': hrn})
357 raise RecordNotFound(hrn)
359 record['last_updated'] = time.gmtime()
361 # Update_membership needs the membership lists in the existing record
362 # filled in, so it can see if members were added or removed
363 api.fill_record_info(record)
365 # Use the pointer from the existing record, not the one that the user
366 # gave us. This prevents the user from inserting a forged pointer
367 pointer = record['pointer']
368 # update the PLC information that was specified with the record
370 if (type == "authority"):
371 api.oar.UpdateSite( pointer, new_record)
373 elif type == "slice":
374 pl_record=api.sfa_fields_to_pl_fields(type, hrn, new_record)
375 if 'name' in pl_record:
376 pl_record.pop('name')
377 api.users.UpdateSlice( pointer, pl_record)
380 # SMBAKER: UpdatePerson only allows a limited set of fields to be
381 # updated. Ideally we should have a more generic way of doing
382 # this. I copied the field names from UpdatePerson.py...
384 all_fields = new_record
385 for key in all_fields.keys():
386 if key in ['first_name', 'last_name', 'title', 'email',
387 'password', 'phone', 'url', 'bio', 'accepted_aup',
389 update_fields[key] = all_fields[key]
390 api.users.UpdatePerson( pointer, update_fields)
392 if 'key' in new_record and new_record['key']:
393 # must check this key against the previous one if it exists
394 persons = api.users.GetPersons( [pointer], ['key_ids'])
396 keys = person['key_ids']
397 keys = api.users.GetKeys( person['key_ids'])
399 if isinstance(new_record['key'], types.ListType):
400 new_key = new_record['key'][0]
402 new_key = new_record['key']
404 # Delete all stale keys
406 if new_record['key'] != key['key']:
407 api.users.DeleteKey( key['key_id'])
411 api.users.AddPersonKey( pointer, {'key_type': 'ssh', 'key': new_key})
413 # update the openssl key and gid
414 pkey = convert_public_key(new_key)
416 gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey)
417 gid = gid_object.save_to_string(save_parents=True)
419 record = SfaRecord(dict=record)
423 api.oar.UpdateNode( pointer, new_record)
426 raise UnknownSfaType(type)
428 # update membership for researchers, pis, owners, operators
429 api.update_membership(record, new_record)
433 # expecting an Xrn instance
434 def remove(api, xrn, origin_hrn=None):
437 filter = {'hrn': xrn.get_hrn()}
440 if type and type not in ['all', '*']:
441 filter['type'] = type
443 records = table.find(filter)
444 if not records: raise RecordNotFound(hrn)
446 type = record['type']
448 credential = api.getCredential()
449 registries = api.registries
451 # Try to remove the object from the PLCDB of federated agg.
452 # This is attempted before removing the object from the local agg's PLCDB and sfa table
453 if hrn.startswith(api.hrn) and type in ['user', 'slice', 'authority']:
454 for registry in registries:
455 if registry not in [api.hrn]:
457 result=registries[registry].remove_peer_object(credential, record, origin_hrn)
461 persons = api.users.GetPersons(record['pointer'])
462 # only delete this person if he has site ids. if he doesnt, it probably means
463 # he was just removed from a site, not actually deleted
464 if persons and persons[0]['site_ids']:
465 api.users.DeletePerson(record['pointer'])
466 elif type == "slice":
467 if api.users.GetSlices( record['pointer']):
468 api.users.DeleteSlice( record['pointer'])
470 if api.oar.GetNodes( record['pointer']):
471 api.oar.DeleteNode( record['pointer'])
472 elif type == "authority":
473 if api.oar.GetSites( record['pointer']):
474 api.oar.DeleteSite( record['pointer'])
476 raise UnknownSfaType(type)
482 def remove_peer_object(api, record, origin_hrn=None):
485 def register_peer_object(api, record, origin_hrn=None):