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
16 from sfa.managers.aggregate_manager_pl import slice_status
18 # The GENI GetVersion call
20 peers =dict ([ (peername,v._ServerProxy__host) for (peername,v) in api.registries.items()
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 if not auth_hrn or hrn == api.config.SFA_INTERFACE_HRN:
40 auth_info = api.auth.get_auth_info(auth_hrn)
42 records = table.findObjects({'type': type, 'hrn': hrn})
44 raise RecordNotFound(hrn)
47 # verify_cancreate_credential requires that the member lists
48 # (researchers, pis, etc) be filled in
49 api.fill_record_info(record)
50 if record['type']=='user':
51 if not record['enabled']:
52 raise AccountNotEnabled(": PlanetLab account %s is not enabled. Please contact your site PI" %(record['email']))
55 # if this is a self cred the record's gid is the caller's gid
58 caller_gid = record.get_gid_object()
60 caller_gid = api.auth.client_cred.get_gid_caller()
61 caller_hrn = caller_gid.get_hrn()
63 object_hrn = record.get_gid_object().get_hrn()
64 rights = api.auth.determine_user_rights(caller_hrn, record)
65 # make sure caller has rights to this object
67 raise PermissionError(caller_hrn + " has no rights to " + record['name'])
69 object_gid = GID(string=record['gid'])
70 new_cred = Credential(subject = object_gid.get_subject())
71 new_cred.set_gid_caller(caller_gid)
72 new_cred.set_gid_object(object_gid)
73 new_cred.set_issuer_keys(auth_info.get_privkey_filename(), auth_info.get_gid_filename())
74 #new_cred.set_pubkey(object_gid.get_pubkey())
75 new_cred.set_privileges(rights)
76 new_cred.get_privileges().delegate_all_privileges(True)
77 if 'expires' in record:
78 new_cred.set_expiration(int(record['expires']))
79 auth_kind = "authority,ma,sa"
80 # Parent not necessary, verify with certs
81 #new_cred.set_parent(api.auth.hierarchy.get_auth_cred(auth_hrn, kind=auth_kind))
85 return new_cred.save_to_string(save_parents=True)
88 def resolve(api, xrns, type=None, full=True):
90 # load all know registry names into a prefix tree and attempt to find
91 # the longest matching prefix
92 if not isinstance(xrns, types.ListType):
94 type = Xrn(xrns).get_type()
96 hrns = [urn_to_hrn(xrn)[0] for xrn in xrns]
97 # create a dict whre key is an registry hrn and its value is a
98 # hrns at that registry (determined by the known prefix tree).
100 registries = api.registries
102 registry_hrns = registries.keys()
103 tree.load(registry_hrns)
105 registry_hrn = tree.best_match(urn_to_hrn(xrn)[0])
106 if registry_hrn not in xrn_dict:
107 xrn_dict[registry_hrn] = []
108 xrn_dict[registry_hrn].append(xrn)
111 for registry_hrn in xrn_dict:
112 # skip the hrn without a registry hrn
113 # XX should we let the user know the authority is unknown?
117 # if the best match (longest matching hrn) is not the local registry,
118 # forward the request
119 xrns = xrn_dict[registry_hrn]
120 if registry_hrn != api.hrn:
121 credential = api.getCredential()
122 peer_records = registries[registry_hrn].Resolve(xrns, credential)
123 records.extend([SfaRecord(dict=record).as_dict() for record in peer_records])
125 # try resolving the remaining unfound records at the local registry
126 remaining_hrns = set(hrns).difference([record['hrn'] for record in records])
127 # convert set to list
128 remaining_hrns = [hrn for hrn in remaining_hrns]
130 local_records = table.findObjects({'hrn': remaining_hrns})
132 api.fill_record_info(local_records)
134 # convert local record objects to dicts
135 records.extend([dict(record) for record in local_records])
137 raise RecordNotFound(str(hrns))
140 records = filter(lambda rec: rec['type'] in [type], records)
144 def list(api, xrn, origin_hrn=None):
145 hrn, type = urn_to_hrn(xrn)
146 # load all know registry names into a prefix tree and attempt to find
147 # the longest matching prefix
149 registries = api.registries
150 registry_hrns = registries.keys()
152 tree.load(registry_hrns)
153 registry_hrn = tree.best_match(hrn)
155 #if there was no match then this record belongs to an unknow registry
157 raise MissingAuthority(xrn)
159 # if the best match (longest matching hrn) is not the local registry,
160 # forward the request
162 if registry_hrn != api.hrn:
163 credential = api.getCredential()
164 record_list = registries[registry_hrn].List(xrn, credential)
165 records = [SfaRecord(dict=record).as_dict() for record in record_list]
167 # if we still have not found the record yet, try the local registry
169 if not api.auth.hierarchy.auth_exists(hrn):
170 raise MissingAuthority(hrn)
173 records = table.find({'authority': hrn})
178 def register(api, record):
180 hrn, type = record['hrn'], record['type']
181 urn = hrn_to_urn(hrn,type)
183 if type not in ['authority', 'slice', 'node', 'user']:
184 raise UnknownSfaType(type)
186 # check if record already exists
188 existing_records = table.find({'type': type, 'hrn': hrn})
190 raise ExistingRecord(hrn)
192 record = SfaRecord(dict = record)
193 record['authority'] = get_authority(record['hrn'])
194 type = record['type']
196 api.auth.verify_object_permission(hrn)
197 auth_info = api.auth.get_auth_info(record['authority'])
199 # make sure record has a gid
200 if 'gid' not in record:
202 pkey = Keypair(create=True)
203 if 'key' in record and record['key']:
204 if isinstance(record['key'], types.ListType):
205 pub_key = record['key'][0]
207 pub_key = record['key']
208 pkey = convert_public_key(pub_key)
210 gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey)
211 gid = gid_object.save_to_string(save_parents=True)
215 if type in ["authority"]:
217 if not api.auth.hierarchy.auth_exists(hrn):
218 api.auth.hierarchy.create_auth(hrn_to_urn(hrn,'authority'))
220 # get the GID from the newly created authority
221 gid = auth_info.get_gid_object()
222 record.set_gid(gid.save_to_string(save_parents=True))
223 pl_record = api.sfa_fields_to_pl_fields(type, hrn, record)
224 sites = api.plshell.GetSites(api.plauth, [pl_record['login_base']])
226 pointer = api.plshell.AddSite(api.plauth, pl_record)
228 pointer = sites[0]['site_id']
230 record.set_pointer(pointer)
231 record['pointer'] = pointer
233 elif (type == "slice"):
234 acceptable_fields=['url', 'instantiation', 'name', 'description']
235 pl_record = api.sfa_fields_to_pl_fields(type, hrn, record)
236 for key in pl_record.keys():
237 if key not in acceptable_fields:
239 slices = api.plshell.GetSlices(api.plauth, [pl_record['name']])
241 pointer = api.plshell.AddSlice(api.plauth, pl_record)
243 pointer = slices[0]['slice_id']
244 record.set_pointer(pointer)
245 record['pointer'] = pointer
247 elif (type == "user"):
248 persons = api.plshell.GetPersons(api.plauth, [record['email']])
250 pointer = api.plshell.AddPerson(api.plauth, dict(record))
252 pointer = persons[0]['person_id']
254 if 'enabled' in record and record['enabled']:
255 api.plshell.UpdatePerson(api.plauth, pointer, {'enabled': record['enabled']})
256 # add this persons to the site only if he is being added for the first
257 # time by sfa and doesont already exist in plc
258 if not persons or not persons[0]['site_ids']:
259 login_base = get_leaf(record['authority'])
260 api.plshell.AddPersonToSite(api.plauth, pointer, login_base)
262 # What roles should this user have?
263 api.plshell.AddRoleToPerson(api.plauth, 'user', pointer)
266 api.plshell.AddPersonKey(api.plauth, pointer, {'key_type' : 'ssh', 'key' : pub_key})
268 elif (type == "node"):
269 pl_record = api.sfa_fields_to_pl_fields(type, hrn, record)
270 login_base = hrn_to_pl_login_base(record['authority'])
271 nodes = api.plshell.GetNodes(api.plauth, [pl_record['hostname']])
273 pointer = api.plshell.AddNode(api.plauth, login_base, pl_record)
275 pointer = nodes[0]['node_id']
277 record['pointer'] = pointer
278 record.set_pointer(pointer)
279 record_id = table.insert(record)
280 record['record_id'] = record_id
282 # update membership for researchers, pis, owners, operators
283 api.update_membership(None, record)
285 return record.get_gid_object().save_to_string(save_parents=True)
287 def update(api, record_dict):
288 new_record = SfaRecord(dict = record_dict)
289 type = new_record['type']
290 hrn = new_record['hrn']
291 urn = hrn_to_urn(hrn,type)
292 api.auth.verify_object_permission(hrn)
294 # make sure the record exists
295 records = table.findObjects({'type': type, 'hrn': hrn})
297 raise RecordNotFound(hrn)
299 record['last_updated'] = time.gmtime()
301 # Update_membership needs the membership lists in the existing record
302 # filled in, so it can see if members were added or removed
303 api.fill_record_info(record)
305 # Use the pointer from the existing record, not the one that the user
306 # gave us. This prevents the user from inserting a forged pointer
307 pointer = record['pointer']
308 # update the PLC information that was specified with the record
310 if (type == "authority"):
311 api.plshell.UpdateSite(api.plauth, pointer, new_record)
313 elif type == "slice":
314 pl_record=api.sfa_fields_to_pl_fields(type, hrn, new_record)
315 if 'name' in pl_record:
316 pl_record.pop('name')
317 api.plshell.UpdateSlice(api.plauth, pointer, pl_record)
320 # SMBAKER: UpdatePerson only allows a limited set of fields to be
321 # updated. Ideally we should have a more generic way of doing
322 # this. I copied the field names from UpdatePerson.py...
324 all_fields = new_record
325 for key in all_fields.keys():
326 if key in ['first_name', 'last_name', 'title', 'email',
327 'password', 'phone', 'url', 'bio', 'accepted_aup',
329 update_fields[key] = all_fields[key]
330 api.plshell.UpdatePerson(api.plauth, pointer, update_fields)
332 if 'key' in new_record and new_record['key']:
333 # must check this key against the previous one if it exists
334 persons = api.plshell.GetPersons(api.plauth, [pointer], ['key_ids'])
336 keys = person['key_ids']
337 keys = api.plshell.GetKeys(api.plauth, person['key_ids'])
339 if isinstance(new_record['key'], types.ListType):
340 new_key = new_record['key'][0]
342 new_key = new_record['key']
344 # Delete all stale keys
346 if new_record['key'] != key['key']:
347 api.plshell.DeleteKey(api.plauth, key['key_id'])
351 api.plshell.AddPersonKey(api.plauth, pointer, {'key_type': 'ssh', 'key': new_key})
353 # update the openssl key and gid
354 pkey = convert_public_key(new_key)
356 gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey)
357 gid = gid_object.save_to_string(save_parents=True)
359 record = SfaRecord(dict=record)
363 api.plshell.UpdateNode(api.plauth, pointer, new_record)
366 raise UnknownSfaType(type)
368 # update membership for researchers, pis, owners, operators
369 api.update_membership(record, new_record)
373 # expecting an Xrn instance
374 def remove(api, xrn, origin_hrn=None):
377 filter = {'hrn': xrn.get_hrn()}
380 if type and type not in ['all', '*']:
381 filter['type'] = type
383 records = table.find(filter)
384 if not records: raise RecordNotFound(hrn)
386 type = record['type']
388 credential = api.getCredential()
389 registries = api.registries
391 # Try to remove the object from the PLCDB of federated agg.
392 # This is attempted before removing the object from the local agg's PLCDB and sfa table
393 if hrn.startswith(api.hrn) and type in ['user', 'slice', 'authority']:
394 for registry in registries:
395 if registry not in [api.hrn]:
397 result=registries[registry].remove_peer_object(credential, record, origin_hrn)
401 persons = api.plshell.GetPersons(api.plauth, record['pointer'])
402 # only delete this person if he has site ids. if he doesnt, it probably means
403 # he was just removed from a site, not actually deleted
404 if persons and persons[0]['site_ids']:
405 api.plshell.DeletePerson(api.plauth, record['pointer'])
406 elif type == "slice":
407 if api.plshell.GetSlices(api.plauth, record['pointer']):
408 api.plshell.DeleteSlice(api.plauth, record['pointer'])
410 if api.plshell.GetNodes(api.plauth, record['pointer']):
411 api.plshell.DeleteNode(api.plauth, record['pointer'])
412 elif type == "authority":
413 if api.plshell.GetSites(api.plauth, record['pointer']):
414 api.plshell.DeleteSite(api.plauth, record['pointer'])
416 raise UnknownSfaType(type)
422 def remove_peer_object(api, record, origin_hrn=None):
425 def register_peer_object(api, record, origin_hrn=None):