4 from sfa.util.faults import RecordNotFound, AccountNotEnabled, PermissionError, MissingAuthority, \
5 UnknownSfaType, ExistingRecord
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.xrn import Xrn, get_leaf, get_authority, hrn_to_urn, urn_to_hrn
10 from sfa.util.plxrn import hrn_to_pl_login_base
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
18 class RegistryManager:
20 def __init__ (self): pass
22 # The GENI GetVersion call
23 def GetVersion(self, api):
24 peers = dict ( [ (hrn,interface._ServerProxy__host) for (hrn,interface) in api.registries.iteritems()
27 return version_core({'interface':'registry',
32 def GetCredential(self, 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 if not auth_hrn or hrn == api.config.SFA_INTERFACE_HRN:
44 auth_info = api.auth.get_auth_info(auth_hrn)
46 records = table.findObjects({'type': type, 'hrn': hrn})
48 raise RecordNotFound(hrn)
51 # verify_cancreate_credential requires that the member lists
52 # (researchers, pis, etc) be filled in
53 api.driver.fill_record_info(record, api.aggregates)
54 if record['type']=='user':
55 if not record['enabled']:
56 raise AccountNotEnabled(": PlanetLab account %s is not enabled. Please contact your site PI" %(record['email']))
59 # if this is a self cred the record's gid is the caller's gid
62 caller_gid = record.get_gid_object()
64 caller_gid = api.auth.client_cred.get_gid_caller()
65 caller_hrn = caller_gid.get_hrn()
67 object_hrn = record.get_gid_object().get_hrn()
68 rights = api.auth.determine_user_rights(caller_hrn, record)
69 # make sure caller has rights to this object
71 raise PermissionError(caller_hrn + " has no rights to " + record['name'])
73 object_gid = GID(string=record['gid'])
74 new_cred = Credential(subject = object_gid.get_subject())
75 new_cred.set_gid_caller(caller_gid)
76 new_cred.set_gid_object(object_gid)
77 new_cred.set_issuer_keys(auth_info.get_privkey_filename(), auth_info.get_gid_filename())
78 #new_cred.set_pubkey(object_gid.get_pubkey())
79 new_cred.set_privileges(rights)
80 new_cred.get_privileges().delegate_all_privileges(True)
81 if 'expires' in record:
82 new_cred.set_expiration(int(record['expires']))
83 auth_kind = "authority,ma,sa"
84 # Parent not necessary, verify with certs
85 #new_cred.set_parent(api.auth.hierarchy.get_auth_cred(auth_hrn, kind=auth_kind))
89 return new_cred.save_to_string(save_parents=True)
92 def Resolve(self, api, xrns, type=None, full=True):
94 # load all known registry names into a prefix tree and attempt to find
95 # the longest matching prefix
96 if not isinstance(xrns, types.ListType):
98 type = Xrn(xrns).get_type()
100 hrns = [urn_to_hrn(xrn)[0] for xrn in xrns]
101 # create a dict where key is a registry hrn and its value is a
102 # hrns at that registry (determined by the known prefix tree).
104 registries = api.registries
106 registry_hrns = registries.keys()
107 tree.load(registry_hrns)
109 registry_hrn = tree.best_match(urn_to_hrn(xrn)[0])
110 if registry_hrn not in xrn_dict:
111 xrn_dict[registry_hrn] = []
112 xrn_dict[registry_hrn].append(xrn)
115 for registry_hrn in xrn_dict:
116 # skip the hrn without a registry hrn
117 # XX should we let the user know the authority is unknown?
121 # if the best match (longest matching hrn) is not the local registry,
122 # forward the request
123 xrns = xrn_dict[registry_hrn]
124 if registry_hrn != api.hrn:
125 credential = api.getCredential()
126 interface = api.registries[registry_hrn]
127 server = api.server_proxy(interface, credential)
128 peer_records = server.Resolve(xrns, credential)
129 records.extend([SfaRecord(dict=record).as_dict() for record in peer_records])
131 # try resolving the remaining unfound records at the local registry
132 remaining_hrns = set(hrns).difference([record['hrn'] for record in records])
133 # convert set to list
134 remaining_hrns = [hrn for hrn in remaining_hrns]
136 local_records = table.findObjects({'hrn': remaining_hrns})
138 api.driver.fill_record_info(local_records, api.aggregates)
140 # convert local record objects to dicts
141 records.extend([dict(record) for record in local_records])
143 raise RecordNotFound(str(hrns))
146 records = filter(lambda rec: rec['type'] in [type], records)
150 def List(self, api, xrn, origin_hrn=None):
151 hrn, type = urn_to_hrn(xrn)
152 # load all know registry names into a prefix tree and attempt to find
153 # the longest matching prefix
155 registries = api.registries
156 registry_hrns = registries.keys()
158 tree.load(registry_hrns)
159 registry_hrn = tree.best_match(hrn)
161 #if there was no match then this record belongs to an unknow registry
163 raise MissingAuthority(xrn)
164 # if the best match (longest matching hrn) is not the local registry,
165 # forward the request
167 if registry_hrn != api.hrn:
168 credential = api.getCredential()
169 interface = api.registries[registry_hrn]
170 server = api.server_proxy(interface, credential)
171 record_list = server.List(xrn, credential)
172 records = [SfaRecord(dict=record).as_dict() for record in record_list]
174 # if we still have not found the record yet, try the local registry
176 if not api.auth.hierarchy.auth_exists(hrn):
177 raise MissingAuthority(hrn)
180 records = table.find({'authority': hrn})
185 def CreateGid(self, api, xrn, cert):
187 authority = Xrn(xrn=xrn).get_authority_hrn()
188 auth_info = api.auth.get_auth_info(authority)
190 pkey = Keypair(create=True)
192 certificate = Certificate(string=cert)
193 pkey = certificate.get_pubkey()
194 gid = api.auth.hierarchy.create_gid(xrn, create_uuid(), pkey)
195 return gid.save_to_string(save_parents=True)
197 def Register(self, api, record):
199 hrn, type = record['hrn'], record['type']
200 urn = hrn_to_urn(hrn,type)
202 if type not in ['authority', 'slice', 'node', 'user']:
203 raise UnknownSfaType(type)
205 # check if record already exists
207 existing_records = table.find({'type': type, 'hrn': hrn})
209 raise ExistingRecord(hrn)
211 record = SfaRecord(dict = record)
212 record['authority'] = get_authority(record['hrn'])
213 type = record['type']
215 auth_info = api.auth.get_auth_info(record['authority'])
217 # make sure record has a gid
218 if 'gid' not in record:
220 pkey = Keypair(create=True)
221 if 'key' in record and record['key']:
222 if isinstance(record['key'], types.ListType):
223 pub_key = record['key'][0]
225 pub_key = record['key']
226 pkey = convert_public_key(pub_key)
228 gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey)
229 gid = gid_object.save_to_string(save_parents=True)
233 if type in ["authority"]:
235 if not api.auth.hierarchy.auth_exists(hrn):
236 api.auth.hierarchy.create_auth(hrn_to_urn(hrn,'authority'))
238 # get the GID from the newly created authority
239 gid = auth_info.get_gid_object()
240 record.set_gid(gid.save_to_string(save_parents=True))
241 pl_record = api.driver.sfa_fields_to_pl_fields(type, hrn, record)
242 sites = api.driver.GetSites([pl_record['login_base']])
244 pointer = api.driver.AddSite(pl_record)
246 pointer = sites[0]['site_id']
248 record.set_pointer(pointer)
249 record['pointer'] = pointer
251 elif (type == "slice"):
252 acceptable_fields=['url', 'instantiation', 'name', 'description']
253 pl_record = api.driver.sfa_fields_to_pl_fields(type, hrn, record)
254 for key in pl_record.keys():
255 if key not in acceptable_fields:
257 slices = api.driver.GetSlices([pl_record['name']])
259 pointer = api.driver.AddSlice(pl_record)
261 pointer = slices[0]['slice_id']
262 record.set_pointer(pointer)
263 record['pointer'] = pointer
265 elif (type == "user"):
266 persons = api.driver.GetPersons([record['email']])
268 pointer = api.driver.AddPerson(dict(record))
270 pointer = persons[0]['person_id']
272 if 'enabled' in record and record['enabled']:
273 api.driver.UpdatePerson(pointer, {'enabled': record['enabled']})
274 # add this persons to the site only if he is being added for the first
275 # time by sfa and doesont already exist in plc
276 if not persons or not persons[0]['site_ids']:
277 login_base = get_leaf(record['authority'])
278 api.driver.AddPersonToSite(pointer, login_base)
280 # What roles should this user have?
281 api.driver.AddRoleToPerson('user', pointer)
284 api.driver.AddPersonKey(pointer, {'key_type' : 'ssh', 'key' : pub_key})
286 elif (type == "node"):
287 pl_record = api.driver.sfa_fields_to_pl_fields(type, hrn, record)
288 login_base = hrn_to_pl_login_base(record['authority'])
289 nodes = api.driver.GetNodes([pl_record['hostname']])
291 pointer = api.driver.AddNode(login_base, pl_record)
293 pointer = nodes[0]['node_id']
295 record['pointer'] = pointer
296 record.set_pointer(pointer)
297 record_id = table.insert(record)
298 record['record_id'] = record_id
300 # update membership for researchers, pis, owners, operators
301 api.driver.update_membership(None, record)
303 return record.get_gid_object().save_to_string(save_parents=True)
305 def Update(self, api, record_dict):
306 new_record = SfaRecord(dict = record_dict)
307 type = new_record['type']
308 hrn = new_record['hrn']
309 urn = hrn_to_urn(hrn,type)
311 # make sure the record exists
312 records = table.findObjects({'type': type, 'hrn': hrn})
314 raise RecordNotFound(hrn)
316 record['last_updated'] = time.gmtime()
318 # Update_membership needs the membership lists in the existing record
319 # filled in, so it can see if members were added or removed
320 api.driver.fill_record_info(record, api.aggregates)
322 # Use the pointer from the existing record, not the one that the user
323 # gave us. This prevents the user from inserting a forged pointer
324 pointer = record['pointer']
325 # update the PLC information that was specified with the record
327 if (type == "authority"):
328 api.driver.UpdateSite(pointer, new_record)
330 elif type == "slice":
331 pl_record=api.driver.sfa_fields_to_pl_fields(type, hrn, new_record)
332 if 'name' in pl_record:
333 pl_record.pop('name')
334 api.driver.UpdateSlice(pointer, pl_record)
337 # SMBAKER: UpdatePerson only allows a limited set of fields to be
338 # updated. Ideally we should have a more generic way of doing
339 # this. I copied the field names from UpdatePerson.py...
341 all_fields = new_record
342 for key in all_fields.keys():
343 if key in ['first_name', 'last_name', 'title', 'email',
344 'password', 'phone', 'url', 'bio', 'accepted_aup',
346 update_fields[key] = all_fields[key]
347 api.driver.UpdatePerson(pointer, update_fields)
349 if 'key' in new_record and new_record['key']:
350 # must check this key against the previous one if it exists
351 persons = api.driver.GetPersons([pointer], ['key_ids'])
353 keys = person['key_ids']
354 keys = api.driver.GetKeys(person['key_ids'])
356 if isinstance(new_record['key'], types.ListType):
357 new_key = new_record['key'][0]
359 new_key = new_record['key']
361 # Delete all stale keys
363 if new_record['key'] != key['key']:
364 api.driver.DeleteKey(key['key_id'])
368 api.driver.AddPersonKey(pointer, {'key_type': 'ssh', 'key': new_key})
370 # update the openssl key and gid
371 pkey = convert_public_key(new_key)
373 gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey)
374 gid = gid_object.save_to_string(save_parents=True)
376 record = SfaRecord(dict=record)
380 api.driver.UpdateNode(pointer, new_record)
383 raise UnknownSfaType(type)
385 # update membership for researchers, pis, owners, operators
386 api.driver.update_membership(record, new_record)
390 # expecting an Xrn instance
391 def Remove(self, api, xrn, origin_hrn=None):
394 filter = {'hrn': xrn.get_hrn()}
397 if type and type not in ['all', '*']:
398 filter['type'] = type
400 records = table.find(filter)
401 if not records: raise RecordNotFound(hrn)
403 type = record['type']
405 credential = api.getCredential()
406 registries = api.registries
408 # Try to remove the object from the PLCDB of federated agg.
409 # This is attempted before removing the object from the local agg's PLCDB and sfa table
410 if hrn.startswith(api.hrn) and type in ['user', 'slice', 'authority']:
411 for registry in registries:
412 if registry not in [api.hrn]:
414 result=registries[registry].remove_peer_object(credential, record, origin_hrn)
418 persons = api.driver.GetPersons(record['pointer'])
419 # only delete this person if he has site ids. if he doesnt, it probably means
420 # he was just removed from a site, not actually deleted
421 if persons and persons[0]['site_ids']:
422 api.driver.DeletePerson(record['pointer'])
423 elif type == "slice":
424 if api.driver.GetSlices(record['pointer']):
425 api.driver.DeleteSlice(record['pointer'])
427 if api.driver.GetNodes(record['pointer']):
428 api.driver.DeleteNode(record['pointer'])
429 elif type == "authority":
430 if api.driver.GetSites(record['pointer']):
431 api.driver.DeleteSite(record['pointer'])
433 raise UnknownSfaType(type)