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, type, caller_xrn=None):
46 hrn = urn_to_hrn(xrn)[0]
48 hrn, type = urn_to_hrn(xrn)
50 # Slivers don't have credentials but users should be able to
51 # specify a sliver xrn and receive the slice's credential
52 if type == 'sliver' or '-' in Xrn(hrn).leaf:
53 slice_xrn = api.driver.sliver_to_slice_xrn(hrn)
56 # Is this a root or sub authority
57 auth_hrn = api.auth.get_authority(hrn)
58 if not auth_hrn or hrn == api.config.SFA_INTERFACE_HRN:
60 auth_info = api.auth.get_auth_info(auth_hrn)
63 dbsession = api.dbsession()
64 record=dbsession.query(RegRecord).filter_by(type=type,hrn=hrn).first()
66 raise RecordNotFound("hrn=%s, type=%s"%(hrn,type))
69 # if caller_xrn is not specified assume the caller is the record
73 caller_gid = record.get_gid_object()
75 caller_hrn, caller_type = urn_to_hrn(caller_xrn)
77 caller_record = dbsession.query(RegRecord).filter_by(hrn=caller_hrn,type=caller_type).first()
79 caller_record = dbsession.query(RegRecord).filter_by(hrn=caller_hrn).first()
81 raise RecordNotFound("Unable to associated caller (hrn=%s, type=%s) with credential for (hrn: %s, type: %s)"%(caller_hrn, caller_type, hrn, type))
82 caller_gid = GID(string=caller_record.gid)
84 object_hrn = record.get_gid_object().get_hrn()
85 # call the builtin authorization/credential generation engine
86 rights = api.auth.determine_user_rights(caller_hrn, record)
87 # make sure caller has rights to this object
89 raise PermissionError("%s has no rights to %s (%s)" % \
90 (caller_hrn, object_hrn, xrn))
91 object_gid = GID(string=record.gid)
92 new_cred = Credential(subject = object_gid.get_subject())
93 new_cred.set_gid_caller(caller_gid)
94 new_cred.set_gid_object(object_gid)
95 new_cred.set_issuer_keys(auth_info.get_privkey_filename(), auth_info.get_gid_filename())
96 #new_cred.set_pubkey(object_gid.get_pubkey())
97 new_cred.set_privileges(rights)
98 new_cred.get_privileges().delegate_all_privileges(True)
99 if hasattr(record,'expires'):
100 date = utcparse(record.expires)
101 expires = datetime_to_epoch(date)
102 new_cred.set_expiration(int(expires))
103 auth_kind = "authority,ma,sa"
104 # Parent not necessary, verify with certs
105 #new_cred.set_parent(api.auth.hierarchy.get_auth_cred(auth_hrn, kind=auth_kind))
109 return new_cred.save_to_string(save_parents=True)
112 # the default for full, which means 'dig into the testbed as well', should be false
113 def Resolve(self, api, xrns, type=None, details=False):
115 dbsession = api.dbsession()
116 if not isinstance(xrns, types.ListType):
117 # try to infer type if not set and we get a single input
119 type = Xrn(xrns).get_type()
121 hrns = [urn_to_hrn(xrn)[0] for xrn in xrns]
123 # load all known registry names into a prefix tree and attempt to find
124 # the longest matching prefix
125 # create a dict where key is a registry hrn and its value is a list
126 # of hrns at that registry (determined by the known prefix tree).
128 registries = api.registries
130 registry_hrns = registries.keys()
131 tree.load(registry_hrns)
133 registry_hrn = tree.best_match(urn_to_hrn(xrn)[0])
134 if registry_hrn not in xrn_dict:
135 xrn_dict[registry_hrn] = []
136 xrn_dict[registry_hrn].append(xrn)
139 for registry_hrn in xrn_dict:
140 # skip the hrn without a registry hrn
141 # XX should we let the user know the authority is unknown?
145 # if the best match (longest matching hrn) is not the local registry,
146 # forward the request
147 xrns = xrn_dict[registry_hrn]
148 if registry_hrn != api.hrn:
149 credential = api.getCredential()
150 interface = api.registries[registry_hrn]
151 server_proxy = api.server_proxy(interface, credential)
152 # should propagate the details flag but that's not supported in the xmlrpc interface yet
153 #peer_records = server_proxy.Resolve(xrns, credential,type, details=details)
154 peer_records = server_proxy.Resolve(xrns, credential)
155 # pass foreign records as-is
156 # previous code used to read
157 # records.extend([SfaRecord(dict=record).as_dict() for record in peer_records])
158 # not sure why the records coming through xmlrpc had to be processed at all
159 records.extend(peer_records)
161 # try resolving the remaining unfound records at the local registry
162 local_hrns = list ( set(hrns).difference([record['hrn'] for record in records]) )
164 local_records = dbsession.query(RegRecord).filter(RegRecord.hrn.in_(local_hrns))
166 local_records = local_records.filter_by(type=type)
167 local_records=local_records.all()
169 for local_record in local_records:
170 augment_with_sfa_builtins (local_record)
172 logger.info("Resolve, (details=%s,type=%s) local_records=%s "%(details,type,local_records))
173 local_dicts = [ record.__dict__ for record in local_records ]
176 # in details mode we get as much info as we can, which involves contacting the
177 # testbed for getting implementation details about the record
178 api.driver.augment_records_with_testbed_info(local_dicts)
179 # also we fill the 'url' field for known authorities
180 # used to be in the driver code, sounds like a poorman thing though
181 def solve_neighbour_url (record):
182 if not record.type.startswith('authority'): return
184 for neighbour_dict in [ api.aggregates, api.registries ]:
185 if hrn in neighbour_dict:
186 record.url=neighbour_dict[hrn].get_url()
188 for record in local_records: solve_neighbour_url (record)
190 # convert local record objects to dicts for xmlrpc
191 # xxx somehow here calling dict(record) issues a weird error
192 # however record.todict() seems to work fine
193 # records.extend( [ dict(record) for record in local_records ] )
194 records.extend( [ record.todict(exclude_types=[InstrumentedList]) for record in local_records ] )
197 raise RecordNotFound(str(hrns))
201 def List (self, api, xrn, origin_hrn=None, options={}):
202 dbsession=api.dbsession()
203 # load all know registry names into a prefix tree and attempt to find
204 # the longest matching prefix
205 hrn, type = urn_to_hrn(xrn)
206 registries = api.registries
207 registry_hrns = registries.keys()
209 tree.load(registry_hrns)
210 registry_hrn = tree.best_match(hrn)
212 #if there was no match then this record belongs to an unknow registry
214 raise MissingAuthority(xrn)
215 # if the best match (longest matching hrn) is not the local registry,
216 # forward the request
218 if registry_hrn != api.hrn:
219 credential = api.getCredential()
220 interface = api.registries[registry_hrn]
221 server_proxy = api.server_proxy(interface, credential)
222 record_list = server_proxy.List(xrn, credential, options)
223 # same as above, no need to process what comes from through xmlrpc
224 # pass foreign records as-is
225 record_dicts = record_list
227 # if we still have not found the record yet, try the local registry
228 # logger.debug("before trying local records, %d foreign records"% len(record_dicts))
231 if ('recursive' in options and options['recursive']):
233 elif hrn.endswith('*'):
237 if not api.auth.hierarchy.auth_exists(hrn):
238 raise MissingAuthority(hrn)
240 records = dbsession.query(RegRecord).filter(RegRecord.hrn.startswith(hrn)).all()
241 # logger.debug("recursive mode, found %d local records"%(len(records)))
243 records = dbsession.query(RegRecord).filter_by(authority=hrn).all()
244 # logger.debug("non recursive mode, found %d local records"%(len(records)))
245 # so that sfi list can show more than plain names...
246 for record in records: augment_with_sfa_builtins (record)
247 record_dicts=[ record.todict(exclude_types=[InstrumentedList]) for record in records ]
252 def CreateGid(self, api, xrn, cert):
254 authority = Xrn(xrn=xrn).get_authority_hrn()
255 auth_info = api.auth.get_auth_info(authority)
257 pkey = Keypair(create=True)
259 certificate = Certificate(string=cert)
260 pkey = certificate.get_pubkey()
261 gid = api.auth.hierarchy.create_gid(xrn, create_uuid(), pkey)
262 return gid.save_to_string(save_parents=True)
265 # utility for handling relationships among the SFA objects
267 # subject_record describes the subject of the relationships
268 # ref_record contains the target values for the various relationships we need to manage
269 # (to begin with, this is just the slice x person (researcher) and authority x person (pi) relationships)
270 def update_driver_relations (self, api, subject_obj, ref_obj):
271 type=subject_obj.type
272 #for (k,v) in subject_obj.__dict__.items(): print k,'=',v
273 if type=='slice' and hasattr(ref_obj,'researcher'):
274 self.update_driver_relation(api, subject_obj, ref_obj.researcher, 'user', 'researcher')
275 elif type=='authority' and hasattr(ref_obj,'pi'):
276 self.update_driver_relation(api, subject_obj,ref_obj.pi, 'user', 'pi')
278 # field_key is the name of one field in the record, typically 'researcher' for a 'slice' record
279 # hrns is the list of hrns that should be linked to the subject from now on
280 # target_type would be e.g. 'user' in the 'slice' x 'researcher' example
281 def update_driver_relation (self, api, record_obj, hrns, target_type, relation_name):
282 dbsession=api.dbsession()
283 # locate the linked objects in our db
284 subject_type=record_obj.type
285 subject_id=record_obj.pointer
286 # get the 'pointer' field of all matching records
287 link_id_tuples = dbsession.query(RegRecord.pointer).filter_by(type=target_type).filter(RegRecord.hrn.in_(hrns)).all()
288 # sqlalchemy returns named tuples for columns
289 link_ids = [ tuple.pointer for tuple in link_id_tuples ]
290 api.driver.update_relation (subject_type, target_type, relation_name, subject_id, link_ids)
292 def Register(self, api, record_dict):
294 dbsession=api.dbsession()
295 hrn, type = record_dict['hrn'], record_dict['type']
296 urn = hrn_to_urn(hrn,type)
298 if type not in ['authority', 'slice', 'node', 'user']:
299 raise UnknownSfaType(type)
301 # check if record_dict already exists
302 existing_records = dbsession.query(RegRecord).filter_by(type=type,hrn=hrn).all()
304 raise ExistingRecord(hrn)
306 assert ('type' in record_dict)
307 # returns the right type of RegRecord according to type in record
308 record = make_record(dict=record_dict)
309 record.just_created()
310 record.authority = get_authority(record.hrn)
311 auth_info = api.auth.get_auth_info(record.authority)
313 # make sure record has a gid
316 pkey = Keypair(create=True)
317 if getattr(record,'keys',None):
319 # use only first key in record
320 if isinstance(record.keys, types.ListType):
321 pub_key = record.keys[0]
322 pkey = convert_public_key(pub_key)
324 gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey)
325 gid = gid_object.save_to_string(save_parents=True)
328 if isinstance (record, RegAuthority):
330 if not api.auth.hierarchy.auth_exists(hrn):
331 api.auth.hierarchy.create_auth(hrn_to_urn(hrn,'authority'))
333 # get the GID from the newly created authority
334 auth_info = api.auth.get_auth_info(hrn)
335 gid = auth_info.get_gid_object()
336 record.gid=gid.save_to_string(save_parents=True)
338 # locate objects for relationships
339 pi_hrns = getattr(record,'pi',None)
340 if pi_hrns is not None: record.update_pis (pi_hrns, dbsession)
342 elif isinstance (record, RegSlice):
343 researcher_hrns = getattr(record,'researcher',None)
344 if researcher_hrns is not None: record.update_researchers (researcher_hrns, dbsession)
346 elif isinstance (record, RegUser):
347 # create RegKey objects for incoming keys
348 if hasattr(record,'keys'):
349 logger.debug ("creating %d keys for user %s"%(len(record.keys),record.hrn))
350 record.reg_keys = [ RegKey (key) for key in record.keys ]
352 # update testbed-specific data if needed
353 pointer = api.driver.register (record.__dict__, hrn, pub_key)
355 record.pointer=pointer
356 dbsession.add(record)
359 # update membership for researchers, pis, owners, operators
360 self.update_driver_relations (api, record, record)
362 return record.get_gid_object().save_to_string(save_parents=True)
364 def Update(self, api, record_dict):
365 dbsession=api.dbsession()
366 assert ('type' in record_dict)
367 new_record=make_record(dict=record_dict)
368 (type,hrn) = (new_record.type, new_record.hrn)
370 # make sure the record exists
371 record = dbsession.query(RegRecord).filter_by(type=type,hrn=hrn).first()
373 raise RecordNotFound("hrn=%s, type=%s"%(hrn,type))
374 record.just_updated()
376 # Use the pointer from the existing record, not the one that the user
377 # gave us. This prevents the user from inserting a forged pointer
378 pointer = record.pointer
380 # is there a change in keys ?
383 if getattr(new_record,'keys',None):
384 new_key=new_record.keys
385 if isinstance (new_key,types.ListType):
388 # take new_key into account
390 # update the openssl key and gid
391 pkey = convert_public_key(new_key)
393 urn = hrn_to_urn(hrn,type)
394 gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey)
395 gid = gid_object.save_to_string(save_parents=True)
397 # xxx should do side effects from new_record to record
398 # not too sure how to do that
399 # not too big a deal with planetlab as the driver is authoritative, but...
401 # update native relations
402 if isinstance (record, RegSlice):
403 researcher_hrns = getattr(new_record,'researcher',None)
404 if researcher_hrns is not None: record.update_researchers (researcher_hrns, dbsession)
406 elif isinstance (record, RegAuthority):
407 pi_hrns = getattr(new_record,'pi',None)
408 if pi_hrns is not None: record.update_pis (pi_hrns, dbsession)
410 # update the PLC information that was specified with the record
411 # xxx oddly enough, without this useless statement,
412 # record.__dict__ as received by the driver seems to be off
413 # anyway the driver should receive an object
414 # (and then extract __dict__ itself if needed)
415 print "DO NOT REMOVE ME before driver.update, record=%s"%record
418 (pointer, new_key_pointer) = api.driver.update (record.__dict__, new_record.__dict__, hrn, new_key)
421 if new_key and new_key_pointer:
422 record.reg_keys=[ RegKey (new_key, new_key_pointer)]
426 # update membership for researchers, pis, owners, operators
427 self.update_driver_relations (api, record, new_record)
431 # expecting an Xrn instance
432 def Remove(self, api, xrn, origin_hrn=None):
433 dbsession=api.dbsession()
436 request=dbsession.query(RegRecord).filter_by(hrn=hrn)
437 if type and type not in ['all', '*']:
438 request=request.filter_by(type=type)
440 record = request.first()
442 msg="Could not find hrn %s"%hrn
443 if type: msg += " type=%s"%type
444 raise RecordNotFound(msg)
447 if type not in ['slice', 'user', 'node', 'authority'] :
448 raise UnknownSfaType(type)
450 credential = api.getCredential()
451 registries = api.registries
453 # Try to remove the object from the PLCDB of federated agg.
454 # This is attempted before removing the object from the local agg's PLCDB and sfa table
455 if hrn.startswith(api.hrn) and type in ['user', 'slice', 'authority']:
456 for registry in registries:
457 if registry not in [api.hrn]:
459 result=registries[registry].remove_peer_object(credential, record, origin_hrn)
463 # call testbed callback first
464 # IIUC this is done on the local testbed TOO because of the refreshpeer link
465 if not api.driver.remove(record.__dict__):
466 logger.warning("driver.remove failed")
469 dbsession.delete(record)
474 # This is a PLC-specific thing, won't work with other platforms
475 def get_key_from_incoming_ip (self, api):
476 dbsession=api.dbsession()
477 # verify that the callers's ip address exist in the db and is an interface
478 # for a node in the db
479 (ip, port) = api.remote_addr
480 interfaces = api.driver.shell.GetInterfaces({'ip': ip}, ['node_id'])
482 raise NonExistingRecord("no such ip %(ip)s" % locals())
483 nodes = api.driver.shell.GetNodes([interfaces[0]['node_id']], ['node_id', 'hostname'])
485 raise NonExistingRecord("no such node using ip %(ip)s" % locals())
488 # look up the sfa record
489 record=dbsession.query(RegRecord).filter_by(type='node',pointer=node['node_id']).first()
491 raise RecordNotFound("node with pointer %s"%node['node_id'])
493 # generate a new keypair and gid
495 pkey = Keypair(create=True)
496 urn = hrn_to_urn(record.hrn, record.type)
497 gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey)
498 gid = gid_object.save_to_string(save_parents=True)
504 # attempt the scp the key
505 # and gid onto the node
506 # this will only work for planetlab based components
507 (kfd, key_filename) = tempfile.mkstemp()
508 (gfd, gid_filename) = tempfile.mkstemp()
509 pkey.save_to_file(key_filename)
510 gid_object.save_to_file(gid_filename, save_parents=True)
511 host = node['hostname']
512 key_dest="/etc/sfa/node.key"
513 gid_dest="/etc/sfa/node.gid"
515 #identity = "/etc/planetlab/root_ssh_key.rsa"
516 identity = "/etc/sfa/root_ssh_key"
517 scp_options=" -i %(identity)s " % locals()
518 scp_options+="-o StrictHostKeyChecking=no " % locals()
519 scp_key_command="%(scp)s %(scp_options)s %(key_filename)s root@%(host)s:%(key_dest)s" %\
521 scp_gid_command="%(scp)s %(scp_options)s %(gid_filename)s root@%(host)s:%(gid_dest)s" %\
524 all_commands = [scp_key_command, scp_gid_command]
526 for command in all_commands:
527 (status, output) = commands.getstatusoutput(command)
529 raise Exception, output
531 for filename in [key_filename, gid_filename]: