2 # for get_key_from_incoming_ip
7 from sfa.util.faults import RecordNotFound, AccountNotEnabled, PermissionError, MissingAuthority, \
8 UnknownSfaType, ExistingRecord, NonExistingRecord
9 from sfa.util.sfatime import utcparse, datetime_to_epoch
10 from sfa.util.prefixTree import prefixTree
11 from sfa.util.xrn import Xrn, get_authority, hrn_to_urn, urn_to_hrn
12 from sfa.util.plxrn import hrn_to_pl_login_base
13 from sfa.util.version import version_core
14 from sfa.util.sfalogging import logger
16 from sfa.trust.gid import GID
17 from sfa.trust.credential import Credential
18 from sfa.trust.certificate import Certificate, Keypair, convert_public_key
19 from sfa.trust.gid import create_uuid
21 from sfa.storage.persistentobjs import make_record,RegRecord
22 from sfa.storage.alchemy import dbsession
24 class RegistryManager:
26 def __init__ (self, config): pass
28 # The GENI GetVersion call
29 def GetVersion(self, api, options):
30 peers = dict ( [ (hrn,interface.get_url()) for (hrn,interface) in api.registries.iteritems()
33 return version_core({'interface':'registry',
40 def GetCredential(self, api, xrn, type, is_self=False):
43 hrn = urn_to_hrn(xrn)[0]
45 hrn, type = urn_to_hrn(xrn)
47 # Is this a root or sub authority
48 auth_hrn = api.auth.get_authority(hrn)
49 if not auth_hrn or hrn == api.config.SFA_INTERFACE_HRN:
51 auth_info = api.auth.get_auth_info(auth_hrn)
53 record=dbsession.query(RegRecord).filter_by(type=type,hrn=hrn).first()
55 raise RecordNotFound("hrn=%s, type=%s"%(hrn,type))
57 # verify_cancreate_credential requires that the member lists
58 # (researchers, pis, etc) be filled in
59 logger.debug("get credential before augment dict, keys=%s"%record.__dict__.keys())
60 self.driver.augment_records_with_testbed_info (record.__dict__)
61 logger.debug("get credential after augment dict, keys=%s"%record.__dict__.keys())
62 if not self.driver.is_enabled (record.__dict__):
63 raise AccountNotEnabled(": PlanetLab account %s is not enabled. Please contact your site PI" %(record.email))
66 # if this is a self cred the record's gid is the caller's gid
69 caller_gid = record.get_gid_object()
71 caller_gid = api.auth.client_cred.get_gid_caller()
72 caller_hrn = caller_gid.get_hrn()
74 object_hrn = record.get_gid_object().get_hrn()
75 rights = api.auth.determine_user_rights(caller_hrn, record.__dict__)
76 # make sure caller has rights to this object
78 raise PermissionError(caller_hrn + " has no rights to " + record.hrn)
80 object_gid = GID(string=record.gid)
81 new_cred = Credential(subject = object_gid.get_subject())
82 new_cred.set_gid_caller(caller_gid)
83 new_cred.set_gid_object(object_gid)
84 new_cred.set_issuer_keys(auth_info.get_privkey_filename(), auth_info.get_gid_filename())
85 #new_cred.set_pubkey(object_gid.get_pubkey())
86 new_cred.set_privileges(rights)
87 new_cred.get_privileges().delegate_all_privileges(True)
88 if hasattr(record,'expires'):
89 date = utcparse(record.expires)
90 expires = datetime_to_epoch(date)
91 new_cred.set_expiration(int(expires))
92 auth_kind = "authority,ma,sa"
93 # Parent not necessary, verify with certs
94 #new_cred.set_parent(api.auth.hierarchy.get_auth_cred(auth_hrn, kind=auth_kind))
98 return new_cred.save_to_string(save_parents=True)
101 def Resolve(self, api, xrns, intype=None, full=True):
103 if not isinstance(xrns, types.ListType):
105 # try to infer type if not set and we get a single input
107 intype = Xrn(xrns).get_type()
108 hrns = [urn_to_hrn(xrn)[0] for xrn in xrns]
110 # load all known registry names into a prefix tree and attempt to find
111 # the longest matching prefix
112 # create a dict where key is a registry hrn and its value is a list
113 # of hrns at that registry (determined by the known prefix tree).
115 registries = api.registries
117 registry_hrns = registries.keys()
118 tree.load(registry_hrns)
120 registry_hrn = tree.best_match(urn_to_hrn(xrn)[0])
121 if registry_hrn not in xrn_dict:
122 xrn_dict[registry_hrn] = []
123 xrn_dict[registry_hrn].append(xrn)
126 for registry_hrn in xrn_dict:
127 # skip the hrn without a registry hrn
128 # XX should we let the user know the authority is unknown?
132 # if the best match (longest matching hrn) is not the local registry,
133 # forward the request
134 xrns = xrn_dict[registry_hrn]
135 if registry_hrn != api.hrn:
136 credential = api.getCredential()
137 interface = api.registries[registry_hrn]
138 server_proxy = api.server_proxy(interface, credential)
139 peer_records = server_proxy.Resolve(xrns, credential,intype)
140 # pass foreign records as-is
141 records.extend(peer_records)
143 # try resolving the remaining unfound records at the local registry
144 local_hrns = list ( set(hrns).difference([record['hrn'] for record in records]) )
145 logger.info("Resolve: local_hrns=%s"%local_hrns)
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 logger.info("Resolve: local_records=%s (intype=%s)"%(local_records,intype))
152 local_dicts = [ record.__dict__ for record in local_records ]
155 # in full mode we get as much info as we can, which involves contacting the
156 # testbed for getting implementation details about the record
157 for record in local_dicts: logger.debug("resolve augment %s"%record)
158 self.driver.augment_records_with_testbed_info(local_dicts)
159 # # also we fill the 'url' field for known authorities
160 # # used to be in the driver code, sounds like a poorman thing though
161 def solve_neighbour_url (record):
162 if not record.type.startswith('authority'): return
164 for neighbour_dict in [ api.aggregates, api.registries ]:
165 if hrn in neighbour_dict:
166 record.url=neighbour_dict[hrn].get_url()
168 for record in local_records: solve_neighbour_url (record)
170 # convert local record objects to dicts for xmlrpc
171 # xxx somehow here calling dict(record) issues a weird error
172 # however record.todict() seems to work fine
173 # records.extend( [ dict(record) for record in local_records ] )
174 records.extend( [ record.todict() for record in local_records ] )
176 raise RecordNotFound(str(hrns))
180 def List (self, api, xrn, origin_hrn=None):
181 hrn, type = urn_to_hrn(xrn)
182 # load all know registry names into a prefix tree and attempt to find
183 # the longest matching prefix
184 registries = api.registries
185 registry_hrns = registries.keys()
187 tree.load(registry_hrns)
188 registry_hrn = tree.best_match(hrn)
190 #if there was no match then this record belongs to an unknow registry
192 raise MissingAuthority(xrn)
193 # if the best match (longest matching hrn) is not the local registry,
194 # forward the request
196 if registry_hrn != api.hrn:
197 credential = api.getCredential()
198 interface = api.registries[registry_hrn]
199 server_proxy = api.server_proxy(interface, credential)
200 record_list = server_proxy.List(xrn, credential)
201 # pass foreign records as-is
202 record_dicts = record_list
204 # if we still have not found the record yet, try the local registry
206 if not api.auth.hierarchy.auth_exists(hrn):
207 raise MissingAuthority(hrn)
208 records = dbsession.query(RegRecord).filter_by(authority=hrn)
209 record_dicts=[ record.todict() for record in records ]
214 def CreateGid(self, api, xrn, cert):
216 authority = Xrn(xrn=xrn).get_authority_hrn()
217 auth_info = api.auth.get_auth_info(authority)
219 pkey = Keypair(create=True)
221 certificate = Certificate(string=cert)
222 pkey = certificate.get_pubkey()
223 gid = api.auth.hierarchy.create_gid(xrn, create_uuid(), pkey)
224 return gid.save_to_string(save_parents=True)
227 # utility for handling relationships among the SFA objects
228 # given that the SFA db does not handle this sort of relationsships
229 # it will rely on side-effects in the testbed to keep this persistent
231 # subject_record describes the subject of the relationships
232 # ref_record contains the target values for the various relationships we need to manage
233 # (to begin with, this is just the slice x person relationship)
234 def update_relations (self, subject_obj, ref_obj):
235 type=subject_obj.type
237 self.update_relation(subject_obj, 'researcher', ref_obj.researcher, 'user')
239 # field_key is the name of one field in the record, typically 'researcher' for a 'slice' record
240 # hrns is the list of hrns that should be linked to the subject from now on
241 # target_type would be e.g. 'user' in the 'slice' x 'researcher' example
242 def update_relation (self, record_obj, field_key, hrns, target_type):
243 # locate the linked objects in our db
244 subject_type=record_obj.type
245 subject_id=record_obj.pointer
246 # get the 'pointer' field of all matching records
247 link_id_tuples = dbsession.query(RegRecord.pointer).filter_by(type=target_type).filter(RegRecord.hrn.in_(hrns)).all()
248 # sqlalchemy returns named tuples for columns
249 link_ids = [ tuple.pointer for tuple in link_id_tuples ]
250 self.driver.update_relation (subject_type, target_type, subject_id, link_ids)
252 def Register(self, api, record_dict):
254 hrn, type = record_dict['hrn'], record_dict['type']
255 urn = hrn_to_urn(hrn,type)
257 if type not in ['authority', 'slice', 'node', 'user']:
258 raise UnknownSfaType(type)
260 # check if record_dict already exists
261 existing_records = dbsession.query(RegRecord).filter_by(type=type,hrn=hrn).all()
263 raise ExistingRecord(hrn)
265 assert ('type' in record_dict)
266 # returns the right type of RegRecord according to type in record
267 record = make_record(record_dict)
268 record.just_created()
269 record.authority = get_authority(record.hrn)
270 auth_info = api.auth.get_auth_info(record.authority)
272 # make sure record has a gid
275 pkey = Keypair(create=True)
276 if getattr(record,'keys',None):
278 # use only first key in record
279 if isinstance(record.keys, types.ListType):
280 pub_key = record.keys[0]
281 pkey = convert_public_key(pub_key)
283 gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey)
284 gid = gid_object.save_to_string(save_parents=True)
287 if type in ["authority"]:
289 if not api.auth.hierarchy.auth_exists(hrn):
290 api.auth.hierarchy.create_auth(hrn_to_urn(hrn,'authority'))
292 # get the GID from the newly created authority
293 gid = auth_info.get_gid_object()
294 record.gid=gid.save_to_string(save_parents=True)
296 # update testbed-specific data if needed
297 pointer = self.driver.register (record.__dict__, hrn, pub_key)
299 record.pointer=pointer
300 dbsession.add(record)
303 # update membership for researchers, pis, owners, operators
304 self.update_relations (record, record)
306 return record.get_gid_object().save_to_string(save_parents=True)
308 def Update(self, api, record_dict):
309 assert ('type' in record_dict)
310 new_record=RegRecord(dict=record_dict)
311 type = new_record.type
314 # make sure the record exists
315 record = dbsession.query(RegRecord).filter_by(type=type,hrn=hrn).first()
317 raise RecordNotFound("hrn=%s, type=%s"%(hrn,type))
318 record.just_updated()
321 # xxx might be simpler to just try to commit as this is a constraint in the db
322 if type not in ['authority', 'slice', 'node', 'user']:
323 raise UnknownSfaType(type)
325 # Use the pointer from the existing record, not the one that the user
326 # gave us. This prevents the user from inserting a forged pointer
327 pointer = record.pointer
329 # is the a change in keys ?
332 if getattr(new_key,'keys',None):
333 new_key=new_record.keys
334 if isinstance (new_key,types.ListType):
337 # update the PLC information that was specified with the record
338 if not self.driver.update (record.__dict__, new_record.__dict__, hrn, new_key):
339 logger.warning("driver.update failed")
341 # take new_key into account
343 # update the openssl key and gid
344 pkey = convert_public_key(new_key)
346 urn = hrn_to_urn(hrn,type)
347 gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey)
348 gid = gid_object.save_to_string(save_parents=True)
352 # update membership for researchers, pis, owners, operators
353 self.update_relations (record, new_record)
357 # expecting an Xrn instance
358 def Remove(self, api, xrn, origin_hrn=None):
361 request=dbsession.query(RegRecord).filter_by(hrn=hrn)
362 if type and type not in ['all', '*']:
363 request=request.filter_by(type=type)
365 record = request.first()
367 msg="Could not find hrn %s"%hrn
368 if type: msg += " type=%s"%type
369 raise RecordNotFound(msg)
372 credential = api.getCredential()
373 registries = api.registries
375 # Try to remove the object from the PLCDB of federated agg.
376 # This is attempted before removing the object from the local agg's PLCDB and sfa table
377 if hrn.startswith(api.hrn) and type in ['user', 'slice', 'authority']:
378 for registry in registries:
379 if registry not in [api.hrn]:
381 result=registries[registry].remove_peer_object(credential, record, origin_hrn)
385 # call testbed callback first
386 # IIUC this is done on the local testbed TOO because of the refreshpeer link
387 if not self.driver.remove(record.__dict__):
388 logger.warning("driver.remove failed")
391 dbsession.delete(record)
396 # This is a PLC-specific thing, won't work with other platforms
397 def get_key_from_incoming_ip (self, api):
398 # verify that the callers's ip address exist in the db and is an interface
399 # for a node in the db
400 (ip, port) = api.remote_addr
401 interfaces = self.driver.shell.GetInterfaces({'ip': ip}, ['node_id'])
403 raise NonExistingRecord("no such ip %(ip)s" % locals())
404 nodes = self.driver.shell.GetNodes([interfaces[0]['node_id']], ['node_id', 'hostname'])
406 raise NonExistingRecord("no such node using ip %(ip)s" % locals())
409 # look up the sfa record
410 record=dbsession.query(RegRecord).filter_by(type='node',pointer=node['node_id']).first()
412 raise RecordNotFound("node with pointer %s"%node['node_id'])
414 # generate a new keypair and gid
416 pkey = Keypair(create=True)
417 urn = hrn_to_urn(record.hrn, record.type)
418 gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey)
419 gid = gid_object.save_to_string(save_parents=True)
425 # attempt the scp the key
426 # and gid onto the node
427 # this will only work for planetlab based components
428 (kfd, key_filename) = tempfile.mkstemp()
429 (gfd, gid_filename) = tempfile.mkstemp()
430 pkey.save_to_file(key_filename)
431 gid_object.save_to_file(gid_filename, save_parents=True)
432 host = node['hostname']
433 key_dest="/etc/sfa/node.key"
434 gid_dest="/etc/sfa/node.gid"
436 #identity = "/etc/planetlab/root_ssh_key.rsa"
437 identity = "/etc/sfa/root_ssh_key"
438 scp_options=" -i %(identity)s " % locals()
439 scp_options+="-o StrictHostKeyChecking=no " % locals()
440 scp_key_command="%(scp)s %(scp_options)s %(key_filename)s root@%(host)s:%(key_dest)s" %\
442 scp_gid_command="%(scp)s %(scp_options)s %(gid_filename)s root@%(host)s:%(gid_dest)s" %\
445 all_commands = [scp_key_command, scp_gid_command]
447 for command in all_commands:
448 (status, output) = commands.getstatusoutput(command)
450 raise Exception, output
452 for filename in [key_filename, gid_filename]: