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):
44 dbsession = api.dbsession()
47 hrn = urn_to_hrn(xrn)[0]
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 if type == 'sliver' or '-' in Xrn(hrn).leaf:
54 slice_xrn = api.driver.sliver_to_slice_xrn(hrn)
57 # Is this a root or sub authority
58 auth_hrn = api.auth.get_authority(hrn)
59 if not auth_hrn or hrn == api.config.SFA_INTERFACE_HRN:
61 auth_info = api.auth.get_auth_info(auth_hrn)
63 record=dbsession.query(RegRecord).filter_by(type=type,hrn=hrn).first()
65 raise RecordNotFound("hrn=%s, type=%s"%(hrn,type))
68 # if caller_xrn is not specified assume the caller is the record
72 caller_gid = record.get_gid_object()
74 caller_hrn, caller_type = urn_to_hrn(caller_xrn)
76 caller_record = dbsession.query(RegRecord).filter_by(hrn=caller_hrn,type=caller_type).first()
78 caller_record = dbsession.query(RegRecord).filter_by(hrn=caller_hrn).first()
80 raise RecordNotFound("Unable to associated caller (hrn=%s, type=%s) with credential for (hrn: %s, type: %s)"%(caller_hrn, caller_type, hrn, type))
81 caller_gid = GID(string=caller_record.gid)
83 object_hrn = record.get_gid_object().get_hrn()
84 # call the builtin authorization/credential generation engine
85 rights = api.auth.determine_user_rights(caller_hrn, record)
86 # make sure caller has rights to this object
88 raise PermissionError("%s has no rights to %s (%s)" % \
89 (caller_hrn, object_hrn, xrn))
90 object_gid = GID(string=record.gid)
91 new_cred = Credential(subject = object_gid.get_subject())
92 new_cred.set_gid_caller(caller_gid)
93 new_cred.set_gid_object(object_gid)
94 new_cred.set_issuer_keys(auth_info.get_privkey_filename(), auth_info.get_gid_filename())
95 #new_cred.set_pubkey(object_gid.get_pubkey())
96 new_cred.set_privileges(rights)
97 new_cred.get_privileges().delegate_all_privileges(True)
98 if hasattr(record,'expires'):
99 date = utcparse(record.expires)
100 expires = datetime_to_epoch(date)
101 new_cred.set_expiration(int(expires))
102 auth_kind = "authority,ma,sa"
103 # Parent not necessary, verify with certs
104 #new_cred.set_parent(api.auth.hierarchy.get_auth_cred(auth_hrn, kind=auth_kind))
108 return new_cred.save_to_string(save_parents=True)
111 # the default for full, which means 'dig into the testbed as well', should be false
112 def Resolve(self, api, xrns, type=None, details=False):
114 dbsession = api.dbsession()
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 # should propagate the details flag but that's not supported in the xmlrpc interface yet
152 #peer_records = server_proxy.Resolve(xrns, credential,type, details=details)
153 peer_records = server_proxy.Resolve(xrns, credential)
154 # pass foreign records as-is
155 # previous code used to read
156 # records.extend([SfaRecord(dict=record).as_dict() for record in peer_records])
157 # not sure why the records coming through xmlrpc had to be processed at all
158 records.extend(peer_records)
160 # try resolving the remaining unfound records at the local registry
161 local_hrns = list ( set(hrns).difference([record['hrn'] for record in records]) )
163 local_records = dbsession.query(RegRecord).filter(RegRecord.hrn.in_(local_hrns))
165 local_records = local_records.filter_by(type=type)
166 local_records=local_records.all()
168 for local_record in local_records:
169 augment_with_sfa_builtins (local_record)
171 logger.info("Resolve, (details=%s,type=%s) local_records=%s "%(details,type,local_records))
172 local_dicts = [ record.__dict__ for record in local_records ]
175 # in details mode we get as much info as we can, which involves contacting the
176 # testbed for getting implementation details about the record
177 api.driver.augment_records_with_testbed_info(local_dicts)
178 # also we fill the 'url' field for known authorities
179 # used to be in the driver code, sounds like a poorman thing though
180 def solve_neighbour_url (record):
181 if not record.type.startswith('authority'): return
183 for neighbour_dict in [ api.aggregates, api.registries ]:
184 if hrn in neighbour_dict:
185 record.url=neighbour_dict[hrn].get_url()
187 for record in local_records: solve_neighbour_url (record)
189 # convert local record objects to dicts for xmlrpc
190 # xxx somehow here calling dict(record) issues a weird error
191 # however record.todict() seems to work fine
192 # records.extend( [ dict(record) for record in local_records ] )
193 records.extend( [ record.todict(exclude_types=[InstrumentedList]) for record in local_records ] )
196 raise RecordNotFound(str(hrns))
200 def List (self, api, xrn, origin_hrn=None, options={}):
201 dbsession=api.dbsession()
202 # load all know registry names into a prefix tree and attempt to find
203 # the longest matching prefix
204 hrn, type = urn_to_hrn(xrn)
205 registries = api.registries
206 registry_hrns = registries.keys()
208 tree.load(registry_hrns)
209 registry_hrn = tree.best_match(hrn)
211 #if there was no match then this record belongs to an unknow registry
213 raise MissingAuthority(xrn)
214 # if the best match (longest matching hrn) is not the local registry,
215 # forward the request
217 if registry_hrn != api.hrn:
218 credential = api.getCredential()
219 interface = api.registries[registry_hrn]
220 server_proxy = api.server_proxy(interface, credential)
221 record_list = server_proxy.List(xrn, credential, options)
222 # same as above, no need to process what comes from through xmlrpc
223 # pass foreign records as-is
224 record_dicts = record_list
226 # if we still have not found the record yet, try the local registry
227 # logger.debug("before trying local records, %d foreign records"% len(record_dicts))
230 if ('recursive' in options and options['recursive']):
232 elif hrn.endswith('*'):
236 if not api.auth.hierarchy.auth_exists(hrn):
237 raise MissingAuthority(hrn)
239 records = dbsession.query(RegRecord).filter(RegRecord.hrn.startswith(hrn)).all()
240 # logger.debug("recursive mode, found %d local records"%(len(records)))
242 records = dbsession.query(RegRecord).filter_by(authority=hrn).all()
243 # logger.debug("non recursive mode, found %d local records"%(len(records)))
244 # so that sfi list can show more than plain names...
245 for record in records: augment_with_sfa_builtins (record)
246 record_dicts=[ record.todict(exclude_types=[InstrumentedList]) for record in records ]
251 def CreateGid(self, api, xrn, cert):
253 authority = Xrn(xrn=xrn).get_authority_hrn()
254 auth_info = api.auth.get_auth_info(authority)
256 pkey = Keypair(create=True)
258 certificate = Certificate(string=cert)
259 pkey = certificate.get_pubkey()
260 gid = api.auth.hierarchy.create_gid(xrn, create_uuid(), pkey)
261 return gid.save_to_string(save_parents=True)
264 # utility for handling relationships among the SFA objects
266 # subject_record describes the subject of the relationships
267 # ref_record contains the target values for the various relationships we need to manage
268 # (to begin with, this is just the slice x person (researcher) and authority x person (pi) relationships)
269 def update_driver_relations (self, api, subject_obj, ref_obj):
270 type=subject_obj.type
271 #for (k,v) in subject_obj.__dict__.items(): print k,'=',v
272 if type=='slice' and hasattr(ref_obj,'researcher'):
273 self.update_driver_relation(api, subject_obj, ref_obj.researcher, 'user', 'researcher')
274 elif type=='authority' and hasattr(ref_obj,'pi'):
275 self.update_driver_relation(api, subject_obj,ref_obj.pi, 'user', 'pi')
277 # field_key is the name of one field in the record, typically 'researcher' for a 'slice' record
278 # hrns is the list of hrns that should be linked to the subject from now on
279 # target_type would be e.g. 'user' in the 'slice' x 'researcher' example
280 def update_driver_relation (self, api, record_obj, hrns, target_type, relation_name):
281 dbsession=api.dbsession()
282 # locate the linked objects in our db
283 subject_type=record_obj.type
284 subject_id=record_obj.pointer
285 # get the 'pointer' field of all matching records
286 link_id_tuples = dbsession.query(RegRecord.pointer).filter_by(type=target_type).filter(RegRecord.hrn.in_(hrns)).all()
287 # sqlalchemy returns named tuples for columns
288 link_ids = [ tuple.pointer for tuple in link_id_tuples ]
289 api.driver.update_relation (subject_type, target_type, relation_name, subject_id, link_ids)
291 def Register(self, api, record_dict):
293 dbsession=api.dbsession()
294 hrn, type = record_dict['hrn'], record_dict['type']
295 urn = hrn_to_urn(hrn,type)
297 if type not in ['authority', 'slice', 'node', 'user']:
298 raise UnknownSfaType(type)
300 # check if record_dict already exists
301 existing_records = dbsession.query(RegRecord).filter_by(type=type,hrn=hrn).all()
303 raise ExistingRecord(hrn)
305 assert ('type' in record_dict)
306 # returns the right type of RegRecord according to type in record
307 record = make_record(dict=record_dict)
308 record.just_created()
309 record.authority = get_authority(record.hrn)
310 auth_info = api.auth.get_auth_info(record.authority)
312 # make sure record has a gid
315 pkey = Keypair(create=True)
316 if getattr(record,'keys',None):
318 # use only first key in record
319 if isinstance(record.keys, types.ListType):
320 pub_key = record.keys[0]
321 pkey = convert_public_key(pub_key)
323 gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey)
324 gid = gid_object.save_to_string(save_parents=True)
327 if isinstance (record, RegAuthority):
329 if not api.auth.hierarchy.auth_exists(hrn):
330 api.auth.hierarchy.create_auth(hrn_to_urn(hrn,'authority'))
332 # get the GID from the newly created authority
333 auth_info = api.auth.get_auth_info(hrn)
334 gid = auth_info.get_gid_object()
335 record.gid=gid.save_to_string(save_parents=True)
337 # locate objects for relationships
338 pi_hrns = getattr(record,'pi',None)
339 if pi_hrns is not None: record.update_pis (pi_hrns, dbsession)
341 elif isinstance (record, RegSlice):
342 researcher_hrns = getattr(record,'researcher',None)
343 if researcher_hrns is not None: record.update_researchers (researcher_hrns, dbsession)
345 elif isinstance (record, RegUser):
346 # create RegKey objects for incoming keys
347 if hasattr(record,'keys'):
348 logger.debug ("creating %d keys for user %s"%(len(record.keys),record.hrn))
349 record.reg_keys = [ RegKey (key) for key in record.keys ]
351 # update testbed-specific data if needed
352 pointer = api.driver.register (record.__dict__, hrn, pub_key)
354 record.pointer=pointer
355 dbsession.add(record)
358 # update membership for researchers, pis, owners, operators
359 self.update_driver_relations (api, record, record)
361 return record.get_gid_object().save_to_string(save_parents=True)
363 def Update(self, api, record_dict):
364 dbsession=api.dbsession()
365 assert ('type' in record_dict)
366 new_record=make_record(dict=record_dict)
367 (type,hrn) = (new_record.type, new_record.hrn)
369 # make sure the record exists
370 record = dbsession.query(RegRecord).filter_by(type=type,hrn=hrn).first()
372 raise RecordNotFound("hrn=%s, type=%s"%(hrn,type))
373 record.just_updated()
375 # Use the pointer from the existing record, not the one that the user
376 # gave us. This prevents the user from inserting a forged pointer
377 pointer = record.pointer
379 # is there a change in keys ?
382 if getattr(new_record,'keys',None):
383 new_key=new_record.keys
384 if isinstance (new_key,types.ListType):
387 # take new_key into account
389 # update the openssl key and gid
390 pkey = convert_public_key(new_key)
392 urn = hrn_to_urn(hrn,type)
393 gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey)
394 gid = gid_object.save_to_string(save_parents=True)
396 # xxx should do side effects from new_record to record
397 # not too sure how to do that
398 # not too big a deal with planetlab as the driver is authoritative, but...
400 # update native relations
401 if isinstance (record, RegSlice):
402 researcher_hrns = getattr(new_record,'researcher',None)
403 if researcher_hrns is not None: record.update_researchers (researcher_hrns, dbsession)
405 elif isinstance (record, RegAuthority):
406 pi_hrns = getattr(new_record,'pi',None)
407 if pi_hrns is not None: record.update_pis (pi_hrns, dbsession)
409 # update the PLC information that was specified with the record
410 # xxx oddly enough, without this useless statement,
411 # record.__dict__ as received by the driver seems to be off
412 # anyway the driver should receive an object
413 # (and then extract __dict__ itself if needed)
414 print "DO NOT REMOVE ME before driver.update, record=%s"%record
417 (pointer, new_key_pointer) = api.driver.update (record.__dict__, new_record.__dict__, hrn, new_key)
420 if new_key and new_key_pointer:
421 record.reg_keys=[ RegKey (new_key, new_key_pointer)]
425 # update membership for researchers, pis, owners, operators
426 self.update_driver_relations (api, record, new_record)
430 # expecting an Xrn instance
431 def Remove(self, api, xrn, origin_hrn=None):
432 dbsession=api.dbsession()
435 request=dbsession.query(RegRecord).filter_by(hrn=hrn)
436 if type and type not in ['all', '*']:
437 request=request.filter_by(type=type)
439 record = request.first()
441 msg="Could not find hrn %s"%hrn
442 if type: msg += " type=%s"%type
443 raise RecordNotFound(msg)
446 if type not in ['slice', 'user', 'node', 'authority'] :
447 raise UnknownSfaType(type)
449 credential = api.getCredential()
450 registries = api.registries
452 # Try to remove the object from the PLCDB of federated agg.
453 # This is attempted before removing the object from the local agg's PLCDB and sfa table
454 if hrn.startswith(api.hrn) and type in ['user', 'slice', 'authority']:
455 for registry in registries:
456 if registry not in [api.hrn]:
458 result=registries[registry].remove_peer_object(credential, record, origin_hrn)
462 # call testbed callback first
463 # IIUC this is done on the local testbed TOO because of the refreshpeer link
464 if not api.driver.remove(record.__dict__):
465 logger.warning("driver.remove failed")
468 dbsession.delete(record)
473 # This is a PLC-specific thing, won't work with other platforms
474 def get_key_from_incoming_ip (self, api):
475 dbsession=api.dbsession()
476 # verify that the callers's ip address exist in the db and is an interface
477 # for a node in the db
478 (ip, port) = api.remote_addr
479 interfaces = api.driver.shell.GetInterfaces({'ip': ip}, ['node_id'])
481 raise NonExistingRecord("no such ip %(ip)s" % locals())
482 nodes = api.driver.shell.GetNodes([interfaces[0]['node_id']], ['node_id', 'hostname'])
484 raise NonExistingRecord("no such node using ip %(ip)s" % locals())
487 # look up the sfa record
488 record=dbsession.query(RegRecord).filter_by(type='node',pointer=node['node_id']).first()
490 raise RecordNotFound("node with pointer %s"%node['node_id'])
492 # generate a new keypair and gid
494 pkey = Keypair(create=True)
495 urn = hrn_to_urn(record.hrn, record.type)
496 gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey)
497 gid = gid_object.save_to_string(save_parents=True)
503 # attempt the scp the key
504 # and gid onto the node
505 # this will only work for planetlab based components
506 (kfd, key_filename) = tempfile.mkstemp()
507 (gfd, gid_filename) = tempfile.mkstemp()
508 pkey.save_to_file(key_filename)
509 gid_object.save_to_file(gid_filename, save_parents=True)
510 host = node['hostname']
511 key_dest="/etc/sfa/node.key"
512 gid_dest="/etc/sfa/node.gid"
514 #identity = "/etc/planetlab/root_ssh_key.rsa"
515 identity = "/etc/sfa/root_ssh_key"
516 scp_options=" -i %(identity)s " % locals()
517 scp_options+="-o StrictHostKeyChecking=no " % locals()
518 scp_key_command="%(scp)s %(scp_options)s %(key_filename)s root@%(host)s:%(key_dest)s" %\
520 scp_gid_command="%(scp)s %(scp_options)s %(gid_filename)s root@%(host)s:%(gid_dest)s" %\
523 all_commands = [scp_key_command, scp_gid_command]
525 for command in all_commands:
526 (status, output) = commands.getstatusoutput(command)
528 raise Exception, output
530 for filename in [key_filename, gid_filename]: