4 from sfa.util.faults import *
5 from sfa.util.prefixTree import prefixTree
6 from sfa.util.record import SfaRecord
7 from sfa.util.table import SfaTable
8 from sfa.util.record import SfaRecord
9 from sfa.trust.gid import GID
10 from sfa.util.xrn import Xrn, get_leaf, get_authority, hrn_to_urn, urn_to_hrn
11 from sfa.util.plxrn import hrn_to_pl_login_base
12 from sfa.trust.credential import Credential
13 from sfa.trust.certificate import Certificate, Keypair
14 from sfa.trust.gid import create_uuid
15 from sfa.util.version import version_core
17 # The GENI GetVersion call
19 peers =dict ([ (peername,v._ServerProxy__host) for (peername,v) in api.registries.iteritems()
20 if peername != api.hrn])
22 return version_core({'interface':'registry',
27 def get_credential(api, xrn, type, is_self=False):
30 hrn = urn_to_hrn(xrn)[0]
32 hrn, type = urn_to_hrn(xrn)
34 # Is this a root or sub authority
35 auth_hrn = api.auth.get_authority(hrn)
36 if not auth_hrn or hrn == api.config.SFA_INTERFACE_HRN:
39 auth_info = api.auth.get_auth_info(auth_hrn)
41 records = table.findObjects({'type': type, 'hrn': hrn})
43 raise RecordNotFound(hrn)
46 # verify_cancreate_credential requires that the member lists
47 # (researchers, pis, etc) be filled in
48 api.fill_record_info(record)
49 if record['type']=='user':
50 if not record['enabled']:
51 raise AccountNotEnabled(": PlanetLab account %s is not enabled. Please contact your site PI" %(record['email']))
54 # if this is a self cred the record's gid is the caller's gid
57 caller_gid = record.get_gid_object()
59 caller_gid = api.auth.client_cred.get_gid_caller()
60 caller_hrn = caller_gid.get_hrn()
62 object_hrn = record.get_gid_object().get_hrn()
63 rights = api.auth.determine_user_rights(caller_hrn, record)
64 # make sure caller has rights to this object
66 raise PermissionError(caller_hrn + " has no rights to " + record['name'])
68 object_gid = GID(string=record['gid'])
69 new_cred = Credential(subject = object_gid.get_subject())
70 new_cred.set_gid_caller(caller_gid)
71 new_cred.set_gid_object(object_gid)
72 new_cred.set_issuer_keys(auth_info.get_privkey_filename(), auth_info.get_gid_filename())
73 #new_cred.set_pubkey(object_gid.get_pubkey())
74 new_cred.set_privileges(rights)
75 new_cred.get_privileges().delegate_all_privileges(True)
76 if 'expires' in record:
77 new_cred.set_expiration(int(record['expires']))
78 auth_kind = "authority,ma,sa"
79 # Parent not necessary, verify with certs
80 #new_cred.set_parent(api.auth.hierarchy.get_auth_cred(auth_hrn, kind=auth_kind))
84 return new_cred.save_to_string(save_parents=True)
87 def resolve(api, xrns, type=None, full=True):
89 # load all known registry names into a prefix tree and attempt to find
90 # the longest matching prefix
91 if not isinstance(xrns, types.ListType):
93 type = Xrn(xrns).get_type()
95 hrns = [urn_to_hrn(xrn)[0] for xrn in xrns]
96 # create a dict where key is a registry hrn and its value is a
97 # hrns at that registry (determined by the known prefix tree).
99 registries = api.registries
101 registry_hrns = registries.keys()
102 tree.load(registry_hrns)
104 registry_hrn = tree.best_match(urn_to_hrn(xrn)[0])
105 if registry_hrn not in xrn_dict:
106 xrn_dict[registry_hrn] = []
107 xrn_dict[registry_hrn].append(xrn)
110 for registry_hrn in xrn_dict:
111 # skip the hrn without a registry hrn
112 # XX should we let the user know the authority is unknown?
116 # if the best match (longest matching hrn) is not the local registry,
117 # forward the request
118 xrns = xrn_dict[registry_hrn]
119 if registry_hrn != api.hrn:
120 credential = api.getCredential()
121 peer_records = registries[registry_hrn].Resolve(xrns, credential)
122 records.extend([SfaRecord(dict=record).as_dict() for record in peer_records])
124 # try resolving the remaining unfound records at the local registry
125 remaining_hrns = set(hrns).difference([record['hrn'] for record in records])
126 # convert set to list
127 remaining_hrns = [hrn for hrn in remaining_hrns]
129 local_records = table.findObjects({'hrn': remaining_hrns})
131 api.fill_record_info(local_records)
133 # convert local record objects to dicts
134 records.extend([dict(record) for record in local_records])
136 raise RecordNotFound(str(hrns))
139 records = filter(lambda rec: rec['type'] in [type], records)
143 def list(api, xrn, origin_hrn=None):
144 hrn, type = urn_to_hrn(xrn)
145 # load all know registry names into a prefix tree and attempt to find
146 # the longest matching prefix
148 registries = api.registries
149 registry_hrns = registries.keys()
151 tree.load(registry_hrns)
152 registry_hrn = tree.best_match(hrn)
154 #if there was no match then this record belongs to an unknow registry
156 raise MissingAuthority(xrn)
158 # if the best match (longest matching hrn) is not the local registry,
159 # forward the request
161 if registry_hrn != api.hrn:
162 credential = api.getCredential()
163 record_list = registries[registry_hrn].List(xrn, credential)
164 records = [SfaRecord(dict=record).as_dict() for record in record_list]
166 # if we still have not found the record yet, try the local registry
168 if not api.auth.hierarchy.auth_exists(hrn):
169 raise MissingAuthority(hrn)
172 records = table.find({'authority': hrn})
177 def register(api, record):
179 hrn, type = record['hrn'], record['type']
180 urn = hrn_to_urn(hrn,type)
182 if type not in ['authority', 'slice', 'node', 'user']:
183 raise UnknownSfaType(type)
185 # check if record already exists
187 existing_records = table.find({'type': type, 'hrn': hrn})
189 raise ExistingRecord(hrn)
191 record = SfaRecord(dict = record)
192 record['authority'] = get_authority(record['hrn'])
193 type = record['type']
195 api.auth.verify_object_permission(hrn)
196 auth_info = api.auth.get_auth_info(record['authority'])
198 # make sure record has a gid
199 if 'gid' not in record:
201 pkey = Keypair(create=True)
202 if 'key' in record and record['key']:
203 if isinstance(record['key'], types.ListType):
204 pub_key = record['key'][0]
206 pub_key = record['key']
207 pkey = convert_public_key(pub_key)
209 gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey)
210 gid = gid_object.save_to_string(save_parents=True)
214 if type in ["authority"]:
216 if not api.auth.hierarchy.auth_exists(hrn):
217 api.auth.hierarchy.create_auth(hrn_to_urn(hrn,'authority'))
219 # get the GID from the newly created authority
220 gid = auth_info.get_gid_object()
221 record.set_gid(gid.save_to_string(save_parents=True))
222 pl_record = api.sfa_fields_to_pl_fields(type, hrn, record)
223 sites = api.plshell.GetSites(api.plauth, [pl_record['login_base']])
225 pointer = api.plshell.AddSite(api.plauth, pl_record)
227 pointer = sites[0]['site_id']
229 record.set_pointer(pointer)
230 record['pointer'] = pointer
232 elif (type == "slice"):
233 acceptable_fields=['url', 'instantiation', 'name', 'description']
234 pl_record = api.sfa_fields_to_pl_fields(type, hrn, record)
235 for key in pl_record.keys():
236 if key not in acceptable_fields:
238 slices = api.plshell.GetSlices(api.plauth, [pl_record['name']])
240 pointer = api.plshell.AddSlice(api.plauth, pl_record)
242 pointer = slices[0]['slice_id']
243 record.set_pointer(pointer)
244 record['pointer'] = pointer
246 elif (type == "user"):
247 persons = api.plshell.GetPersons(api.plauth, [record['email']])
249 pointer = api.plshell.AddPerson(api.plauth, dict(record))
251 pointer = persons[0]['person_id']
253 if 'enabled' in record and record['enabled']:
254 api.plshell.UpdatePerson(api.plauth, pointer, {'enabled': record['enabled']})
255 # add this persons to the site only if he is being added for the first
256 # time by sfa and doesont already exist in plc
257 if not persons or not persons[0]['site_ids']:
258 login_base = get_leaf(record['authority'])
259 api.plshell.AddPersonToSite(api.plauth, pointer, login_base)
261 # What roles should this user have?
262 api.plshell.AddRoleToPerson(api.plauth, 'user', pointer)
265 api.plshell.AddPersonKey(api.plauth, pointer, {'key_type' : 'ssh', 'key' : pub_key})
267 elif (type == "node"):
268 pl_record = api.sfa_fields_to_pl_fields(type, hrn, record)
269 login_base = hrn_to_pl_login_base(record['authority'])
270 nodes = api.plshell.GetNodes(api.plauth, [pl_record['hostname']])
272 pointer = api.plshell.AddNode(api.plauth, login_base, pl_record)
274 pointer = nodes[0]['node_id']
276 record['pointer'] = pointer
277 record.set_pointer(pointer)
278 record_id = table.insert(record)
279 record['record_id'] = record_id
281 # update membership for researchers, pis, owners, operators
282 api.update_membership(None, record)
284 return record.get_gid_object().save_to_string(save_parents=True)
286 def update(api, record_dict):
287 new_record = SfaRecord(dict = record_dict)
288 type = new_record['type']
289 hrn = new_record['hrn']
290 urn = hrn_to_urn(hrn,type)
291 api.auth.verify_object_permission(hrn)
293 # make sure the record exists
294 records = table.findObjects({'type': type, 'hrn': hrn})
296 raise RecordNotFound(hrn)
298 record['last_updated'] = time.gmtime()
300 # Update_membership needs the membership lists in the existing record
301 # filled in, so it can see if members were added or removed
302 api.fill_record_info(record)
304 # Use the pointer from the existing record, not the one that the user
305 # gave us. This prevents the user from inserting a forged pointer
306 pointer = record['pointer']
307 # update the PLC information that was specified with the record
309 if (type == "authority"):
310 api.plshell.UpdateSite(api.plauth, pointer, new_record)
312 elif type == "slice":
313 pl_record=api.sfa_fields_to_pl_fields(type, hrn, new_record)
314 if 'name' in pl_record:
315 pl_record.pop('name')
316 api.plshell.UpdateSlice(api.plauth, pointer, pl_record)
319 # SMBAKER: UpdatePerson only allows a limited set of fields to be
320 # updated. Ideally we should have a more generic way of doing
321 # this. I copied the field names from UpdatePerson.py...
323 all_fields = new_record
324 for key in all_fields.keys():
325 if key in ['first_name', 'last_name', 'title', 'email',
326 'password', 'phone', 'url', 'bio', 'accepted_aup',
328 update_fields[key] = all_fields[key]
329 api.plshell.UpdatePerson(api.plauth, pointer, update_fields)
331 if 'key' in new_record and new_record['key']:
332 # must check this key against the previous one if it exists
333 persons = api.plshell.GetPersons(api.plauth, [pointer], ['key_ids'])
335 keys = person['key_ids']
336 keys = api.plshell.GetKeys(api.plauth, person['key_ids'])
338 if isinstance(new_record['key'], types.ListType):
339 new_key = new_record['key'][0]
341 new_key = new_record['key']
343 # Delete all stale keys
345 if new_record['key'] != key['key']:
346 api.plshell.DeleteKey(api.plauth, key['key_id'])
350 api.plshell.AddPersonKey(api.plauth, pointer, {'key_type': 'ssh', 'key': new_key})
352 # update the openssl key and gid
353 pkey = convert_public_key(new_key)
355 gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey)
356 gid = gid_object.save_to_string(save_parents=True)
358 record = SfaRecord(dict=record)
362 api.plshell.UpdateNode(api.plauth, pointer, new_record)
365 raise UnknownSfaType(type)
367 # update membership for researchers, pis, owners, operators
368 api.update_membership(record, new_record)
372 # expecting an Xrn instance
373 def remove(api, xrn, origin_hrn=None):
376 filter = {'hrn': xrn.get_hrn()}
379 if type and type not in ['all', '*']:
380 filter['type'] = type
382 records = table.find(filter)
383 if not records: raise RecordNotFound(hrn)
385 type = record['type']
387 credential = api.getCredential()
388 registries = api.registries
390 # Try to remove the object from the PLCDB of federated agg.
391 # This is attempted before removing the object from the local agg's PLCDB and sfa table
392 if hrn.startswith(api.hrn) and type in ['user', 'slice', 'authority']:
393 for registry in registries:
394 if registry not in [api.hrn]:
396 result=registries[registry].remove_peer_object(credential, record, origin_hrn)
400 persons = api.plshell.GetPersons(api.plauth, record['pointer'])
401 # only delete this person if he has site ids. if he doesnt, it probably means
402 # he was just removed from a site, not actually deleted
403 if persons and persons[0]['site_ids']:
404 api.plshell.DeletePerson(api.plauth, record['pointer'])
405 elif type == "slice":
406 if api.plshell.GetSlices(api.plauth, record['pointer']):
407 api.plshell.DeleteSlice(api.plauth, record['pointer'])
409 if api.plshell.GetNodes(api.plauth, record['pointer']):
410 api.plshell.DeleteNode(api.plauth, record['pointer'])
411 elif type == "authority":
412 if api.plshell.GetSites(api.plauth, record['pointer']):
413 api.plshell.DeleteSite(api.plauth, record['pointer'])
415 raise UnknownSfaType(type)
421 def remove_peer_object(api, record, origin_hrn=None):
424 def register_peer_object(api, record, origin_hrn=None):