5 from sfa.util.faults import *
6 from sfa.util.prefixTree import prefixTree
7 from sfa.util.record import SfaRecord
8 from sfa.util.table 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
18 # The GENI GetVersion call
20 peers =dict ([ (peername,v._ServerProxy__host) for (peername,v) in api.registries.iteritems()
21 if peername != api.hrn])
23 return version_core({'interface':'registry',
28 def get_credential(api, xrn, type, is_self=False):
31 hrn = urn_to_hrn(xrn)[0]
33 hrn, type = urn_to_hrn(xrn)
35 # Is this a root or sub authority
36 auth_hrn = api.auth.get_authority(hrn)
37 print>> sys.stderr , " \r\n REGISTRY get_credential auth_hrn" , auth_hrn
38 if not auth_hrn or hrn == api.config.SFA_INTERFACE_HRN:
41 auth_info = api.auth.get_auth_info(auth_hrn)
43 records = table.findObjects({'type': type, 'hrn': hrn})
44 print>> sys.stderr , " \r\n ++ REGISTRY get_credential hrn %s records %s " %(hrn, records)
46 raise RecordNotFound(hrn)
49 # verify_cancreate_credential requires that the member lists
50 # (researchers, pis, etc) be filled in
51 #api.fill_record_info(record)
52 record['enabled'] = True
53 print>> sys.stderr , " \r\n ++ REGISTRY get_credential hrn %s record['enabled'] %s is_self %s" %(hrn, record['enabled'], is_self)
54 if record['type']=='user':
55 if not record['enabled']:
56 print>> sys.stderr , " \r\n ++ REGISTRY get_credential hrn %s ACCOUNT Not enabled"
57 raise AccountNotEnabled(": PlanetLab account %s is not enabled. Please contact your site PI" %(record['email']))
60 # if this is a self cred the record's gid is the caller's gid
63 caller_gid = record.get_gid_object()
65 print>> sys.stderr , " \r\n ++ ELSE "
66 caller_gid = api.auth.client_cred.get_gid_caller()
67 print>> sys.stderr , " \r\n ++ ELSE caller_gid %s record %s" %(caller_gid, record)
68 caller_hrn = caller_gid.get_hrn()
69 print>> sys.stderr , " \r\n ++ ELSE caller_hrn %s " %(caller_hrn)
71 object_hrn = record.get_gid_object().get_hrn()
72 print>> sys.stderr , " \r\n ++ ELSE object_hrn %s " %(object_hrn)
74 rights = api.auth.determine_user_rights(caller_hrn, record)
75 print>> sys.stderr , " \r\n ++ After rights record: %s " %(record )
77 # make sure caller has rights to this object
79 raise PermissionError(caller_hrn + " has no rights to " + record['name'])
81 object_gid = GID(string=record['gid'])
82 new_cred = Credential(subject = object_gid.get_subject())
83 new_cred.set_gid_caller(caller_gid)
84 new_cred.set_gid_object(object_gid)
85 new_cred.set_issuer_keys(auth_info.get_privkey_filename(), auth_info.get_gid_filename())
86 #new_cred.set_pubkey(object_gid.get_pubkey())
87 new_cred.set_privileges(rights)
88 new_cred.get_privileges().delegate_all_privileges(True)
89 if 'expires' in record:
90 new_cred.set_expiration(int(record['expires']))
91 auth_kind = "authority,ma,sa"
92 # Parent not necessary, verify with certs
93 #new_cred.set_parent(api.auth.hierarchy.get_auth_cred(auth_hrn, kind=auth_kind))
97 return new_cred.save_to_string(save_parents=True)
100 def resolve(api, xrns, type=None, full=True):
102 # load all known registry names into a prefix tree and attempt to find
103 # the longest matching prefix
104 print >>sys.stderr , '\t\t REGISTRY MANAGER : resolve=========xrns ', xrns
105 if not isinstance(xrns, types.ListType):
107 type = Xrn(xrns).get_type()
109 hrns = [urn_to_hrn(xrn)[0] for xrn in xrns]
110 print >>sys.stderr , '\t\t =========hrns ', hrns
111 # create a dict where key is a registry hrn and its value is a
112 # hrns at that registry (determined by the known prefix tree).
114 print >>sys.stderr, '\r\n REGISTRY MANAGER : resolve xrns ' , xrns #api.__dict__.keys()
115 registries = api.registries
117 registry_hrns = registries.keys()
118 print >>sys.stderr, '\r\n \t\t REGISTRY MANAGER registry_hrns' , registry_hrns
119 tree.load(registry_hrns)
121 registry_hrn = tree.best_match(urn_to_hrn(xrn)[0])
122 print >>sys.stderr, '\t\tREGISTRY MANAGER *****tree.best_match ', registry_hrn
123 if registry_hrn not in xrn_dict:
124 xrn_dict[registry_hrn] = []
125 xrn_dict[registry_hrn].append(xrn)
126 print >>sys.stderr, '\t\tREGISTRY MANAGER *****xrn_dict[registry_hrn] ',xrn_dict[registry_hrn]
129 for registry_hrn in xrn_dict:
130 # skip the hrn without a registry hrn
131 # XX should we let the user know the authority is unknown?
132 print >>sys.stderr, '\t\t registry_hrn in xrn_dict ', registry_hrn
136 # if the best match (longest matching hrn) is not the local registry,
137 # forward the request
138 xrns = xrn_dict[registry_hrn]
139 if registry_hrn != api.hrn:
140 credential = api.getCredential()
141 peer_records = registries[registry_hrn].Resolve(xrns, credential)
142 print >>sys.stderr , '\t\t peer_records ', peer_records
143 records.extend([SfaRecord(dict=record).as_dict() for record in peer_records])
145 print >>sys.stderr,'\t\t hrns ' , hrns
146 # try resolving the remaining unfound records at the local registry
147 remaining_hrns = set(hrns).difference([record['hrn'] for record in records])
149 # convert set to list
150 remaining_hrns = [hrn for hrn in remaining_hrns]
151 print >>sys.stderr, '\t\t remaining_hrns', remaining_hrns
153 local_records = table.findObjects({'hrn': remaining_hrns})
155 print >>sys.stderr, '\t\t LOCAL REC !', local_records
156 for rec in local_records:
157 print >>sys.stderr, '\t\t resolve regmanager : rec ', rec
160 print >>sys.stderr, '\r\n \r\n REGISTRY:_FULL', api
161 api.fill_record_info(local_records)
164 # convert local record objects to dicts
165 records.extend([dict(record) for record in local_records])
166 print >>sys.stderr, "\r\n \t\t records extends %s" %(records)
168 raise RecordNotFound(str(hrns))
171 records = filter(lambda rec: rec['type'] in [type], records)
175 def list(api, xrn, origin_hrn=None):
176 hrn, type = urn_to_hrn(xrn)
177 # load all know registry names into a prefix tree and attempt to find
178 # the longest matching prefix
180 registries = api.registries
181 registry_hrns = registries.keys()
183 tree.load(registry_hrns)
184 registry_hrn = tree.best_match(hrn)
186 #if there was no match then this record belongs to an unknow registry
188 raise MissingAuthority(xrn)
190 # if the best match (longest matching hrn) is not the local registry,
191 # forward the request
193 if registry_hrn != api.hrn:
194 credential = api.getCredential()
195 record_list = registries[registry_hrn].List(xrn, credential)
196 records = [SfaRecord(dict=record).as_dict() for record in record_list]
198 # if we still have not found the record yet, try the local registry
200 if not api.auth.hierarchy.auth_exists(hrn):
201 raise MissingAuthority(hrn)
204 records = table.find({'authority': hrn})
209 def register(api, record):
211 print>>sys.stderr, " \r\n \r\n ----------- registry_manager_sl register hrn %s"%(hrn)
212 hrn, type = record['hrn'], record['type']
213 urn = hrn_to_urn(hrn,type)
215 if type not in ['authority', 'slice', 'node', 'user']:
216 raise UnknownSfaType(type)
218 # check if record already exists
220 existing_records = table.find({'type': type, 'hrn': hrn})
222 raise ExistingRecord(hrn)
224 record = SfaRecord(dict = record)
225 record['authority'] = get_authority(record['hrn'])
226 type = record['type']
228 api.auth.verify_object_permission(hrn)
229 auth_info = api.auth.get_auth_info(record['authority'])
231 # make sure record has a gid
232 if 'gid' not in record:
234 pkey = Keypair(create=True)
235 if 'key' in record and record['key']:
236 if isinstance(record['key'], types.ListType):
237 pub_key = record['key'][0]
239 pub_key = record['key']
240 pkey = convert_public_key(pub_key)
242 gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey)
243 gid = gid_object.save_to_string(save_parents=True)
247 if type in ["authority"]:
249 if not api.auth.hierarchy.auth_exists(hrn):
250 api.auth.hierarchy.create_auth(hrn_to_urn(hrn,'authority'))
252 # get the GID from the newly created authority
253 gid = auth_info.get_gid_object()
254 record.set_gid(gid.save_to_string(save_parents=True))
255 pl_record = api.sfa_fields_to_pl_fields(type, hrn, record)
256 sites = api.plshell.GetSites(api.plauth, [pl_record['login_base']])
258 pointer = api.plshell.AddSite(api.plauth, pl_record)
260 pointer = sites[0]['site_id']
262 record.set_pointer(pointer)
263 record['pointer'] = pointer
265 elif (type == "slice"):
266 acceptable_fields=['url', 'instantiation', 'name', 'description']
267 pl_record = api.sfa_fields_to_pl_fields(type, hrn, record)
268 for key in pl_record.keys():
269 if key not in acceptable_fields:
271 slices = api.plshell.GetSlices(api.plauth, [pl_record['name']])
273 pointer = api.plshell.AddSlice(api.plauth, pl_record)
275 pointer = slices[0]['slice_id']
276 record.set_pointer(pointer)
277 record['pointer'] = pointer
279 elif (type == "user"):
280 persons = api.plshell.GetPersons(api.plauth, [record['email']])
282 pointer = api.plshell.AddPerson(api.plauth, dict(record))
284 pointer = persons[0]['person_id']
286 if 'enabled' in record and record['enabled']:
287 api.plshell.UpdatePerson(api.plauth, pointer, {'enabled': record['enabled']})
288 # add this persons to the site only if he is being added for the first
289 # time by sfa and doesont already exist in plc
290 if not persons or not persons[0]['site_ids']:
291 login_base = get_leaf(record['authority'])
292 api.plshell.AddPersonToSite(api.plauth, pointer, login_base)
294 # What roles should this user have?
295 api.plshell.AddRoleToPerson(api.plauth, 'user', pointer)
298 api.plshell.AddPersonKey(api.plauth, pointer, {'key_type' : 'ssh', 'key' : pub_key})
300 elif (type == "node"):
301 pl_record = api.sfa_fields_to_pl_fields(type, hrn, record)
302 login_base = hrn_to_pl_login_base(record['authority'])
303 nodes = api.plshell.GetNodes(api.plauth, [pl_record['hostname']])
305 pointer = api.plshell.AddNode(api.plauth, login_base, pl_record)
307 pointer = nodes[0]['node_id']
309 record['pointer'] = pointer
310 record.set_pointer(pointer)
311 record_id = table.insert(record)
312 record['record_id'] = record_id
314 # update membership for researchers, pis, owners, operators
315 api.update_membership(None, record)
317 return record.get_gid_object().save_to_string(save_parents=True)
319 def update(api, record_dict):
320 new_record = SfaRecord(dict = record_dict)
321 type = new_record['type']
322 hrn = new_record['hrn']
323 urn = hrn_to_urn(hrn,type)
324 api.auth.verify_object_permission(hrn)
326 # make sure the record exists
327 records = table.findObjects({'type': type, 'hrn': hrn})
329 raise RecordNotFound(hrn)
331 record['last_updated'] = time.gmtime()
333 # Update_membership needs the membership lists in the existing record
334 # filled in, so it can see if members were added or removed
335 api.fill_record_info(record)
337 # Use the pointer from the existing record, not the one that the user
338 # gave us. This prevents the user from inserting a forged pointer
339 pointer = record['pointer']
340 # update the PLC information that was specified with the record
342 if (type == "authority"):
343 api.plshell.UpdateSite(api.plauth, pointer, new_record)
345 elif type == "slice":
346 pl_record=api.sfa_fields_to_pl_fields(type, hrn, new_record)
347 if 'name' in pl_record:
348 pl_record.pop('name')
349 api.plshell.UpdateSlice(api.plauth, pointer, pl_record)
352 # SMBAKER: UpdatePerson only allows a limited set of fields to be
353 # updated. Ideally we should have a more generic way of doing
354 # this. I copied the field names from UpdatePerson.py...
356 all_fields = new_record
357 for key in all_fields.keys():
358 if key in ['first_name', 'last_name', 'title', 'email',
359 'password', 'phone', 'url', 'bio', 'accepted_aup',
361 update_fields[key] = all_fields[key]
362 api.plshell.UpdatePerson(api.plauth, pointer, update_fields)
364 if 'key' in new_record and new_record['key']:
365 # must check this key against the previous one if it exists
366 persons = api.plshell.GetPersons(api.plauth, [pointer], ['key_ids'])
368 keys = person['key_ids']
369 keys = api.plshell.GetKeys(api.plauth, person['key_ids'])
371 if isinstance(new_record['key'], types.ListType):
372 new_key = new_record['key'][0]
374 new_key = new_record['key']
376 # Delete all stale keys
378 if new_record['key'] != key['key']:
379 api.plshell.DeleteKey(api.plauth, key['key_id'])
383 api.plshell.AddPersonKey(api.plauth, pointer, {'key_type': 'ssh', 'key': new_key})
385 # update the openssl key and gid
386 pkey = convert_public_key(new_key)
388 gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey)
389 gid = gid_object.save_to_string(save_parents=True)
391 record = SfaRecord(dict=record)
395 api.plshell.UpdateNode(api.plauth, pointer, new_record)
398 raise UnknownSfaType(type)
400 # update membership for researchers, pis, owners, operators
401 api.update_membership(record, new_record)
405 # expecting an Xrn instance
406 def remove(api, xrn, origin_hrn=None):
409 filter = {'hrn': xrn.get_hrn()}
412 if type and type not in ['all', '*']:
413 filter['type'] = type
415 records = table.find(filter)
416 if not records: raise RecordNotFound(hrn)
418 type = record['type']
420 credential = api.getCredential()
421 registries = api.registries
423 # Try to remove the object from the PLCDB of federated agg.
424 # This is attempted before removing the object from the local agg's PLCDB and sfa table
425 if hrn.startswith(api.hrn) and type in ['user', 'slice', 'authority']:
426 for registry in registries:
427 if registry not in [api.hrn]:
429 result=registries[registry].remove_peer_object(credential, record, origin_hrn)
433 persons = api.plshell.GetPersons(api.plauth, record['pointer'])
434 # only delete this person if he has site ids. if he doesnt, it probably means
435 # he was just removed from a site, not actually deleted
436 if persons and persons[0]['site_ids']:
437 api.plshell.DeletePerson(api.plauth, record['pointer'])
438 elif type == "slice":
439 if api.plshell.GetSlices(api.plauth, record['pointer']):
440 api.plshell.DeleteSlice(api.plauth, record['pointer'])
442 if api.plshell.GetNodes(api.plauth, record['pointer']):
443 api.plshell.DeleteNode(api.plauth, record['pointer'])
444 elif type == "authority":
445 if api.plshell.GetSites(api.plauth, record['pointer']):
446 api.plshell.DeleteSite(api.plauth, record['pointer'])
448 raise UnknownSfaType(type)
454 def remove_peer_object(api, record, origin_hrn=None):
457 def register_peer_object(api, record, origin_hrn=None):