2 from datetime import datetime
3 # for get_key_from_incoming_ip
8 from sfa.util.faults import RecordNotFound, AccountNotEnabled, PermissionError, MissingAuthority, \
9 UnknownSfaType, ExistingRecord, NonExistingRecord
10 from sfa.util.sfatime import utcparse, datetime_to_epoch
11 from sfa.util.prefixTree import prefixTree
12 from sfa.util.xrn import Xrn, get_authority, hrn_to_urn, urn_to_hrn
13 from sfa.util.plxrn import hrn_to_pl_login_base
14 from sfa.util.version import version_core
15 from sfa.util.sfalogging import logger
17 from sfa.trust.gid import GID
18 from sfa.trust.credential import Credential
19 from sfa.trust.certificate import Certificate, Keypair, convert_public_key
20 from sfa.trust.gid import create_uuid
22 from sfa.storage.persistentobjs import RegRecord
23 from sfa.storage.alchemy import dbsession
25 class RegistryManager:
27 def __init__ (self, config): pass
29 # The GENI GetVersion call
30 def GetVersion(self, api, options):
31 peers = dict ( [ (hrn,interface.get_url()) for (hrn,interface) in api.registries.iteritems()
34 return version_core({'interface':'registry',
41 def GetCredential(self, api, xrn, type, is_self=False):
44 hrn = urn_to_hrn(xrn)[0]
46 hrn, type = urn_to_hrn(xrn)
48 # Is this a root or sub authority
49 auth_hrn = api.auth.get_authority(hrn)
50 if not auth_hrn or hrn == api.config.SFA_INTERFACE_HRN:
52 auth_info = api.auth.get_auth_info(auth_hrn)
54 record=dbsession.query(RegRecord).filter_by(type=type,hrn=hrn).first()
56 raise RecordNotFound(hrn)
58 # verify_cancreate_credential requires that the member lists
59 # (researchers, pis, etc) be filled in
60 logger.debug("get credential before augment dict, keys=%s"%record.__dict__.keys())
61 self.driver.augment_records_with_testbed_info (record.__dict__)
62 logger.debug("get credential after augment dict, keys=%s"%record.__dict__.keys())
63 if not self.driver.is_enabled (record.__dict__):
64 raise AccountNotEnabled(": PlanetLab account %s is not enabled. Please contact your site PI" %(record.email))
67 # if this is a self cred the record's gid is the caller's gid
70 caller_gid = record.get_gid_object()
72 caller_gid = api.auth.client_cred.get_gid_caller()
73 caller_hrn = caller_gid.get_hrn()
75 object_hrn = record.get_gid_object().get_hrn()
76 rights = api.auth.determine_user_rights(caller_hrn, record.__dict__)
77 # make sure caller has rights to this object
79 raise PermissionError(caller_hrn + " has no rights to " + record.hrn)
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 hasattr(record,'expires'):
90 date = utcparse(record.expires)
91 expires = datetime_to_epoch(date)
92 new_cred.set_expiration(int(expires))
93 auth_kind = "authority,ma,sa"
94 # Parent not necessary, verify with certs
95 #new_cred.set_parent(api.auth.hierarchy.get_auth_cred(auth_hrn, kind=auth_kind))
99 return new_cred.save_to_string(save_parents=True)
102 def Resolve(self, api, xrns, intype=None, full=True):
104 if not isinstance(xrns, types.ListType):
106 # try to infer type if not set and we get a single input
108 intype = Xrn(xrns).get_type()
109 hrns = [urn_to_hrn(xrn)[0] for xrn in xrns]
111 # load all known registry names into a prefix tree and attempt to find
112 # the longest matching prefix
113 # create a dict where key is a registry hrn and its value is a list
114 # of hrns at that registry (determined by the known prefix tree).
116 registries = api.registries
118 registry_hrns = registries.keys()
119 tree.load(registry_hrns)
121 registry_hrn = tree.best_match(urn_to_hrn(xrn)[0])
122 if registry_hrn not in xrn_dict:
123 xrn_dict[registry_hrn] = []
124 xrn_dict[registry_hrn].append(xrn)
127 for registry_hrn in xrn_dict:
128 # skip the hrn without a registry hrn
129 # XX should we let the user know the authority is unknown?
133 # if the best match (longest matching hrn) is not the local registry,
134 # forward the request
135 xrns = xrn_dict[registry_hrn]
136 if registry_hrn != api.hrn:
137 credential = api.getCredential()
138 interface = api.registries[registry_hrn]
139 server_proxy = api.server_proxy(interface, credential)
140 peer_records = server_proxy.Resolve(xrns, credential,intype)
141 # pass foreign records as-is
142 records.extend(peer_records)
144 # try resolving the remaining unfound records at the local registry
145 local_hrns = list ( set(hrns).difference([record['hrn'] for record in records]) )
147 local_records = dbsession.query(RegRecord).filter(RegRecord.hrn.in_(local_hrns))
149 local_records = local_records.filter_by(type=intype)
150 local_records=local_records.all()
151 local_dicts = [ record.__dict__ for record in local_records ]
154 # in full mode we get as much info as we can, which involves contacting the
155 # testbed for getting implementation details about the record
156 for record in local_dicts: logger.info("resolve augment %s"%record)
157 self.driver.augment_records_with_testbed_info(local_dicts)
158 # # also we fill the 'url' field for known authorities
159 # # used to be in the driver code, sounds like a poorman thing though
160 def solve_neighbour_url (record):
161 if not record.type.startswith('authority'): return
163 for neighbour_dict in [ api.aggregates, api.registries ]:
164 if hrn in neighbour_dict:
165 record.url=neighbour_dict[hrn].get_url()
167 for record in local_records: solve_neighbour_url (record)
169 # convert local record objects to dicts for xmlrpc
170 # xxx somehow here calling dict(record) issues a weird error
171 # however record.todict() seems to work fine
172 # records.extend( [ dict(record) for record in local_records ] )
173 records.extend( [ record.todict() for record in local_records ] )
175 raise RecordNotFound(str(hrns))
179 def List (self, api, xrn, origin_hrn=None):
180 hrn, type = urn_to_hrn(xrn)
181 # load all know registry names into a prefix tree and attempt to find
182 # the longest matching prefix
183 registries = api.registries
184 registry_hrns = registries.keys()
186 tree.load(registry_hrns)
187 registry_hrn = tree.best_match(hrn)
189 #if there was no match then this record belongs to an unknow registry
191 raise MissingAuthority(xrn)
192 # if the best match (longest matching hrn) is not the local registry,
193 # forward the request
195 if registry_hrn != api.hrn:
196 credential = api.getCredential()
197 interface = api.registries[registry_hrn]
198 server_proxy = api.server_proxy(interface, credential)
199 record_list = server_proxy.List(xrn, credential)
200 # pass foreign records as-is
201 record_dicts = record_list
203 # if we still have not found the record yet, try the local registry
205 if not api.auth.hierarchy.auth_exists(hrn):
206 raise MissingAuthority(hrn)
207 records = dbsession.query(RegRecord).filter_by(authority=hrn)
208 record_dicts=[ record.__dict__ for record in records ]
213 def CreateGid(self, api, xrn, cert):
215 authority = Xrn(xrn=xrn).get_authority_hrn()
216 auth_info = api.auth.get_auth_info(authority)
218 pkey = Keypair(create=True)
220 certificate = Certificate(string=cert)
221 pkey = certificate.get_pubkey()
222 gid = api.auth.hierarchy.create_gid(xrn, create_uuid(), pkey)
223 return gid.save_to_string(save_parents=True)
226 # utility for handling relationships among the SFA objects
227 # given that the SFA db does not handle this sort of relationsships
228 # it will rely on side-effects in the testbed to keep this persistent
230 # subject_record describes the subject of the relationships
231 # ref_record contains the target values for the various relationships we need to manage
232 # (to begin with, this is just the slice x person relationship)
233 def update_relations (self, subject_obj, ref_obj):
234 type=subject_obj.type
236 self.update_relation(subject_obj, 'researcher', ref_obj.researcher, 'user')
238 # field_key is the name of one field in the record, typically 'researcher' for a 'slice' record
239 # hrns is the list of hrns that should be linked to the subject from now on
240 # target_type would be e.g. 'user' in the 'slice' x 'researcher' example
241 def update_relation (self, record_obj, field_key, hrns, target_type):
242 # locate the linked objects in our db
243 subject_type=record_obj.type
244 subject_id=record_obj.pointer
245 # get the 'pointer' field of all matching records
246 link_id_tuples = dbsession.query(RegRecord.pointer).filter_by(type=target_type).filter(RegRecord.hrn.in_(hrns)).all()
247 # sqlalchemy returns named tuples for columns
248 link_ids = [ tuple.pointer for tuple in link_id_tuples ]
249 self.driver.update_relation (subject_type, target_type, subject_id, link_ids)
251 def Register(self, api, record_dict):
253 hrn, type = record_dict['hrn'], record_dict['type']
254 urn = hrn_to_urn(hrn,type)
256 if type not in ['authority', 'slice', 'node', 'user']:
257 raise UnknownSfaType(type)
259 # check if record_dict already exists
260 existing_records = dbsession.query(RegRecord).filter_by(type=type,hrn=hrn).all()
262 raise ExistingRecord(hrn)
264 assert ('type' in record_dict)
265 record = RegRecord("undefined")
266 record.set_from_dict(record_dict)
268 record.date_created=now
269 record.last_updated=now
270 record.authority = get_authority(record.hrn)
271 auth_info = api.auth.get_auth_info(record.authority)
273 # make sure record has a gid
276 pkey = Keypair(create=True)
277 if getattr(record,'keys',None):
279 # use only first key in record
280 if isinstance(record.keys, types.ListType):
281 pub_key = record.keys[0]
282 pkey = convert_public_key(pub_key)
284 gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey)
285 gid = gid_object.save_to_string(save_parents=True)
288 if type in ["authority"]:
290 if not api.auth.hierarchy.auth_exists(hrn):
291 api.auth.hierarchy.create_auth(hrn_to_urn(hrn,'authority'))
293 # get the GID from the newly created authority
294 gid = auth_info.get_gid_object()
295 record.gid=gid.save_to_string(save_parents=True)
297 # update testbed-specific data if needed
298 pointer = self.driver.register (record.__dict__, hrn, pub_key)
300 record.pointer=pointer
301 dbsession.add(record)
304 # update membership for researchers, pis, owners, operators
305 self.update_relations (record, record)
307 return record.get_gid_object().save_to_string(save_parents=True)
309 def Update(self, api, record_dict):
310 assert ('type' in record_dict)
311 new_record=RegRecord(type="unknown")
312 new_record.set_from_dict(record_dict)
313 type = new_record.type
316 # make sure the record exists
317 record = dbsession.query(RegRecord).filter_by(type=type,hrn=hrn).first()
319 raise RecordNotFound(hrn)
321 record.last_updated=now
324 # xxx might be simpler to just try to commit as this is a constraint in the db
325 if type not in ['authority', 'slice', 'node', 'user']:
326 raise UnknownSfaType(type)
328 # Use the pointer from the existing record, not the one that the user
329 # gave us. This prevents the user from inserting a forged pointer
330 pointer = record.pointer
332 # is the a change in keys ?
335 if getattr(new_key,'keys',None):
336 new_key=new_record.keys
337 if isinstance (new_key,types.ListType):
340 # update the PLC information that was specified with the record
341 if not self.driver.update (record.__dict__, new_record.__dict__, hrn, new_key):
342 logger.warning("driver.update failed")
344 # take new_key into account
346 # update the openssl key and gid
347 pkey = convert_public_key(new_key)
349 urn = hrn_to_urn(hrn,type)
350 gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey)
351 gid = gid_object.save_to_string(save_parents=True)
355 # update membership for researchers, pis, owners, operators
356 self.update_relations (record, new_record)
360 # expecting an Xrn instance
361 def Remove(self, api, xrn, origin_hrn=None):
364 filter = {'hrn': xrn.get_hrn()}
367 if type and type not in ['all', '*']:
368 filter['type'] = type
370 records = table.find(filter)
371 if not records: raise RecordNotFound(hrn)
373 type = record['type']
375 if type not in ['slice', 'user', 'node', 'authority'] :
376 raise UnknownSfaType(type)
378 credential = api.getCredential()
379 registries = api.registries
381 # Try to remove the object from the PLCDB of federated agg.
382 # This is attempted before removing the object from the local agg's PLCDB and sfa table
383 if hrn.startswith(api.hrn) and type in ['user', 'slice', 'authority']:
384 for registry in registries:
385 if registry not in [api.hrn]:
387 result=registries[registry].remove_peer_object(credential, record, origin_hrn)
391 # call testbed callback first
392 # IIUC this is done on the local testbed TOO because of the refreshpeer link
393 if not self.driver.remove(record):
394 logger.warning("driver.remove failed")
401 # This is a PLC-specific thing...
402 def get_key_from_incoming_ip (self, api):
403 # verify that the callers's ip address exist in the db and is an interface
404 # for a node in the db
405 (ip, port) = api.remote_addr
406 interfaces = self.driver.shell.GetInterfaces({'ip': ip}, ['node_id'])
408 raise NonExistingRecord("no such ip %(ip)s" % locals())
409 nodes = self.driver.shell.GetNodes([interfaces[0]['node_id']], ['node_id', 'hostname'])
411 raise NonExistingRecord("no such node using ip %(ip)s" % locals())
414 # look up the sfa record
416 records = table.findObjects({'type': 'node', 'pointer': node['node_id']})
418 raise RecordNotFound("pointer:" + str(node['node_id']))
421 # generate a new keypair and gid
423 pkey = Keypair(create=True)
424 urn = hrn_to_urn(record['hrn'], record['type'])
425 gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey)
426 gid = gid_object.save_to_string(save_parents=True)
433 # attempt the scp the key
434 # and gid onto the node
435 # this will only work for planetlab based components
436 (kfd, key_filename) = tempfile.mkstemp()
437 (gfd, gid_filename) = tempfile.mkstemp()
438 pkey.save_to_file(key_filename)
439 gid_object.save_to_file(gid_filename, save_parents=True)
440 host = node['hostname']
441 key_dest="/etc/sfa/node.key"
442 gid_dest="/etc/sfa/node.gid"
444 #identity = "/etc/planetlab/root_ssh_key.rsa"
445 identity = "/etc/sfa/root_ssh_key"
446 scp_options=" -i %(identity)s " % locals()
447 scp_options+="-o StrictHostKeyChecking=no " % locals()
448 scp_key_command="%(scp)s %(scp_options)s %(key_filename)s root@%(host)s:%(key_dest)s" %\
450 scp_gid_command="%(scp)s %(scp_options)s %(gid_filename)s root@%(host)s:%(gid_dest)s" %\
453 all_commands = [scp_key_command, scp_gid_command]
455 for command in all_commands:
456 (status, output) = commands.getstatusoutput(command)
458 raise Exception, output
460 for filename in [key_filename, gid_filename]: