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 from sfa.storage.alchemy import dbsession
23 ### the types that we need to exclude from sqlobjects before being able to dump
24 # them on the xmlrpc wire
25 from sqlalchemy.orm.collections import InstrumentedList
27 class RegistryManager:
29 def __init__ (self, config): pass
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 = self.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)
62 record=dbsession.query(RegRecord).filter_by(type=type,hrn=hrn).first()
64 raise RecordNotFound("hrn=%s, type=%s"%(hrn,type))
67 # if caller_xrn is not specified assume the caller is the record
71 caller_gid = record.get_gid_object()
73 caller_hrn, caller_type = urn_to_hrn(caller_xrn)
75 caller_record = dbsession.query(RegRecord).filter_by(hrn=caller_hrn,type=caller_type).first()
77 caller_record = dbsession.query(RegRecord).filter_by(hrn=caller_hrn).first()
79 raise RecordNotFound("Unable to associated caller (hrn=%s, type=%s) with credential for (hrn: %s, type: %s)"%(caller_hrn, caller_type, hrn, type))
80 caller_gid = GID(string=caller_record.gid)
82 object_hrn = record.get_gid_object().get_hrn()
83 # call the builtin authorization/credential generation engine
84 rights = api.auth.determine_user_rights(caller_hrn, record)
85 # make sure caller has rights to this object
87 raise PermissionError("%s has no rights to %s (%s)" % \
88 (caller_hrn, object_hrn, xrn))
89 object_gid = GID(string=record.gid)
90 new_cred = Credential(subject = object_gid.get_subject())
91 new_cred.set_gid_caller(caller_gid)
92 new_cred.set_gid_object(object_gid)
93 new_cred.set_issuer_keys(auth_info.get_privkey_filename(), auth_info.get_gid_filename())
94 #new_cred.set_pubkey(object_gid.get_pubkey())
95 new_cred.set_privileges(rights)
96 new_cred.get_privileges().delegate_all_privileges(True)
97 if hasattr(record,'expires'):
98 date = utcparse(record.expires)
99 expires = datetime_to_epoch(date)
100 new_cred.set_expiration(int(expires))
101 auth_kind = "authority,ma,sa"
102 # Parent not necessary, verify with certs
103 #new_cred.set_parent(api.auth.hierarchy.get_auth_cred(auth_hrn, kind=auth_kind))
107 return new_cred.save_to_string(save_parents=True)
110 # the default for full, which means 'dig into the testbed as well', should be false
111 def Resolve(self, api, xrns, type=None, details=False):
113 if not isinstance(xrns, types.ListType):
114 # try to infer type if not set and we get a single input
116 type = Xrn(xrns).get_type()
118 hrns = [urn_to_hrn(xrn)[0] for xrn in xrns]
120 # load all known registry names into a prefix tree and attempt to find
121 # the longest matching prefix
122 # create a dict where key is a registry hrn and its value is a list
123 # of hrns at that registry (determined by the known prefix tree).
125 registries = api.registries
127 registry_hrns = registries.keys()
128 tree.load(registry_hrns)
130 registry_hrn = tree.best_match(urn_to_hrn(xrn)[0])
131 if registry_hrn not in xrn_dict:
132 xrn_dict[registry_hrn] = []
133 xrn_dict[registry_hrn].append(xrn)
136 for registry_hrn in xrn_dict:
137 # skip the hrn without a registry hrn
138 # XX should we let the user know the authority is unknown?
142 # if the best match (longest matching hrn) is not the local registry,
143 # forward the request
144 xrns = xrn_dict[registry_hrn]
145 if registry_hrn != api.hrn:
146 credential = api.getCredential()
147 interface = api.registries[registry_hrn]
148 server_proxy = api.server_proxy(interface, credential)
149 # should propagate the details flag but that's not supported in the xmlrpc interface yet
150 #peer_records = server_proxy.Resolve(xrns, credential,type, details=details)
151 peer_records = server_proxy.Resolve(xrns, credential)
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()
166 for local_record in local_records:
167 augment_with_sfa_builtins (local_record)
169 logger.info("Resolve, (details=%s,type=%s) local_records=%s "%(details,type,local_records))
170 local_dicts = [ record.__dict__ for record in local_records ]
173 # in details mode we get as much info as we can, which involves contacting the
174 # testbed for getting implementation details about the record
175 self.driver.augment_records_with_testbed_info(local_dicts)
176 # also we fill the 'url' field for known authorities
177 # used to be in the driver code, sounds like a poorman thing though
178 def solve_neighbour_url (record):
179 if not record.type.startswith('authority'): return
181 for neighbour_dict in [ api.aggregates, api.registries ]:
182 if hrn in neighbour_dict:
183 record.url=neighbour_dict[hrn].get_url()
185 for record in local_records: solve_neighbour_url (record)
187 # convert local record objects to dicts for xmlrpc
188 # xxx somehow here calling dict(record) issues a weird error
189 # however record.todict() seems to work fine
190 # records.extend( [ dict(record) for record in local_records ] )
191 records.extend( [ record.todict(exclude_types=[InstrumentedList]) for record in local_records ] )
194 raise RecordNotFound(str(hrns))
198 def List (self, api, xrn, origin_hrn=None, options={}):
199 # load all know registry names into a prefix tree and attempt to find
200 # the longest matching prefix
201 hrn, type = urn_to_hrn(xrn)
202 registries = api.registries
203 registry_hrns = registries.keys()
205 tree.load(registry_hrns)
206 registry_hrn = tree.best_match(hrn)
208 #if there was no match then this record belongs to an unknow registry
210 raise MissingAuthority(xrn)
211 # if the best match (longest matching hrn) is not the local registry,
212 # forward the request
214 if registry_hrn != api.hrn:
215 credential = api.getCredential()
216 interface = api.registries[registry_hrn]
217 server_proxy = api.server_proxy(interface, credential)
218 record_list = server_proxy.List(xrn, credential, options)
219 # same as above, no need to process what comes from through xmlrpc
220 # pass foreign records as-is
221 record_dicts = record_list
223 # if we still have not found the record yet, try the local registry
224 # logger.debug("before trying local records, %d foreign records"% len(record_dicts))
227 if ('recursive' in options and options['recursive']):
229 elif hrn.endswith('*'):
233 if not api.auth.hierarchy.auth_exists(hrn):
234 raise MissingAuthority(hrn)
236 records = dbsession.query(RegRecord).filter(RegRecord.hrn.startswith(hrn)).all()
237 # logger.debug("recursive mode, found %d local records"%(len(records)))
239 records = dbsession.query(RegRecord).filter_by(authority=hrn).all()
240 # logger.debug("non recursive mode, found %d local records"%(len(records)))
241 # so that sfi list can show more than plain names...
242 for record in records: augment_with_sfa_builtins (record)
243 record_dicts=[ record.todict(exclude_types=[InstrumentedList]) for record in records ]
248 def CreateGid(self, api, xrn, cert):
250 authority = Xrn(xrn=xrn).get_authority_hrn()
251 auth_info = api.auth.get_auth_info(authority)
253 pkey = Keypair(create=True)
255 certificate = Certificate(string=cert)
256 pkey = certificate.get_pubkey()
257 gid = api.auth.hierarchy.create_gid(xrn, create_uuid(), pkey)
258 return gid.save_to_string(save_parents=True)
261 # utility for handling relationships among the SFA objects
263 # subject_record describes the subject of the relationships
264 # ref_record contains the target values for the various relationships we need to manage
265 # (to begin with, this is just the slice x person (researcher) and authority x person (pi) relationships)
266 def update_driver_relations (self, subject_obj, ref_obj):
267 type=subject_obj.type
268 #for (k,v) in subject_obj.__dict__.items(): print k,'=',v
269 if type=='slice' and hasattr(ref_obj,'researcher'):
270 self.update_driver_relation(subject_obj, ref_obj.researcher, 'user', 'researcher')
271 elif type=='authority' and hasattr(ref_obj,'pi'):
272 self.update_driver_relation(subject_obj,ref_obj.pi, 'user', 'pi')
274 # field_key is the name of one field in the record, typically 'researcher' for a 'slice' record
275 # hrns is the list of hrns that should be linked to the subject from now on
276 # target_type would be e.g. 'user' in the 'slice' x 'researcher' example
277 def update_driver_relation (self, record_obj, hrns, target_type, relation_name):
278 # locate the linked objects in our db
279 subject_type=record_obj.type
280 subject_id=record_obj.pointer
281 # get the 'pointer' field of all matching records
282 link_id_tuples = dbsession.query(RegRecord.pointer).filter_by(type=target_type).filter(RegRecord.hrn.in_(hrns)).all()
283 # sqlalchemy returns named tuples for columns
284 link_ids = [ tuple.pointer for tuple in link_id_tuples ]
285 self.driver.update_relation (subject_type, target_type, relation_name, subject_id, link_ids)
287 def Register(self, api, record_dict):
289 hrn, type = record_dict['hrn'], record_dict['type']
290 urn = hrn_to_urn(hrn,type)
292 if type not in ['authority', 'slice', 'node', 'user']:
293 raise UnknownSfaType(type)
295 # check if record_dict already exists
296 existing_records = dbsession.query(RegRecord).filter_by(type=type,hrn=hrn).all()
298 raise ExistingRecord(hrn)
300 assert ('type' in record_dict)
301 # returns the right type of RegRecord according to type in record
302 record = make_record(dict=record_dict)
303 record.just_created()
304 record.authority = get_authority(record.hrn)
305 auth_info = api.auth.get_auth_info(record.authority)
307 # make sure record has a gid
310 pkey = Keypair(create=True)
311 if getattr(record,'keys',None):
313 # use only first key in record
314 if isinstance(record.keys, types.ListType):
315 pub_key = record.keys[0]
316 pkey = convert_public_key(pub_key)
318 gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey)
319 gid = gid_object.save_to_string(save_parents=True)
322 if isinstance (record, RegAuthority):
324 if not api.auth.hierarchy.auth_exists(hrn):
325 api.auth.hierarchy.create_auth(hrn_to_urn(hrn,'authority'))
327 # get the GID from the newly created authority
328 auth_info = api.auth.get_auth_info(hrn)
329 gid = auth_info.get_gid_object()
330 record.gid=gid.save_to_string(save_parents=True)
332 # locate objects for relationships
333 pi_hrns = getattr(record,'pi',None)
334 if pi_hrns is not None: record.update_pis (pi_hrns)
336 elif isinstance (record, RegSlice):
337 researcher_hrns = getattr(record,'researcher',None)
338 if researcher_hrns is not None: record.update_researchers (researcher_hrns)
340 elif isinstance (record, RegUser):
341 # create RegKey objects for incoming keys
342 if hasattr(record,'keys'):
343 logger.debug ("creating %d keys for user %s"%(len(record.keys),record.hrn))
344 record.reg_keys = [ RegKey (key) for key in record.keys ]
346 # update testbed-specific data if needed
347 pointer = self.driver.register (record.__dict__, hrn, pub_key)
349 record.pointer=pointer
350 dbsession.add(record)
353 # update membership for researchers, pis, owners, operators
354 self.update_driver_relations (record, record)
356 return record.get_gid_object().save_to_string(save_parents=True)
358 def Update(self, api, record_dict):
359 assert ('type' in record_dict)
360 new_record=make_record(dict=record_dict)
361 (type,hrn) = (new_record.type, new_record.hrn)
363 # make sure the record exists
364 record = dbsession.query(RegRecord).filter_by(type=type,hrn=hrn).first()
366 raise RecordNotFound("hrn=%s, type=%s"%(hrn,type))
367 record.just_updated()
369 # Use the pointer from the existing record, not the one that the user
370 # gave us. This prevents the user from inserting a forged pointer
371 pointer = record.pointer
373 # is there a change in keys ?
376 if getattr(new_record,'keys',None):
377 new_key=new_record.keys
378 if isinstance (new_key,types.ListType):
381 # take new_key into account
383 # update the openssl key and gid
384 pkey = convert_public_key(new_key)
386 urn = hrn_to_urn(hrn,type)
387 gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey)
388 gid = gid_object.save_to_string(save_parents=True)
390 # xxx should do side effects from new_record to record
391 # not too sure how to do that
392 # not too big a deal with planetlab as the driver is authoritative, but...
394 # update native relations
395 if isinstance (record, RegSlice):
396 researcher_hrns = getattr(new_record,'researcher',None)
397 if researcher_hrns is not None: record.update_researchers (researcher_hrns)
399 elif isinstance (record, RegAuthority):
400 pi_hrns = getattr(new_record,'pi',None)
401 if pi_hrns is not None: record.update_pis (pi_hrns)
403 # update the PLC information that was specified with the record
404 # xxx oddly enough, without this useless statement,
405 # record.__dict__ as received by the driver seems to be off
406 # anyway the driver should receive an object
407 # (and then extract __dict__ itself if needed)
408 print "DO NOT REMOVE ME before driver.update, record=%s"%record
411 (pointer, new_key_pointer) = self.driver.update (record.__dict__, new_record.__dict__, hrn, new_key)
414 if new_key and new_key_pointer:
415 record.reg_keys=[ RegKey (new_key, new_key_pointer)]
419 # update membership for researchers, pis, owners, operators
420 self.update_driver_relations (record, new_record)
424 # expecting an Xrn instance
425 def Remove(self, api, xrn, origin_hrn=None):
428 request=dbsession.query(RegRecord).filter_by(hrn=hrn)
429 if type and type not in ['all', '*']:
430 request=request.filter_by(type=type)
432 record = request.first()
434 msg="Could not find hrn %s"%hrn
435 if type: msg += " type=%s"%type
436 raise RecordNotFound(msg)
439 if type not in ['slice', 'user', 'node', 'authority'] :
440 raise UnknownSfaType(type)
442 credential = api.getCredential()
443 registries = api.registries
445 # Try to remove the object from the PLCDB of federated agg.
446 # This is attempted before removing the object from the local agg's PLCDB and sfa table
447 if hrn.startswith(api.hrn) and type in ['user', 'slice', 'authority']:
448 for registry in registries:
449 if registry not in [api.hrn]:
451 result=registries[registry].remove_peer_object(credential, record, origin_hrn)
455 # call testbed callback first
456 # IIUC this is done on the local testbed TOO because of the refreshpeer link
457 if not self.driver.remove(record.__dict__):
458 logger.warning("driver.remove failed")
461 dbsession.delete(record)
466 # This is a PLC-specific thing, won't work with other platforms
467 def get_key_from_incoming_ip (self, api):
468 # verify that the callers's ip address exist in the db and is an interface
469 # for a node in the db
470 (ip, port) = api.remote_addr
471 interfaces = self.driver.shell.GetInterfaces({'ip': ip}, ['node_id'])
473 raise NonExistingRecord("no such ip %(ip)s" % locals())
474 nodes = self.driver.shell.GetNodes([interfaces[0]['node_id']], ['node_id', 'hostname'])
476 raise NonExistingRecord("no such node using ip %(ip)s" % locals())
479 # look up the sfa record
480 record=dbsession.query(RegRecord).filter_by(type='node',pointer=node['node_id']).first()
482 raise RecordNotFound("node with pointer %s"%node['node_id'])
484 # generate a new keypair and gid
486 pkey = Keypair(create=True)
487 urn = hrn_to_urn(record.hrn, record.type)
488 gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey)
489 gid = gid_object.save_to_string(save_parents=True)
495 # attempt the scp the key
496 # and gid onto the node
497 # this will only work for planetlab based components
498 (kfd, key_filename) = tempfile.mkstemp()
499 (gfd, gid_filename) = tempfile.mkstemp()
500 pkey.save_to_file(key_filename)
501 gid_object.save_to_file(gid_filename, save_parents=True)
502 host = node['hostname']
503 key_dest="/etc/sfa/node.key"
504 gid_dest="/etc/sfa/node.gid"
506 #identity = "/etc/planetlab/root_ssh_key.rsa"
507 identity = "/etc/sfa/root_ssh_key"
508 scp_options=" -i %(identity)s " % locals()
509 scp_options+="-o StrictHostKeyChecking=no " % locals()
510 scp_key_command="%(scp)s %(scp_options)s %(key_filename)s root@%(host)s:%(key_dest)s" %\
512 scp_gid_command="%(scp)s %(scp_options)s %(gid_filename)s root@%(host)s:%(gid_dest)s" %\
515 all_commands = [scp_key_command, scp_gid_command]
517 for command in all_commands:
518 (status, output) = commands.getstatusoutput(command)
520 raise Exception, output
522 for filename in [key_filename, gid_filename]: