3 from sfa.util.prefixTree import prefixTree
4 from sfa.util.record import SfaRecord
5 from sfa.util.table import SfaTable
6 from sfa.util.record import SfaRecord
7 from sfa.trust.gid import GID
8 from sfa.util.namespace import get_leaf, get_authority, hrn_to_urn, hrn_to_pl_login_base, urn_to_hrn
9 from sfa.trust.credential import *
10 from sfa.trust.certificate import *
11 from sfa.util.faults import *
12 from sfa.trust.gid import create_uuid
16 version['geni_api'] = 1
20 def get_credential(api, xrn, type, is_self=False):
23 hrn = urn_to_hrn(xrn)[0]
25 hrn, type = urn_to_hrn(xrn)
27 # Is this a root or sub authority
28 auth_hrn = api.auth.get_authority(hrn)
29 if not auth_hrn or hrn == api.config.SFA_INTERFACE_HRN:
32 auth_info = api.auth.get_auth_info(auth_hrn)
34 records = table.findObjects({'type': type, 'hrn': hrn})
36 raise RecordNotFound(hrn)
39 # verify_cancreate_credential requires that the member lists
40 # (researchers, pis, etc) be filled in
41 api.fill_record_info(record)
42 if record['type']=='user':
43 if not record['enabled']:
44 raise AccountNotEnabled(": PlanetLab account %s is not enabled. Please contact your site PI" %(record['email']))
47 # if this is a self cred the record's gid is the caller's gid
50 caller_gid = record.get_gid_object()
52 caller_gid = api.auth.client_cred.get_gid_caller()
53 caller_hrn = caller_gid.get_hrn()
55 object_hrn = record.get_gid_object().get_hrn()
56 rights = api.auth.determine_user_rights(caller_hrn, record)
57 # make sure caller has rights to this object
59 raise PermissionError(caller_hrn + " has no rights to " + record['name'])
61 object_gid = GID(string=record['gid'])
62 new_cred = Credential(subject = object_gid.get_subject())
63 new_cred.set_gid_caller(caller_gid)
64 new_cred.set_gid_object(object_gid)
65 new_cred.set_issuer_keys(auth_info.get_privkey_filename(), auth_info.get_gid_filename())
66 #new_cred.set_pubkey(object_gid.get_pubkey())
67 new_cred.set_privileges(rights)
68 new_cred.get_privileges().delegate_all_privileges(True)
69 auth_kind = "authority,ma,sa"
70 # Parent not necessary, verify with certs
71 #new_cred.set_parent(api.auth.hierarchy.get_auth_cred(auth_hrn, kind=auth_kind))
75 return new_cred.save_to_string(save_parents=True)
78 # The GENI GetVersion call
81 version['geni_api'] = 1
84 def resolve(api, xrns, type=None, full=True):
86 # load all know registry names into a prefix tree and attempt to find
87 # the longest matching prefix
88 if not isinstance(xrns, types.ListType):
90 hrns = [urn_to_hrn(xrn)[0] for xrn in xrns]
91 # create a dict whre key is an registry hrn and its value is a
92 # hrns at that registry (determined by the known prefix tree).
94 registries = api.registries
96 registry_hrns = registries.keys()
97 tree.load(registry_hrns)
99 registry_hrn = tree.best_match(urn_to_hrn(xrn)[0])
100 if registry_hrn not in xrn_dict:
101 xrn_dict[registry_hrn] = []
102 xrn_dict[registry_hrn].append(xrn)
105 for registry_hrn in xrn_dict:
106 # skip the hrn without a registry hrn
107 # XX should we let the user know the authority is unknown?
111 # if the best match (longest matching hrn) is not the local registry,
112 # forward the request
113 xrns = xrn_dict[registry_hrn]
114 if registry_hrn != api.hrn:
115 credential = api.getCredential()
116 peer_records = registries[registry_hrn].Resolve(xrns, credential)
117 records.extend([SfaRecord(dict=record).as_dict() for record in peer_records])
119 # try resolving the remaining unfound records at the local registry
120 remaining_hrns = set(hrns).difference([record['hrn'] for record in records])
121 # convert set to list
122 remaining_hrns = [hrn for hrn in remaining_hrns]
124 local_records = table.findObjects({'hrn': remaining_hrns})
126 api.fill_record_info(local_records)
128 # convert local record objects to dicts
129 records.extend([dict(record) for record in local_records])
131 raise RecordNotFound(str(hrns))
134 records = filter(lambda rec: rec['type'] in [type], records)
138 def list(api, xrn, origin_hrn=None):
139 hrn, type = urn_to_hrn(xrn)
140 # load all know registry names into a prefix tree and attempt to find
141 # the longest matching prefix
143 registries = api.registries
144 registry_hrns = registries.keys()
146 tree.load(registry_hrns)
147 registry_hrn = tree.best_match(hrn)
149 #if there was no match then this record belongs to an unknow registry
151 raise MissingAuthority(xrn)
153 # if the best match (longest matching hrn) is not the local registry,
154 # forward the request
156 if registry_hrn != api.hrn:
157 credential = api.getCredential()
158 record_list = registries[registry_hrn].list(credential, xrn, origin_hrn)
159 records = [SfaRecord(dict=record).as_dict() for record in record_list]
161 # if we still havnt found the record yet, try the local registry
163 if not api.auth.hierarchy.auth_exists(hrn):
164 raise MissingAuthority(hrn)
167 records = table.find({'authority': hrn})
172 def register(api, record):
174 hrn, type = record['hrn'], record['type']
175 urn = hrn_to_urn(hrn,type)
177 if type not in ['authority', 'slice', 'node', 'user']:
178 raise UnknownSfaType(type)
180 # check if record already exists
182 existing_records = table.find({'type': type, 'hrn': hrn})
184 raise ExistingRecord(hrn)
186 record = SfaRecord(dict = record)
187 record['authority'] = get_authority(record['hrn'])
188 type = record['type']
190 api.auth.verify_object_permission(hrn)
191 auth_info = api.auth.get_auth_info(record['authority'])
193 # make sure record has a gid
194 if 'gid' not in record:
196 pkey = Keypair(create=True)
197 if 'key' in record and record['key']:
198 if isinstance(record['key'], types.ListType):
199 pub_key = record['key'][0]
201 pub_key = record['key']
202 pkey = convert_public_key(pub_key)
204 gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey)
205 gid = gid_object.save_to_string(save_parents=True)
209 if type in ["authority"]:
211 if not api.auth.hierarchy.auth_exists(hrn):
212 api.auth.hierarchy.create_auth(hrn_to_urn(hrn,'authority'))
214 # get the GID from the newly created authority
215 gid = auth_info.get_gid_object()
216 record.set_gid(gid.save_to_string(save_parents=True))
217 pl_record = api.sfa_fields_to_pl_fields(type, hrn, record)
218 sites = api.plshell.GetSites(api.plauth, [pl_record['login_base']])
220 pointer = api.plshell.AddSite(api.plauth, pl_record)
222 pointer = sites[0]['site_id']
224 record.set_pointer(pointer)
225 record['pointer'] = pointer
227 elif (type == "slice"):
228 acceptable_fields=['url', 'instantiation', 'name', 'description']
229 pl_record = api.sfa_fields_to_pl_fields(type, hrn, record)
230 for key in pl_record.keys():
231 if key not in acceptable_fields:
233 slices = api.plshell.GetSlices(api.plauth, [pl_record['name']])
235 pointer = api.plshell.AddSlice(api.plauth, pl_record)
237 pointer = slices[0]['slice_id']
238 record.set_pointer(pointer)
239 record['pointer'] = pointer
241 elif (type == "user"):
242 persons = api.plshell.GetPersons(api.plauth, [record['email']])
244 pointer = api.plshell.AddPerson(api.plauth, dict(record))
246 pointer = persons[0]['person_id']
248 if 'enabled' in record and record['enabled']:
249 api.plshell.UpdatePerson(api.plauth, pointer, {'enabled': record['enabled']})
250 # add this persons to the site only if he is being added for the first
251 # time by sfa and doesont already exist in plc
252 if not persons or not persons[0]['site_ids']:
253 login_base = get_leaf(record['authority'])
254 api.plshell.AddPersonToSite(api.plauth, pointer, login_base)
256 # What roles should this user have?
257 api.plshell.AddRoleToPerson(api.plauth, 'user', pointer)
260 api.plshell.AddPersonKey(api.plauth, pointer, {'key_type' : 'ssh', 'key' : pub_key})
262 elif (type == "node"):
263 pl_record = api.sfa_fields_to_pl_fields(type, hrn, record)
264 login_base = hrn_to_pl_login_base(record['authority'])
265 nodes = api.plshell.GetNodes(api.plauth, [pl_record['hostname']])
267 pointer = api.plshell.AddNode(api.plauth, login_base, pl_record)
269 pointer = nodes[0]['node_id']
271 record['pointer'] = pointer
272 record.set_pointer(pointer)
273 record_id = table.insert(record)
274 record['record_id'] = record_id
276 # update membership for researchers, pis, owners, operators
277 api.update_membership(None, record)
279 return record.get_gid_object().save_to_string(save_parents=True)
281 def update(api, record_dict):
282 new_record = SfaRecord(dict = record_dict)
283 type = new_record['type']
284 hrn = new_record['hrn']
285 urn = hrn_to_urn(hrn,type)
286 api.auth.verify_object_permission(hrn)
288 # make sure the record exists
289 records = table.findObjects({'type': type, 'hrn': hrn})
291 raise RecordNotFound(hrn)
293 record['last_updated'] = time.gmtime()
295 # Update_membership needs the membership lists in the existing record
296 # filled in, so it can see if members were added or removed
297 api.fill_record_info(record)
299 # Use the pointer from the existing record, not the one that the user
300 # gave us. This prevents the user from inserting a forged pointer
301 pointer = record['pointer']
302 # update the PLC information that was specified with the record
304 if (type == "authority"):
305 api.plshell.UpdateSite(api.plauth, pointer, new_record)
307 elif type == "slice":
308 pl_record=api.sfa_fields_to_pl_fields(type, hrn, new_record)
309 if 'name' in pl_record:
310 pl_record.pop('name')
311 api.plshell.UpdateSlice(api.plauth, pointer, pl_record)
314 # SMBAKER: UpdatePerson only allows a limited set of fields to be
315 # updated. Ideally we should have a more generic way of doing
316 # this. I copied the field names from UpdatePerson.py...
318 all_fields = new_record
319 for key in all_fields.keys():
320 if key in ['first_name', 'last_name', 'title', 'email',
321 'password', 'phone', 'url', 'bio', 'accepted_aup',
323 update_fields[key] = all_fields[key]
324 api.plshell.UpdatePerson(api.plauth, pointer, update_fields)
326 if 'key' in new_record and new_record['key']:
327 # must check this key against the previous one if it exists
328 persons = api.plshell.GetPersons(api.plauth, [pointer], ['key_ids'])
330 keys = person['key_ids']
331 keys = api.plshell.GetKeys(api.plauth, person['key_ids'])
333 if isinstance(new_record['key'], types.ListType):
334 new_key = new_record['key'][0]
336 new_key = new_record['key']
338 # Delete all stale keys
340 if new_record['key'] != key['key']:
341 api.plshell.DeleteKey(api.plauth, key['key_id'])
345 api.plshell.AddPersonKey(api.plauth, pointer, {'key_type': 'ssh', 'key': new_key})
347 # update the openssl key and gid
348 pkey = convert_public_key(new_key)
350 gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey)
351 gid = gid_object.save_to_string(save_parents=True)
353 record = SfaRecord(dict=record)
357 api.plshell.UpdateNode(api.plauth, pointer, new_record)
360 raise UnknownSfaType(type)
362 # update membership for researchers, pis, owners, operators
363 api.update_membership(record, new_record)
367 def remove(api, xrn, type, origin_hrn=None):
370 hrn = urn_to_hrn(xrn)[0]
372 hrn, type = urn_to_hrn(xrn)
375 filter = {'hrn': hrn}
376 if type and type not in ['all', '*']:
377 filter['type'] = type
378 records = table.find(filter)
380 raise RecordNotFound(hrn)
382 type = record['type']
384 credential = api.getCredential()
385 registries = api.registries
387 # Try to remove the object from the PLCDB of federated agg.
388 # This is attempted before removing the object from the local agg's PLCDB and sfa table
389 if hrn.startswith(api.hrn) and type in ['user', 'slice', 'authority']:
390 for registry in registries:
391 if registry not in [api.hrn]:
393 result=registries[registry].remove_peer_object(credential, record, origin_hrn)
397 persons = api.plshell.GetPersons(api.plauth, record['pointer'])
398 # only delete this person if he has site ids. if he doesnt, it probably means
399 # he was just removed from a site, not actually deleted
400 if persons and persons[0]['site_ids']:
401 api.plshell.DeletePerson(api.plauth, record['pointer'])
402 elif type == "slice":
403 if api.plshell.GetSlices(api.plauth, record['pointer']):
404 api.plshell.DeleteSlice(api.plauth, record['pointer'])
406 if api.plshell.GetNodes(api.plauth, record['pointer']):
407 api.plshell.DeleteNode(api.plauth, record['pointer'])
408 elif type == "authority":
409 if api.plshell.GetSites(api.plauth, record['pointer']):
410 api.plshell.DeleteSite(api.plauth, record['pointer'])
412 raise UnknownSfaType(type)
418 def remove_peer_object(api, record, origin_hrn=None):
421 def register_peer_object(api, record, origin_hrn=None):