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 augment_with_sfa_builtins
22 ### the types that we need to exclude from sqlobjects before being able to dump
23 # them on the xmlrpc wire
24 from sqlalchemy.orm.collections import InstrumentedList
26 class RegistryManager:
28 def __init__ (self, config):
29 logger.info("Creating RegistryManager[%s]"%id(self))
31 # The GENI GetVersion call
32 def GetVersion(self, api, options):
33 peers = dict ( [ (hrn,interface.get_url()) for (hrn,interface) in api.registries.iteritems()
36 return version_core({'interface':'registry',
43 def GetCredential(self, api, xrn, input_type, caller_xrn=None):
46 hrn, _ = urn_to_hrn(xrn)
49 hrn, type = urn_to_hrn(xrn)
51 # Slivers don't have credentials but users should be able to
52 # specify a sliver xrn and receive the slice's credential
53 # However if input_type is specified
54 if type == 'sliver' or ( not input_type and '-' in Xrn(hrn).leaf):
55 slice_xrn = api.driver.sliver_to_slice_xrn(hrn)
58 # Is this a root or sub authority
59 auth_hrn = api.auth.get_authority(hrn)
60 if not auth_hrn or hrn == api.config.SFA_INTERFACE_HRN:
62 auth_info = api.auth.get_auth_info(auth_hrn)
65 dbsession = api.dbsession()
66 record=dbsession.query(RegRecord).filter_by(type=type,hrn=hrn).first()
68 raise RecordNotFound("hrn=%s, type=%s"%(hrn,type))
71 # if caller_xrn is not specified assume the caller is the record
75 caller_gid = record.get_gid_object()
77 caller_hrn, caller_type = urn_to_hrn(caller_xrn)
79 caller_record = dbsession.query(RegRecord).filter_by(hrn=caller_hrn,type=caller_type).first()
81 caller_record = dbsession.query(RegRecord).filter_by(hrn=caller_hrn).first()
83 raise RecordNotFound("Unable to associated caller (hrn=%s, type=%s) with credential for (hrn: %s, type: %s)"%(caller_hrn, caller_type, hrn, type))
84 caller_gid = GID(string=caller_record.gid)
86 object_hrn = record.get_gid_object().get_hrn()
87 # call the builtin authorization/credential generation engine
88 rights = api.auth.determine_user_rights(caller_hrn, record)
89 # make sure caller has rights to this object
91 raise PermissionError("%s has no rights to %s (%s)" % \
92 (caller_hrn, object_hrn, xrn))
93 object_gid = GID(string=record.gid)
94 new_cred = Credential(subject = object_gid.get_subject())
95 new_cred.set_gid_caller(caller_gid)
96 new_cred.set_gid_object(object_gid)
97 new_cred.set_issuer_keys(auth_info.get_privkey_filename(), auth_info.get_gid_filename())
98 #new_cred.set_pubkey(object_gid.get_pubkey())
99 new_cred.set_privileges(rights)
100 new_cred.get_privileges().delegate_all_privileges(True)
101 if hasattr(record,'expires'):
102 date = utcparse(record.expires)
103 expires = datetime_to_epoch(date)
104 new_cred.set_expiration(int(expires))
105 auth_kind = "authority,ma,sa"
106 # Parent not necessary, verify with certs
107 #new_cred.set_parent(api.auth.hierarchy.get_auth_cred(auth_hrn, kind=auth_kind))
111 return new_cred.save_to_string(save_parents=True)
114 # the default for full, which means 'dig into the testbed as well', should be false
115 def Resolve(self, api, xrns, type=None, details=False):
117 dbsession = api.dbsession()
118 if not isinstance(xrns, types.ListType):
119 # try to infer type if not set and we get a single input
121 type = Xrn(xrns).get_type()
123 hrns = [urn_to_hrn(xrn)[0] for xrn in xrns]
125 # load all known registry names into a prefix tree and attempt to find
126 # the longest matching prefix
127 # create a dict where key is a registry hrn and its value is a list
128 # of hrns at that registry (determined by the known prefix tree).
130 registries = api.registries
132 registry_hrns = registries.keys()
133 tree.load(registry_hrns)
135 registry_hrn = tree.best_match(urn_to_hrn(xrn)[0])
136 if registry_hrn not in xrn_dict:
137 xrn_dict[registry_hrn] = []
138 xrn_dict[registry_hrn].append(xrn)
141 for registry_hrn in xrn_dict:
142 # skip the hrn without a registry hrn
143 # XX should we let the user know the authority is unknown?
147 # if the best match (longest matching hrn) is not the local registry,
148 # forward the request
149 xrns = xrn_dict[registry_hrn]
150 if registry_hrn != api.hrn:
151 credential = api.getCredential()
152 interface = api.registries[registry_hrn]
153 server_proxy = api.server_proxy(interface, credential)
154 # should propagate the details flag but that's not supported in the xmlrpc interface yet
155 #peer_records = server_proxy.Resolve(xrns, credential,type, details=details)
156 peer_records = server_proxy.Resolve(xrns, credential)
157 # pass foreign records as-is
158 # previous code used to read
159 # records.extend([SfaRecord(dict=record).as_dict() for record in peer_records])
160 # not sure why the records coming through xmlrpc had to be processed at all
161 records.extend(peer_records)
163 # try resolving the remaining unfound records at the local registry
164 local_hrns = list ( set(hrns).difference([record['hrn'] for record in records]) )
166 local_records = dbsession.query(RegRecord).filter(RegRecord.hrn.in_(local_hrns))
168 local_records = local_records.filter_by(type=type)
169 local_records=local_records.all()
171 for local_record in local_records:
172 augment_with_sfa_builtins (local_record)
174 logger.info("Resolve, (details=%s,type=%s) local_records=%s "%(details,type,local_records))
175 local_dicts = [ record.__dict__ for record in local_records ]
178 # in details mode we get as much info as we can, which involves contacting the
179 # testbed for getting implementation details about the record
180 api.driver.augment_records_with_testbed_info(local_dicts)
181 # also we fill the 'url' field for known authorities
182 # used to be in the driver code, sounds like a poorman thing though
183 def solve_neighbour_url (record):
184 if not record.type.startswith('authority'): return
186 for neighbour_dict in [ api.aggregates, api.registries ]:
187 if hrn in neighbour_dict:
188 record.url=neighbour_dict[hrn].get_url()
190 for record in local_records: solve_neighbour_url (record)
192 # convert local record objects to dicts for xmlrpc
193 # xxx somehow here calling dict(record) issues a weird error
194 # however record.todict() seems to work fine
195 # records.extend( [ dict(record) for record in local_records ] )
196 records.extend( [ record.todict(exclude_types=[InstrumentedList]) for record in local_records ] )
199 raise RecordNotFound(str(hrns))
203 def List (self, api, xrn, origin_hrn=None, options={}):
204 dbsession=api.dbsession()
205 # load all know registry names into a prefix tree and attempt to find
206 # the longest matching prefix
207 hrn, type = urn_to_hrn(xrn)
208 registries = api.registries
209 registry_hrns = registries.keys()
211 tree.load(registry_hrns)
212 registry_hrn = tree.best_match(hrn)
214 #if there was no match then this record belongs to an unknow registry
216 raise MissingAuthority(xrn)
217 # if the best match (longest matching hrn) is not the local registry,
218 # forward the request
220 if registry_hrn != api.hrn:
221 credential = api.getCredential()
222 interface = api.registries[registry_hrn]
223 server_proxy = api.server_proxy(interface, credential)
224 record_list = server_proxy.List(xrn, credential, options)
225 # same as above, no need to process what comes from through xmlrpc
226 # pass foreign records as-is
227 record_dicts = record_list
229 # if we still have not found the record yet, try the local registry
230 # logger.debug("before trying local records, %d foreign records"% len(record_dicts))
233 if ('recursive' in options and options['recursive']):
235 elif hrn.endswith('*'):
239 if not api.auth.hierarchy.auth_exists(hrn):
240 raise MissingAuthority(hrn)
242 records = dbsession.query(RegRecord).filter(RegRecord.hrn.startswith(hrn)).all()
243 # logger.debug("recursive mode, found %d local records"%(len(records)))
245 records = dbsession.query(RegRecord).filter_by(authority=hrn).all()
246 # logger.debug("non recursive mode, found %d local records"%(len(records)))
247 # so that sfi list can show more than plain names...
248 for record in records: augment_with_sfa_builtins (record)
249 record_dicts=[ record.todict(exclude_types=[InstrumentedList]) for record in records ]
254 def CreateGid(self, api, xrn, cert):
256 authority = Xrn(xrn=xrn).get_authority_hrn()
257 auth_info = api.auth.get_auth_info(authority)
259 pkey = Keypair(create=True)
261 certificate = Certificate(string=cert)
262 pkey = certificate.get_pubkey()
263 gid = api.auth.hierarchy.create_gid(xrn, create_uuid(), pkey)
264 return gid.save_to_string(save_parents=True)
267 # utility for handling relationships among the SFA objects
269 # subject_record describes the subject of the relationships
270 # ref_record contains the target values for the various relationships we need to manage
271 # (to begin with, this is just the slice x person (researcher) and authority x person (pi) relationships)
272 def update_driver_relations (self, api, subject_obj, ref_obj):
273 type=subject_obj.type
274 #for (k,v) in subject_obj.__dict__.items(): print k,'=',v
275 if type=='slice' and hasattr(ref_obj,'researcher'):
276 self.update_driver_relation(api, subject_obj, ref_obj.researcher, 'user', 'researcher')
277 elif type=='authority' and hasattr(ref_obj,'pi'):
278 self.update_driver_relation(api, subject_obj,ref_obj.pi, 'user', 'pi')
280 # field_key is the name of one field in the record, typically 'researcher' for a 'slice' record
281 # hrns is the list of hrns that should be linked to the subject from now on
282 # target_type would be e.g. 'user' in the 'slice' x 'researcher' example
283 def update_driver_relation (self, api, record_obj, hrns, target_type, relation_name):
284 dbsession=api.dbsession()
285 # locate the linked objects in our db
286 subject_type=record_obj.type
287 subject_id=record_obj.pointer
288 # get the 'pointer' field of all matching records
289 link_id_tuples = dbsession.query(RegRecord.pointer).filter_by(type=target_type).filter(RegRecord.hrn.in_(hrns)).all()
290 # sqlalchemy returns named tuples for columns
291 link_ids = [ tuple.pointer for tuple in link_id_tuples ]
292 api.driver.update_relation (subject_type, target_type, relation_name, subject_id, link_ids)
294 def Register(self, api, record_dict):
296 dbsession=api.dbsession()
297 hrn, type = record_dict['hrn'], record_dict['type']
298 urn = hrn_to_urn(hrn,type)
300 if type not in ['authority', 'slice', 'node', 'user']:
301 raise UnknownSfaType(type)
303 # check if record_dict already exists
304 existing_records = dbsession.query(RegRecord).filter_by(type=type,hrn=hrn).all()
306 raise ExistingRecord(hrn)
308 assert ('type' in record_dict)
309 # returns the right type of RegRecord according to type in record
310 record = make_record(dict=record_dict)
311 record.just_created()
312 record.authority = get_authority(record.hrn)
313 auth_info = api.auth.get_auth_info(record.authority)
315 # make sure record has a gid
318 pkey = Keypair(create=True)
319 if getattr(record,'keys',None):
321 # use only first key in record
322 if isinstance(record.keys, types.ListType):
323 pub_key = record.keys[0]
324 pkey = convert_public_key(pub_key)
326 gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey)
327 gid = gid_object.save_to_string(save_parents=True)
330 if isinstance (record, RegAuthority):
332 if not api.auth.hierarchy.auth_exists(hrn):
333 api.auth.hierarchy.create_auth(hrn_to_urn(hrn,'authority'))
335 # get the GID from the newly created authority
336 auth_info = api.auth.get_auth_info(hrn)
337 gid = auth_info.get_gid_object()
338 record.gid=gid.save_to_string(save_parents=True)
340 # locate objects for relationships
341 pi_hrns = getattr(record,'pi',None)
342 if pi_hrns is not None: record.update_pis (pi_hrns, dbsession)
344 elif isinstance (record, RegSlice):
345 researcher_hrns = getattr(record,'researcher',None)
346 if researcher_hrns is not None: record.update_researchers (researcher_hrns, dbsession)
348 elif isinstance (record, RegUser):
349 # create RegKey objects for incoming keys
350 if hasattr(record,'keys'):
351 logger.debug ("creating %d keys for user %s"%(len(record.keys),record.hrn))
352 record.reg_keys = [ RegKey (key) for key in record.keys ]
354 # update testbed-specific data if needed
355 pointer = api.driver.register (record.__dict__, hrn, pub_key)
357 record.pointer=pointer
358 dbsession.add(record)
361 # update membership for researchers, pis, owners, operators
362 self.update_driver_relations (api, record, record)
364 return record.get_gid_object().save_to_string(save_parents=True)
366 def Update(self, api, record_dict):
367 dbsession=api.dbsession()
368 assert ('type' in record_dict)
369 new_record=make_record(dict=record_dict)
370 (type,hrn) = (new_record.type, new_record.hrn)
372 # make sure the record exists
373 record = dbsession.query(RegRecord).filter_by(type=type,hrn=hrn).first()
375 raise RecordNotFound("hrn=%s, type=%s"%(hrn,type))
376 record.just_updated()
378 # Use the pointer from the existing record, not the one that the user
379 # gave us. This prevents the user from inserting a forged pointer
380 pointer = record.pointer
382 # is there a change in keys ?
385 if getattr(new_record,'keys',None):
386 new_key=new_record.keys
387 if isinstance (new_key,types.ListType):
390 # take new_key into account
392 # update the openssl key and gid
393 pkey = convert_public_key(new_key)
395 urn = hrn_to_urn(hrn,type)
396 gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey)
397 gid = gid_object.save_to_string(save_parents=True)
399 # xxx should do side effects from new_record to record
400 # not too sure how to do that
401 # not too big a deal with planetlab as the driver is authoritative, but...
403 # update native relations
404 if isinstance (record, RegSlice):
405 researcher_hrns = getattr(new_record,'researcher',None)
406 if researcher_hrns is not None: record.update_researchers (researcher_hrns, dbsession)
408 elif isinstance (record, RegAuthority):
409 pi_hrns = getattr(new_record,'pi',None)
410 if pi_hrns is not None: record.update_pis (pi_hrns, dbsession)
412 # update the PLC information that was specified with the record
413 # xxx oddly enough, without this useless statement,
414 # record.__dict__ as received by the driver seems to be off
415 # anyway the driver should receive an object
416 # (and then extract __dict__ itself if needed)
417 print "DO NOT REMOVE ME before driver.update, record=%s"%record
420 (pointer, new_key_pointer) = api.driver.update (record.__dict__, new_record.__dict__, hrn, new_key)
423 if new_key and new_key_pointer:
424 record.reg_keys=[ RegKey (new_key, new_key_pointer)]
428 # update membership for researchers, pis, owners, operators
429 self.update_driver_relations (api, record, new_record)
433 # expecting an Xrn instance
434 def Remove(self, api, xrn, origin_hrn=None):
435 dbsession=api.dbsession()
438 request=dbsession.query(RegRecord).filter_by(hrn=hrn)
439 if type and type not in ['all', '*']:
440 request=request.filter_by(type=type)
442 record = request.first()
444 msg="Could not find hrn %s"%hrn
445 if type: msg += " type=%s"%type
446 raise RecordNotFound(msg)
449 if type not in ['slice', 'user', 'node', 'authority'] :
450 raise UnknownSfaType(type)
452 credential = api.getCredential()
453 registries = api.registries
455 # Try to remove the object from the PLCDB of federated agg.
456 # This is attempted before removing the object from the local agg's PLCDB and sfa table
457 if hrn.startswith(api.hrn) and type in ['user', 'slice', 'authority']:
458 for registry in registries:
459 if registry not in [api.hrn]:
461 result=registries[registry].remove_peer_object(credential, record, origin_hrn)
465 # call testbed callback first
466 # IIUC this is done on the local testbed TOO because of the refreshpeer link
467 if not api.driver.remove(record.__dict__):
468 logger.warning("driver.remove failed")
471 dbsession.delete(record)
476 # This is a PLC-specific thing, won't work with other platforms
477 def get_key_from_incoming_ip (self, api):
478 dbsession=api.dbsession()
479 # verify that the callers's ip address exist in the db and is an interface
480 # for a node in the db
481 (ip, port) = api.remote_addr
482 interfaces = api.driver.shell.GetInterfaces({'ip': ip}, ['node_id'])
484 raise NonExistingRecord("no such ip %(ip)s" % locals())
485 nodes = api.driver.shell.GetNodes([interfaces[0]['node_id']], ['node_id', 'hostname'])
487 raise NonExistingRecord("no such node using ip %(ip)s" % locals())
490 # look up the sfa record
491 record=dbsession.query(RegRecord).filter_by(type='node',pointer=node['node_id']).first()
493 raise RecordNotFound("node with pointer %s"%node['node_id'])
495 # generate a new keypair and gid
497 pkey = Keypair(create=True)
498 urn = hrn_to_urn(record.hrn, record.type)
499 gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey)
500 gid = gid_object.save_to_string(save_parents=True)
506 # attempt the scp the key
507 # and gid onto the node
508 # this will only work for planetlab based components
509 (kfd, key_filename) = tempfile.mkstemp()
510 (gfd, gid_filename) = tempfile.mkstemp()
511 pkey.save_to_file(key_filename)
512 gid_object.save_to_file(gid_filename, save_parents=True)
513 host = node['hostname']
514 key_dest="/etc/sfa/node.key"
515 gid_dest="/etc/sfa/node.gid"
517 #identity = "/etc/planetlab/root_ssh_key.rsa"
518 identity = "/etc/sfa/root_ssh_key"
519 scp_options=" -i %(identity)s " % locals()
520 scp_options+="-o StrictHostKeyChecking=no " % locals()
521 scp_key_command="%(scp)s %(scp_options)s %(key_filename)s root@%(host)s:%(key_dest)s" %\
523 scp_gid_command="%(scp)s %(scp_options)s %(gid_filename)s root@%(host)s:%(gid_dest)s" %\
526 all_commands = [scp_key_command, scp_gid_command]
528 for command in all_commands:
529 (status, output) = commands.getstatusoutput(command)
531 raise Exception, output
533 for filename in [key_filename, gid_filename]: