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.version import version_core
13 from sfa.util.sfalogging import logger
15 from sfa.trust.gid import GID
16 from sfa.trust.credential import Credential
17 from sfa.trust.certificate import Certificate, Keypair, convert_public_key
18 from sfa.trust.gid import create_uuid
20 from sfa.storage.model import make_record, RegRecord, RegAuthority, RegUser, RegSlice, RegKey
21 from sfa.storage.alchemy import dbsession
23 class RegistryManager:
25 def __init__ (self, config): pass
27 # The GENI GetVersion call
28 def GetVersion(self, api, options):
29 peers = dict ( [ (hrn,interface.get_url()) for (hrn,interface) in api.registries.iteritems()
32 return version_core({'interface':'registry',
39 def GetCredential(self, api, xrn, type, caller_xrn=None):
42 hrn = urn_to_hrn(xrn)[0]
44 hrn, type = urn_to_hrn(xrn)
46 # Slivers don't have credentials but users should be able to
47 # specify a sliver xrn and receive the slice's credential
48 if type == 'sliver' or '-' in Xrn(hrn).leaf:
49 slice_xrn = self.driver.sliver_to_slice_xrn(hrn)
52 # Is this a root or sub authority
53 auth_hrn = api.auth.get_authority(hrn)
54 if not auth_hrn or hrn == api.config.SFA_INTERFACE_HRN:
56 auth_info = api.auth.get_auth_info(auth_hrn)
58 record=dbsession.query(RegRecord).filter_by(type=type,hrn=hrn).first()
60 raise RecordNotFound("hrn=%s, type=%s"%(hrn,type))
62 # xxx for the record only
63 # used to call this, which was wrong, now all needed data is natively is our DB
64 # self.driver.augment_records_with_testbed_info (record.__dict__)
65 # likewise, we deprecate is_enabled which was not really useful
66 # if not self.driver.is_enabled (record.__dict__): ...
67 # xxx for the record only
70 # if caller_xrn is not specified assume the caller is the record
74 caller_gid = record.get_gid_object()
76 caller_hrn, caller_type = urn_to_hrn(caller_xrn)
78 caller_record = dbsession.query(RegRecord).filter_by(hrn=caller_hrn,type=caller_type).first()
80 caller_record = dbsession.query(RegRecord).filter_by(hrn=caller_hrn).first()
82 raise RecordNotFound("Unable to associated caller (hrn=%s, type=%s) with credential for (hrn: %s, type: %s)"%(caller_hrn, caller_type, hrn, type))
83 caller_gid = GID(string=caller_record.gid)
85 object_hrn = record.get_gid_object().get_hrn()
86 # call the builtin authorization/credential generation engine
87 rights = api.auth.determine_user_rights(caller_hrn, record)
88 # make sure caller has rights to this object
90 raise PermissionError("%s has no rights to %s (%s)" % \
91 (caller_hrn, object_hrn, xrn))
92 object_gid = GID(string=record.gid)
93 new_cred = Credential(subject = object_gid.get_subject())
94 new_cred.set_gid_caller(caller_gid)
95 new_cred.set_gid_object(object_gid)
96 new_cred.set_issuer_keys(auth_info.get_privkey_filename(), auth_info.get_gid_filename())
97 #new_cred.set_pubkey(object_gid.get_pubkey())
98 new_cred.set_privileges(rights)
99 new_cred.get_privileges().delegate_all_privileges(True)
100 if hasattr(record,'expires'):
101 date = utcparse(record.expires)
102 expires = datetime_to_epoch(date)
103 new_cred.set_expiration(int(expires))
104 auth_kind = "authority,ma,sa"
105 # Parent not necessary, verify with certs
106 #new_cred.set_parent(api.auth.hierarchy.get_auth_cred(auth_hrn, kind=auth_kind))
110 return new_cred.save_to_string(save_parents=True)
113 def Resolve(self, api, xrns, type=None, full=True):
115 if not isinstance(xrns, types.ListType):
116 # try to infer type if not set and we get a single input
118 type = Xrn(xrns).get_type()
120 hrns = [urn_to_hrn(xrn)[0] for xrn in xrns]
122 # load all known registry names into a prefix tree and attempt to find
123 # the longest matching prefix
124 # create a dict where key is a registry hrn and its value is a list
125 # of hrns at that registry (determined by the known prefix tree).
127 registries = api.registries
129 registry_hrns = registries.keys()
130 tree.load(registry_hrns)
132 registry_hrn = tree.best_match(urn_to_hrn(xrn)[0])
133 if registry_hrn not in xrn_dict:
134 xrn_dict[registry_hrn] = []
135 xrn_dict[registry_hrn].append(xrn)
138 for registry_hrn in xrn_dict:
139 # skip the hrn without a registry hrn
140 # XX should we let the user know the authority is unknown?
144 # if the best match (longest matching hrn) is not the local registry,
145 # forward the request
146 xrns = xrn_dict[registry_hrn]
147 if registry_hrn != api.hrn:
148 credential = api.getCredential()
149 interface = api.registries[registry_hrn]
150 server_proxy = api.server_proxy(interface, credential)
151 peer_records = server_proxy.Resolve(xrns, credential,type)
152 # pass foreign records as-is
153 # previous code used to read
154 # records.extend([SfaRecord(dict=record).as_dict() for record in peer_records])
155 # not sure why the records coming through xmlrpc had to be processed at all
156 records.extend(peer_records)
158 # try resolving the remaining unfound records at the local registry
159 local_hrns = list ( set(hrns).difference([record['hrn'] for record in records]) )
161 local_records = dbsession.query(RegRecord).filter(RegRecord.hrn.in_(local_hrns))
163 local_records = local_records.filter_by(type=type)
164 local_records=local_records.all()
165 logger.info("Resolve: local_records=%s (type=%s)"%(local_records,type))
166 local_dicts = [ record.__dict__ for record in local_records ]
169 # in full mode we get as much info as we can, which involves contacting the
170 # testbed for getting implementation details about the record
171 self.driver.augment_records_with_testbed_info(local_dicts)
172 # also we fill the 'url' field for known authorities
173 # used to be in the driver code, sounds like a poorman thing though
174 def solve_neighbour_url (record):
175 if not record.type.startswith('authority'): return
177 for neighbour_dict in [ api.aggregates, api.registries ]:
178 if hrn in neighbour_dict:
179 record.url=neighbour_dict[hrn].get_url()
181 for record in local_records: solve_neighbour_url (record)
183 # convert local record objects to dicts for xmlrpc
184 # xxx somehow here calling dict(record) issues a weird error
185 # however record.todict() seems to work fine
186 # records.extend( [ dict(record) for record in local_records ] )
187 records.extend( [ record.todict() for record in local_records ] )
189 raise RecordNotFound(str(hrns))
193 def List (self, api, xrn, origin_hrn=None, options={}):
194 # load all know registry names into a prefix tree and attempt to find
195 # the longest matching prefix
196 hrn, type = urn_to_hrn(xrn)
197 registries = api.registries
198 registry_hrns = registries.keys()
200 tree.load(registry_hrns)
201 registry_hrn = tree.best_match(hrn)
203 #if there was no match then this record belongs to an unknow registry
205 raise MissingAuthority(xrn)
206 # if the best match (longest matching hrn) is not the local registry,
207 # forward the request
209 if registry_hrn != api.hrn:
210 credential = api.getCredential()
211 interface = api.registries[registry_hrn]
212 server_proxy = api.server_proxy(interface, credential)
213 record_list = server_proxy.List(xrn, credential, options)
214 # same as above, no need to process what comes from through xmlrpc
215 # pass foreign records as-is
216 record_dicts = record_list
218 # if we still have not found the record yet, try the local registry
221 if ('recursive' in options and options['recursive']):
223 elif hrn.endswith('*'):
227 if not api.auth.hierarchy.auth_exists(hrn):
228 raise MissingAuthority(hrn)
230 records = dbsession.query(RegRecord).filter(RegRecord.hrn.startswith(hrn))
232 records = dbsession.query(RegRecord).filter_by(authority=hrn)
233 record_dicts=[ record.todict() for record in records ]
238 def CreateGid(self, api, xrn, cert):
240 authority = Xrn(xrn=xrn).get_authority_hrn()
241 auth_info = api.auth.get_auth_info(authority)
243 pkey = Keypair(create=True)
245 certificate = Certificate(string=cert)
246 pkey = certificate.get_pubkey()
247 gid = api.auth.hierarchy.create_gid(xrn, create_uuid(), pkey)
248 return gid.save_to_string(save_parents=True)
251 # utility for handling relationships among the SFA objects
252 # given that the SFA db does not handle this sort of relationsships
253 # it will rely on side-effects in the testbed to keep this persistent
255 # subject_record describes the subject of the relationships
256 # ref_record contains the target values for the various relationships we need to manage
257 # (to begin with, this is just the slice x person relationship)
258 def update_driver_relations (self, subject_obj, ref_obj):
259 type=subject_obj.type
260 #for (k,v) in subject_obj.__dict__.items(): print k,'=',v
261 if type=='slice' and hasattr(ref_obj,'researcher'):
262 self.update_driver_relation(subject_obj, ref_obj.researcher, 'user', 'researcher')
263 elif type=='authority' and hasattr(ref_obj,'pi'):
264 self.update_driver_relation(subject_obj,ref_obj.pi, 'user', 'pi')
266 # field_key is the name of one field in the record, typically 'researcher' for a 'slice' record
267 # hrns is the list of hrns that should be linked to the subject from now on
268 # target_type would be e.g. 'user' in the 'slice' x 'researcher' example
269 def update_driver_relation (self, record_obj, hrns, target_type, relation_name):
270 # locate the linked objects in our db
271 subject_type=record_obj.type
272 subject_id=record_obj.pointer
273 # get the 'pointer' field of all matching records
274 link_id_tuples = dbsession.query(RegRecord.pointer).filter_by(type=target_type).filter(RegRecord.hrn.in_(hrns)).all()
275 # sqlalchemy returns named tuples for columns
276 link_ids = [ tuple.pointer for tuple in link_id_tuples ]
277 self.driver.update_relation (subject_type, target_type, relation_name, subject_id, link_ids)
279 def Register(self, api, record_dict):
281 hrn, type = record_dict['hrn'], record_dict['type']
282 urn = hrn_to_urn(hrn,type)
284 if type not in ['authority', 'slice', 'node', 'user']:
285 raise UnknownSfaType(type)
287 # check if record_dict already exists
288 existing_records = dbsession.query(RegRecord).filter_by(type=type,hrn=hrn).all()
290 raise ExistingRecord(hrn)
292 assert ('type' in record_dict)
293 # returns the right type of RegRecord according to type in record
294 record = make_record(dict=record_dict)
295 record.just_created()
296 record.authority = get_authority(record.hrn)
297 auth_info = api.auth.get_auth_info(record.authority)
299 # make sure record has a gid
302 pkey = Keypair(create=True)
303 if getattr(record,'keys',None):
305 # use only first key in record
306 if isinstance(record.keys, types.ListType):
307 pub_key = record.keys[0]
308 pkey = convert_public_key(pub_key)
310 gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey)
311 gid = gid_object.save_to_string(save_parents=True)
314 if isinstance (record, RegAuthority):
316 if not api.auth.hierarchy.auth_exists(hrn):
317 api.auth.hierarchy.create_auth(hrn_to_urn(hrn,'authority'))
319 # get the GID from the newly created authority
320 auth_info = api.auth.get_auth_info(hrn)
321 gid = auth_info.get_gid_object()
322 record.gid=gid.save_to_string(save_parents=True)
324 # locate objects for relationships
325 pi_hrns = getattr(record,'pi',None)
326 if pi_hrns is not None: record.update_pis (pi_hrns)
328 elif isinstance (record, RegSlice):
329 researcher_hrns = getattr(record,'researcher',None)
330 if researcher_hrns is not None: record.update_researchers (researcher_hrns)
332 elif isinstance (record, RegUser):
333 # create RegKey objects for incoming keys
334 if hasattr(record,'keys'):
335 logger.debug ("creating %d keys for user %s"%(len(record.keys),record.hrn))
336 record.reg_keys = [ RegKey (key) for key in record.keys ]
338 # update testbed-specific data if needed
339 pointer = self.driver.register (record.__dict__, hrn, pub_key)
341 record.pointer=pointer
342 dbsession.add(record)
345 # update membership for researchers, pis, owners, operators
346 self.update_driver_relations (record, record)
348 return record.get_gid_object().save_to_string(save_parents=True)
350 def Update(self, api, record_dict):
351 assert ('type' in record_dict)
352 new_record=make_record(dict=record_dict)
353 (type,hrn) = (new_record.type, new_record.hrn)
355 # make sure the record exists
356 record = dbsession.query(RegRecord).filter_by(type=type,hrn=hrn).first()
358 raise RecordNotFound("hrn=%s, type=%s"%(hrn,type))
359 record.just_updated()
361 # Use the pointer from the existing record, not the one that the user
362 # gave us. This prevents the user from inserting a forged pointer
363 pointer = record.pointer
365 # is there a change in keys ?
368 if getattr(new_key,'keys',None):
369 new_key=new_record.keys
370 if isinstance (new_key,types.ListType):
373 # take new_key into account
375 # update the openssl key and gid
376 pkey = convert_public_key(new_key)
378 urn = hrn_to_urn(hrn,type)
379 gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey)
380 gid = gid_object.save_to_string(save_parents=True)
384 # xxx should do side effects from new_record to record
385 # not too sure how to do that
386 # not too big a deal with planetlab as the driver is authoritative, but...
388 # update native relations
389 if isinstance (record, RegSlice):
390 researcher_hrns = getattr(new_record,'researcher',None)
391 if researcher_hrns is not None: record.update_researchers (researcher_hrns)
394 elif isinstance (record, RegAuthority):
395 pi_hrns = getattr(new_record,'pi',None)
396 if pi_hrns is not None: record.update_pis (pi_hrns)
399 # update the PLC information that was specified with the record
400 # xxx oddly enough, without this useless statement,
401 # record.__dict__ as received by the driver seems to be off
402 # anyway the driver should receive an object
403 # (and then extract __dict__ itself if needed)
404 print "DO NOT REMOVE ME before driver.update, record=%s"%record
405 if not self.driver.update (record.__dict__, new_record.__dict__, hrn, new_key):
406 logger.warning("driver.update failed")
408 # update membership for researchers, pis, owners, operators
409 self.update_driver_relations (record, new_record)
413 # expecting an Xrn instance
414 def Remove(self, api, xrn, origin_hrn=None):
417 request=dbsession.query(RegRecord).filter_by(hrn=hrn)
418 if type and type not in ['all', '*']:
419 request=request.filter_by(type=type)
421 record = request.first()
423 msg="Could not find hrn %s"%hrn
424 if type: msg += " type=%s"%type
425 raise RecordNotFound(msg)
428 if type not in ['slice', 'user', 'node', 'authority'] :
429 raise UnknownSfaType(type)
431 credential = api.getCredential()
432 registries = api.registries
434 # Try to remove the object from the PLCDB of federated agg.
435 # This is attempted before removing the object from the local agg's PLCDB and sfa table
436 if hrn.startswith(api.hrn) and type in ['user', 'slice', 'authority']:
437 for registry in registries:
438 if registry not in [api.hrn]:
440 result=registries[registry].remove_peer_object(credential, record, origin_hrn)
444 # call testbed callback first
445 # IIUC this is done on the local testbed TOO because of the refreshpeer link
446 if not self.driver.remove(record.__dict__):
447 logger.warning("driver.remove failed")
450 dbsession.delete(record)
455 # This is a PLC-specific thing, won't work with other platforms
456 def get_key_from_incoming_ip (self, api):
457 # verify that the callers's ip address exist in the db and is an interface
458 # for a node in the db
459 (ip, port) = api.remote_addr
460 interfaces = self.driver.shell.GetInterfaces({'ip': ip}, ['node_id'])
462 raise NonExistingRecord("no such ip %(ip)s" % locals())
463 nodes = self.driver.shell.GetNodes([interfaces[0]['node_id']], ['node_id', 'hostname'])
465 raise NonExistingRecord("no such node using ip %(ip)s" % locals())
468 # look up the sfa record
469 record=dbsession.query(RegRecord).filter_by(type='node',pointer=node['node_id']).first()
471 raise RecordNotFound("node with pointer %s"%node['node_id'])
473 # generate a new keypair and gid
475 pkey = Keypair(create=True)
476 urn = hrn_to_urn(record.hrn, record.type)
477 gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey)
478 gid = gid_object.save_to_string(save_parents=True)
484 # attempt the scp the key
485 # and gid onto the node
486 # this will only work for planetlab based components
487 (kfd, key_filename) = tempfile.mkstemp()
488 (gfd, gid_filename) = tempfile.mkstemp()
489 pkey.save_to_file(key_filename)
490 gid_object.save_to_file(gid_filename, save_parents=True)
491 host = node['hostname']
492 key_dest="/etc/sfa/node.key"
493 gid_dest="/etc/sfa/node.gid"
495 #identity = "/etc/planetlab/root_ssh_key.rsa"
496 identity = "/etc/sfa/root_ssh_key"
497 scp_options=" -i %(identity)s " % locals()
498 scp_options+="-o StrictHostKeyChecking=no " % locals()
499 scp_key_command="%(scp)s %(scp_options)s %(key_filename)s root@%(host)s:%(key_dest)s" %\
501 scp_gid_command="%(scp)s %(scp_options)s %(gid_filename)s root@%(host)s:%(gid_dest)s" %\
504 all_commands = [scp_key_command, scp_gid_command]
506 for command in all_commands:
507 (status, output) = commands.getstatusoutput(command)
509 raise Exception, output
511 for filename in [key_filename, gid_filename]: