5 from sfa.util.faults import RecordNotFound, AccountNotEnabled, PermissionError, MissingAuthority, \
6 UnknownSfaType, ExistingRecord
7 from sfa.util.prefixTree import prefixTree
8 from sfa.storage.record import SfaRecord
9 from sfa.storage.table 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
19 # The GENI GetVersion call
22 # Bugfix TP 09/11/2011
23 #peers =dict ([ (peername,v._ServerProxy__host) for (peername,v) in api.registries.iteritems()
24 peers =dict ([ (peername,v.get_url()) for (peername,v) in api.registries.iteritems()
25 if peername != api.hrn])
27 return version_core({'interface':'registry',
32 def GetCredential(api, xrn, type, is_self=False):
35 hrn = urn_to_hrn(xrn)[0]
37 hrn, type = urn_to_hrn(xrn)
39 # Is this a root or sub authority
40 auth_hrn = api.auth.get_authority(hrn)
41 print>> sys.stderr , " \r\n REGISTRY get_credential auth_hrn:" , auth_hrn,"hrn : ", hrn, " Type : ", type, "is self : " , is_self,"<<"
42 if not auth_hrn or hrn == api.config.SFA_INTERFACE_HRN:
45 auth_info = api.auth.get_auth_info(auth_hrn)
47 print >> sys.stderr , " findObject ", type, hrn
48 records = table.findObjects({'type': type, 'hrn': hrn})
49 print>> sys.stderr , " \r\n ++ REGISTRY get_credential hrn %s records %s " %(hrn, records)
51 raise RecordNotFound(hrn)
54 # verify_cancreate_credential requires that the member lists
55 # (researchers, pis, etc) be filled in
56 #api.driver.fill_record_info(record, api.aggregates)
57 api.driver.fill_record_info(record)
58 record['enabled'] = True
59 print>> sys.stderr , " \r\n ++ REGISTRY get_credential hrn %s record['enabled'] %s is_self %s" %(hrn, record['enabled'], is_self)
60 if record['type']=='user':
61 if not record['enabled']:
62 print>> sys.stderr , " \r\n ++ REGISTRY get_credential hrn %s ACCOUNT Not enabled"
63 raise AccountNotEnabled(": PlanetLab account %s is not enabled. Please contact your site PI" %(record['email']))
66 # if this is a self cred the record's gid is the caller's gid
69 caller_gid = record.get_gid_object()
70 print>>sys.stderr, " \r\n REGISTRY IS SELF OK caller_hrn %s--- \r\n caller_gid %s---------" %(caller_hrn,caller_gid)
72 print>> sys.stderr , " \r\n ++ ELSE "
73 caller_gid = api.auth.client_cred.get_gid_caller()
74 print>> sys.stderr , " \r\n ++ ELSE caller_gid %s record %s" %(caller_gid, record)
75 caller_hrn = caller_gid.get_hrn()
76 print>> sys.stderr , " \r\n ++ ELSE caller_hrn %s " %(caller_hrn)
78 object_hrn = record.get_gid_object().get_hrn()
79 print>> sys.stderr , " \r\n ++ ELSE object_hrn %s " %(object_hrn)
81 rights = api.auth.determine_user_rights(caller_hrn, record)
82 print>> sys.stderr , " \r\n ++ After rights record: %s \r\n ====RIGHTS %s " %(record , rights)
84 # make sure caller has rights to this object
86 raise PermissionError(caller_hrn + " has no rights to " + record['name'])
88 object_gid = GID(string=record['gid'])
89 new_cred = Credential(subject = object_gid.get_subject())
90 new_cred.set_gid_caller(caller_gid)
91 new_cred.set_gid_object(object_gid)
92 new_cred.set_issuer_keys(auth_info.get_privkey_filename(), auth_info.get_gid_filename())
93 #new_cred.set_pubkey(object_gid.get_pubkey())
94 new_cred.set_privileges(rights)
95 new_cred.get_privileges().delegate_all_privileges(True)
96 if 'expires' in record:
97 new_cred.set_expiration(int(record['expires']))
98 auth_kind = "authority,ma,sa"
99 # Parent not necessary, verify with certs
100 #new_cred.set_parent(api.auth.hierarchy.get_auth_cred(auth_hrn, kind=auth_kind))
104 return new_cred.save_to_string(save_parents=True)
107 def Resolve(api, xrns, type=None, full=True):
109 # load all known registry names into a prefix tree and attempt to find
110 # the longest matching prefix
111 print >>sys.stderr , '\t\t REGISTRY MANAGER : resolve=========api ', api
112 print >>sys.stderr , '\t\t REGISTRY MANAGER : resolve=========xrns ', xrns
113 if not isinstance(xrns, types.ListType):
115 type = Xrn(xrns).get_type()
117 hrns = [urn_to_hrn(xrn)[0] for xrn in xrns]
118 print >>sys.stderr , '\t\t =========hrns ', hrns
119 # create a dict where key is a registry hrn and its value is a
120 # hrns at that registry (determined by the known prefix tree).
122 print >>sys.stderr, '\r\n REGISTRY MANAGER : resolve xrns ' , xrns #api.__dict__.keys()
123 registries = api.registries
125 registry_hrns = registries.keys()
126 print >>sys.stderr, '\r\n \t\t REGISTRY MANAGER registry_hrns' , registry_hrns
127 tree.load(registry_hrns)
129 registry_hrn = tree.best_match(urn_to_hrn(xrn)[0])
130 print >>sys.stderr, '\t\tREGISTRY MANAGER *****tree.best_match ', registry_hrn
131 if registry_hrn not in xrn_dict:
132 xrn_dict[registry_hrn] = []
133 xrn_dict[registry_hrn].append(xrn)
134 print >>sys.stderr, '\t\tREGISTRY MANAGER *****xrn_dict[registry_hrn] ',xrn_dict[registry_hrn]
136 for registry_hrn in xrn_dict:
137 # skip the hrn without a registry hrn
138 # XX should we let the user know the authority is unknown?
139 print >>sys.stderr, '\t\t registry_hrn in xrn_dict ', registry_hrn
143 # if the best match (longest matching hrn) is not the local registry,
144 # forward the request
145 xrns = xrn_dict[registry_hrn]
146 if registry_hrn != api.hrn:
147 credential = api.getCredential()
148 interface = api.registries[registry_hrn]
149 server = api.server_proxy(interface, credential)
150 peer_records = server.Resolve(xrns, credential)
151 print >>sys.stderr , '\t\t peer_records ', peer_records
152 records.extend([SfaRecord(dict=record).as_dict() for record in peer_records])
154 print >>sys.stderr,'\t\t hrns ' , hrns
155 # try resolving the remaining unfound records at the local registry
156 remaining_hrns = set(hrns).difference([record['hrn'] for record in records])
157 # convert set to list
158 remaining_hrns = [hrn for hrn in remaining_hrns]
159 print >>sys.stderr, '\t\t remaining_hrns', remaining_hrns
161 local_records = table.findObjects({'hrn': remaining_hrns})
163 print >>sys.stderr, '\t\t LOCAL REC !', local_records
164 for rec in local_records:
165 print >>sys.stderr, '\t\t resolve regmanager : rec ', rec
168 print >>sys.stderr, '\r\n \r\n REGISTRY:_FULL', api
170 api.driver.fill_record_info(local_records)
172 # convert local record objects to dicts
173 records.extend([dict(record) for record in local_records])
174 #print >>sys.stderr, "\r\n \t\t records extends %s" %(records)
176 raise RecordNotFound(str(hrns))
179 records = filter(lambda rec: rec['type'] in [type], records)
183 def List(api, xrn, origin_hrn=None):
184 hrn, type = urn_to_hrn(xrn)
185 # load all know registry names into a prefix tree and attempt to find
186 # the longest matching prefix
188 registries = api.registries
189 registry_hrns = registries.keys()
191 tree.load(registry_hrns)
192 registry_hrn = tree.best_match(hrn)
194 #if there was no match then this record belongs to an unknow registry
196 raise MissingAuthority(xrn)
197 # if the best match (longest matching hrn) is not the local registry,
198 # forward the request
200 if registry_hrn != api.hrn:
201 credential = api.getCredential()
202 print>>sys.stderr, "Registries : ", registries
203 interface = api.registries[registry_hrn]
204 server = api.server_proxy(interface, credential)
205 record_list = server.List(xrn, credential)
206 records = [SfaRecord(dict=record).as_dict() for record in record_list]
208 # if we still have not found the record yet, try the local registry
210 if not api.auth.hierarchy.auth_exists(hrn):
211 raise MissingAuthority(hrn)
214 records = table.find({'authority': hrn})
219 def Register(api, record):
222 #hrn, type = record['hrn'], record['type']
223 hrn = str(record['hrn']).strip("['']")
224 type = str( record['type']).strip("['']")
225 urn = hrn_to_urn(hrn,type)
227 if type not in ['authority', 'slice', 'node', 'user']:
228 raise UnknownSfaType(type)
230 # check if record already exists
232 existing_records = table.find({'type': type, 'hrn': hrn})
234 raise ExistingRecord(hrn)
236 record = SfaRecord(dict = record)
238 print>>sys.stderr, " \r\n \r\n ----------- REGISTRY_MANAGER_SLAN.PY register SfaRecordrecord %s" %(record)
239 #record['authority'] = get_authority(record['hrn'])
240 record['authority'] = get_authority(hrn)
242 #type_of_rec = record['type']
245 #api.auth.verify_object_permission(hrn)
246 api.auth.verify_object_permission( record['hrn'])
247 auth_info = api.auth.get_auth_info(record['authority'])
252 # make sure record has a gid
253 if 'gid' not in record:
255 pkey = Keypair(create=True)
256 if 'key' in record and record['key']:
257 if isinstance(record['key'], types.ListType):
258 pub_key = record['key'][0]
260 pub_key = record['key']
261 pkey = convert_public_key(pub_key)
263 gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey)
264 gid = gid_object.save_to_string(save_parents=True)
267 print>>sys.stderr, " \r\n \r\n ----------- REGISTRY_MANAGER_SLAB.PY record['gid'] %s" %(record['gid'])
268 print>>sys.stderr, " \r\n \r\n ----------- REGISTRY_MANAGER_SLAB.PY register type %s"%(type)
270 if type in ["authority"]:
272 if not api.auth.hierarchy.auth_exists(hrn):
273 api.auth.hierarchy.create_auth(hrn_to_urn(hrn,'authority'))
275 # get the GID from the newly created authority
276 gid = auth_info.get_gid_object()
277 record.set_gid(gid.save_to_string(save_parents=True))
279 #pl_record = api.driver.sfa_fields_to_pl_fields(type, hrn, record)
280 print>>sys.stderr, " \r\n \r\n ----------- REGISTRY_MANAGER_SLAB.PY register : type in [authority ] sfa_fields_to_pl_fields FIELDS A CHANGER"
282 # thierry: ideally we'd like to be able to write api.driver.GetSites
283 # in which case the code would become mostly the same as for pl
284 sites = api.driver.GetSites([pl_record['login_base']])
287 # Error (E0601, register): Using variable 'pl_record' before assignment
288 pointer = api.driver.AddSite( pl_record)
290 pointer = sites[0]['site_id']
292 record.set_pointer(pointer)
293 record['pointer'] = pointer
295 elif (type == "slice"):
296 acceptable_fields=['url', 'instantiation', 'name', 'description']
297 pl_record = api.driver.sfa_fields_to_pl_fields(type, hrn, record)
298 print>>sys.stderr, " \r\n \r\n ----------- REGISTRY_MANAGER_SLAB.PY register slice pl_record %s"%(pl_record)
299 for key in pl_record.keys():
300 if key not in acceptable_fields:
302 slices = api.driver.GetSlices([pl_record['name']])
304 pointer = api.driver.AddSlice(pl_record)
306 pointer = slices[0]['slice_id']
307 record.set_pointer(pointer)
308 record['pointer'] = pointer
310 elif (type == "user"):
311 persons = api.driver.GetPersons([record['email']])
313 print>>sys.stderr, " \r\n \r\n ----------- registry_manager_slab register NO PERSON ADD TO LDAP?"
316 #pointer = api.driver.AddPerson( dict(record))
318 #pointer = persons[0]['person_id']
320 if 'enabled' in record and record['enabled']:
321 api.driver.UpdatePerson(pointer, {'enabled': record['enabled']})
322 # add this persons to the site only if he is being added for the first
323 # time by sfa and doesont already exist in plc
324 if not persons or not persons[0]['site_ids']:
325 login_base = get_leaf(record['authority'])
327 api.driver.AddPersonToSite(pointer, login_base)
329 # What roles should this user have?
330 api.driver.AddRoleToPerson('user', pointer)
333 api.driver.AddPersonKey(pointer, {'key_type' : 'ssh', 'key' : pub_key})
335 #elif (type == "node"):
336 #pl_record = api.driver.sfa_fields_to_pl_fields(type, hrn, record)
337 #login_base = hrn_to_pl_login_base(record['authority'])
338 #nodes = api.driver.GetNodes([pl_record['hostname']])
340 #pointer = api.driver.AddNode(login_base, pl_record)
342 #pointer = nodes[0]['node_id']
344 ##record['pointer'] = pointer
345 ##record.set_pointer(pointer)
346 #record_id = table.insert(record)
347 #record['record_id'] = record_id
349 # update membership for researchers, pis, owners, operators
350 api.driver.update_membership(None, record)
352 return record.get_gid_object().save_to_string(save_parents=True)
354 def Update(api, record_dict):
355 new_record = SfaRecord(dict = record_dict)
356 type = new_record['type']
357 hrn = new_record['hrn']
358 urn = hrn_to_urn(hrn,type)
359 api.auth.verify_object_permission(hrn)
361 # make sure the record exists
362 records = table.findObjects({'type': type, 'hrn': hrn})
364 raise RecordNotFound(hrn)
366 record['last_updated'] = time.gmtime()
368 # Update_membership needs the membership lists in the existing record
369 # filled in, so it can see if members were added or removed
370 api.driver.fill_record_info(record)
372 # Use the pointer from the existing record, not the one that the user
373 # gave us. This prevents the user from inserting a forged pointer
374 pointer = record['pointer']
375 # update the PLC information that was specified with the record
377 if (type == "authority"):
378 api.driver.UpdateSite(pointer, new_record)
380 elif type == "slice":
381 pl_record=api.driver.sfa_fields_to_pl_fields(type, hrn, new_record)
382 if 'name' in pl_record:
383 pl_record.pop('name')
384 api.driver.UpdateSlice(pointer, pl_record)
387 # SMBAKER: UpdatePerson only allows a limited set of fields to be
388 # updated. Ideally we should have a more generic way of doing
389 # this. I copied the field names from UpdatePerson.py...
391 all_fields = new_record
392 for key in all_fields.keys():
393 if key in ['first_name', 'last_name', 'title', 'email',
394 'password', 'phone', 'url', 'bio', 'accepted_aup',
396 update_fields[key] = all_fields[key]
397 api.driver.UpdatePerson(pointer, update_fields)
399 if 'key' in new_record and new_record['key']:
400 # must check this key against the previous one if it exists
401 persons = api.driver.GetPersons([pointer], ['key_ids'])
403 keys = person['key_ids']
404 keys = api.driver.GetKeys(person['key_ids'])
406 if isinstance(new_record['key'], types.ListType):
407 new_key = new_record['key'][0]
409 new_key = new_record['key']
411 # Delete all stale keys
413 if new_record['key'] != key['key']:
414 api.driver.DeleteKey(key['key_id'])
418 api.driver.AddPersonKey(pointer, {'key_type': 'ssh', 'key': new_key})
420 # update the openssl key and gid
421 pkey = convert_public_key(new_key)
423 gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey)
424 gid = gid_object.save_to_string(save_parents=True)
426 record = SfaRecord(dict=record)
430 api.driver.UpdateNode(pointer, new_record)
433 raise UnknownSfaType(type)
435 # update membership for researchers, pis, owners, operators
436 api.driver.update_membership(record, new_record)
440 # expecting an Xrn instance
441 def Remove(api, xrn, origin_hrn=None):
444 filter = {'hrn': xrn.get_hrn()}
447 if type and type not in ['all', '*']:
448 filter['type'] = type
450 records = table.find(filter)
451 if not records: raise RecordNotFound(hrn)
453 type = record['type']
455 credential = api.getCredential()
456 registries = api.registries
458 # Try to remove the object from the PLCDB of federated agg.
459 # This is attempted before removing the object from the local agg's PLCDB and sfa table
460 if hrn.startswith(api.hrn) and type in ['user', 'slice', 'authority']:
461 for registry in registries:
462 if registry not in [api.hrn]:
464 result=registries[registry].remove_peer_object(credential, record, origin_hrn)
468 persons = api.driver.GetPersons(record['pointer'])
469 # only delete this person if he has site ids. if he doesnt, it probably means
470 # he was just removed from a site, not actually deleted
471 if persons and persons[0]['site_ids']:
472 api.driver.DeletePerson(record['pointer'])
473 elif type == "slice":
474 if api.driver.GetSlices(record['pointer']):
475 api.driver.DeleteSlice(record['pointer'])
477 if api.driver.GetNodes(record['pointer']):
478 api.driver.DeleteNode(record['pointer'])
479 elif type == "authority":
480 if api.driver.GetSites(record['pointer']):
481 api.driver.DeleteSite(record['pointer'])
483 raise UnknownSfaType(type)