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 # Is this a root or sub authority
51 auth_hrn = api.auth.get_authority(hrn)
52 if not auth_hrn or hrn == api.config.SFA_INTERFACE_HRN:
54 auth_info = api.auth.get_auth_info(auth_hrn)
56 record=dbsession.query(RegRecord).filter_by(type=type,hrn=hrn).first()
58 raise RecordNotFound("hrn=%s, type=%s"%(hrn,type))
61 # if caller_xrn is not specified assume the caller is the record
65 caller_gid = record.get_gid_object()
67 caller_hrn, caller_type = urn_to_hrn(caller_xrn)
69 caller_record = dbsession.query(RegRecord).filter_by(hrn=caller_hrn,type=caller_type).first()
71 caller_record = dbsession.query(RegRecord).filter_by(hrn=caller_hrn).first()
73 raise RecordNotFound("Unable to associated caller (hrn=%s, type=%s) with credential for (hrn: %s, type: %s)"%(caller_hrn, caller_type, hrn, type))
74 caller_gid = GID(string=caller_record.gid)
76 object_hrn = record.get_gid_object().get_hrn()
77 # call the builtin authorization/credential generation engine
78 rights = api.auth.determine_user_rights(caller_hrn, record)
79 # make sure caller has rights to this object
81 raise PermissionError("%s has no rights to %s (%s)" % \
82 (caller_hrn, object_hrn, xrn))
83 object_gid = GID(string=record.gid)
84 new_cred = Credential(subject = object_gid.get_subject())
85 new_cred.set_gid_caller(caller_gid)
86 new_cred.set_gid_object(object_gid)
87 new_cred.set_issuer_keys(auth_info.get_privkey_filename(), auth_info.get_gid_filename())
88 #new_cred.set_pubkey(object_gid.get_pubkey())
89 new_cred.set_privileges(rights)
90 new_cred.get_privileges().delegate_all_privileges(True)
91 if hasattr(record,'expires'):
92 date = utcparse(record.expires)
93 expires = datetime_to_epoch(date)
94 new_cred.set_expiration(int(expires))
95 auth_kind = "authority,ma,sa"
96 # Parent not necessary, verify with certs
97 #new_cred.set_parent(api.auth.hierarchy.get_auth_cred(auth_hrn, kind=auth_kind))
101 return new_cred.save_to_string(save_parents=True)
104 # the default for full, which means 'dig into the testbed as well', should be false
105 def Resolve(self, api, xrns, type=None, details=False):
107 if not isinstance(xrns, types.ListType):
108 # try to infer type if not set and we get a single input
110 type = Xrn(xrns).get_type()
112 hrns = [urn_to_hrn(xrn)[0] for xrn in xrns]
114 # load all known registry names into a prefix tree and attempt to find
115 # the longest matching prefix
116 # create a dict where key is a registry hrn and its value is a list
117 # of hrns at that registry (determined by the known prefix tree).
119 registries = api.registries
121 registry_hrns = registries.keys()
122 tree.load(registry_hrns)
124 registry_hrn = tree.best_match(urn_to_hrn(xrn)[0])
125 if registry_hrn not in xrn_dict:
126 xrn_dict[registry_hrn] = []
127 xrn_dict[registry_hrn].append(xrn)
130 for registry_hrn in xrn_dict:
131 # skip the hrn without a registry hrn
132 # XX should we let the user know the authority is unknown?
136 # if the best match (longest matching hrn) is not the local registry,
137 # forward the request
138 xrns = xrn_dict[registry_hrn]
139 if registry_hrn != api.hrn:
140 credential = api.getCredential()
141 interface = api.registries[registry_hrn]
142 server_proxy = api.server_proxy(interface, credential)
143 # should propagate the details flag but that's not supported in the xmlrpc interface yet
144 #peer_records = server_proxy.Resolve(xrns, credential,type, details=details)
145 peer_records = server_proxy.Resolve(xrns, credential)
146 # pass foreign records as-is
147 # previous code used to read
148 # records.extend([SfaRecord(dict=record).as_dict() for record in peer_records])
149 # not sure why the records coming through xmlrpc had to be processed at all
150 records.extend(peer_records)
152 # try resolving the remaining unfound records at the local registry
153 local_hrns = list ( set(hrns).difference([record['hrn'] for record in records]) )
155 local_records = dbsession.query(RegRecord).filter(RegRecord.hrn.in_(local_hrns))
157 local_records = local_records.filter_by(type=type)
158 local_records=local_records.all()
160 for local_record in local_records:
161 augment_with_sfa_builtins (local_record)
163 logger.info("Resolve, (details=%s,type=%s) local_records=%s "%(details,type,local_records))
164 local_dicts = [ record.__dict__ for record in local_records ]
167 # in details mode we get as much info as we can, which involves contacting the
168 # testbed for getting implementation details about the record
169 self.driver.augment_records_with_testbed_info(local_dicts)
170 # also we fill the 'url' field for known authorities
171 # used to be in the driver code, sounds like a poorman thing though
172 def solve_neighbour_url (record):
173 if not record.type.startswith('authority'): return
175 for neighbour_dict in [ api.aggregates, api.registries ]:
176 if hrn in neighbour_dict:
177 record.url=neighbour_dict[hrn].get_url()
179 for record in local_records: solve_neighbour_url (record)
181 # convert local record objects to dicts for xmlrpc
182 # xxx somehow here calling dict(record) issues a weird error
183 # however record.todict() seems to work fine
184 # records.extend( [ dict(record) for record in local_records ] )
185 records.extend( [ record.todict(exclude_types=[InstrumentedList]) for record in local_records ] )
188 raise RecordNotFound(str(hrns))
192 def List (self, api, xrn, origin_hrn=None, options={}):
193 # load all know registry names into a prefix tree and attempt to find
194 # the longest matching prefix
195 hrn, type = urn_to_hrn(xrn)
196 registries = api.registries
197 registry_hrns = registries.keys()
199 tree.load(registry_hrns)
200 registry_hrn = tree.best_match(hrn)
202 #if there was no match then this record belongs to an unknow registry
204 raise MissingAuthority(xrn)
205 # if the best match (longest matching hrn) is not the local registry,
206 # forward the request
208 if registry_hrn != api.hrn:
209 credential = api.getCredential()
210 interface = api.registries[registry_hrn]
211 server_proxy = api.server_proxy(interface, credential)
212 record_list = server_proxy.List(xrn, credential, options)
213 # same as above, no need to process what comes from through xmlrpc
214 # pass foreign records as-is
215 record_dicts = record_list
217 # if we still have not found the record yet, try the local registry
218 # logger.debug("before trying local records, %d foreign records"% len(record_dicts))
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)).all()
231 # logger.debug("recursive mode, found %d local records"%(len(records)))
233 records = dbsession.query(RegRecord).filter_by(authority=hrn).all()
234 # logger.debug("non recursive mode, found %d local records"%(len(records)))
235 # so that sfi list can show more than plain names...
236 for record in records: augment_with_sfa_builtins (record)
237 record_dicts=[ record.todict(exclude_types=[InstrumentedList]) for record in records ]
242 def CreateGid(self, api, xrn, cert):
244 authority = Xrn(xrn=xrn).get_authority_hrn()
245 auth_info = api.auth.get_auth_info(authority)
247 pkey = Keypair(create=True)
249 certificate = Certificate(string=cert)
250 pkey = certificate.get_pubkey()
251 gid = api.auth.hierarchy.create_gid(xrn, create_uuid(), pkey)
252 return gid.save_to_string(save_parents=True)
255 # utility for handling relationships among the SFA objects
257 # subject_record describes the subject of the relationships
258 # ref_record contains the target values for the various relationships we need to manage
259 # (to begin with, this is just the slice x person (researcher) and authority x person (pi) relationships)
260 def update_driver_relations (self, subject_obj, ref_obj):
261 type=subject_obj.type
262 #for (k,v) in subject_obj.__dict__.items(): print k,'=',v
263 if type=='slice' and hasattr(ref_obj,'researcher'):
264 self.update_driver_relation(subject_obj, ref_obj.researcher, 'user', 'researcher')
265 elif type=='authority' and hasattr(ref_obj,'pi'):
266 self.update_driver_relation(subject_obj,ref_obj.pi, 'user', 'pi')
268 # field_key is the name of one field in the record, typically 'researcher' for a 'slice' record
269 # hrns is the list of hrns that should be linked to the subject from now on
270 # target_type would be e.g. 'user' in the 'slice' x 'researcher' example
271 def update_driver_relation (self, record_obj, hrns, target_type, relation_name):
272 # locate the linked objects in our db
273 subject_type=record_obj.type
274 subject_id=record_obj.pointer
275 # get the 'pointer' field of all matching records
276 link_id_tuples = dbsession.query(RegRecord.pointer).filter_by(type=target_type).filter(RegRecord.hrn.in_(hrns)).all()
277 # sqlalchemy returns named tuples for columns
278 link_ids = [ tuple.pointer for tuple in link_id_tuples ]
279 self.driver.update_relation (subject_type, target_type, relation_name, subject_id, link_ids)
281 def Register(self, api, record_dict):
283 hrn, type = record_dict['hrn'], record_dict['type']
284 urn = hrn_to_urn(hrn,type)
286 if type not in ['authority', 'slice', 'node', 'user']:
287 raise UnknownSfaType(type)
289 # check if record_dict already exists
290 existing_records = dbsession.query(RegRecord).filter_by(type=type,hrn=hrn).all()
292 raise ExistingRecord(hrn)
294 assert ('type' in record_dict)
295 # returns the right type of RegRecord according to type in record
296 record = make_record(dict=record_dict)
297 record.just_created()
298 record.authority = get_authority(record.hrn)
299 auth_info = api.auth.get_auth_info(record.authority)
301 # make sure record has a gid
304 pkey = Keypair(create=True)
305 if getattr(record,'keys',None):
307 # use only first key in record
308 if isinstance(record.keys, types.ListType):
309 pub_key = record.keys[0]
310 pkey = convert_public_key(pub_key)
312 gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey)
313 gid = gid_object.save_to_string(save_parents=True)
316 if isinstance (record, RegAuthority):
318 if not api.auth.hierarchy.auth_exists(hrn):
319 api.auth.hierarchy.create_auth(hrn_to_urn(hrn,'authority'))
321 # get the GID from the newly created authority
322 auth_info = api.auth.get_auth_info(hrn)
323 gid = auth_info.get_gid_object()
324 record.gid=gid.save_to_string(save_parents=True)
326 # locate objects for relationships
327 pi_hrns = getattr(record,'pi',None)
328 if pi_hrns is not None: record.update_pis (pi_hrns)
330 elif isinstance (record, RegSlice):
331 researcher_hrns = getattr(record,'researcher',None)
332 if researcher_hrns is not None: record.update_researchers (researcher_hrns)
334 elif isinstance (record, RegUser):
335 # create RegKey objects for incoming keys
336 if hasattr(record,'keys'):
337 logger.debug ("creating %d keys for user %s"%(len(record.keys),record.hrn))
338 record.reg_keys = [ RegKey (key) for key in record.keys ]
340 # update testbed-specific data if needed
341 pointer = self.driver.register (record.__dict__, hrn, pub_key)
343 record.pointer=pointer
344 dbsession.add(record)
347 # update membership for researchers, pis, owners, operators
348 self.update_driver_relations (record, record)
350 return record.get_gid_object().save_to_string(save_parents=True)
352 def Update(self, api, record_dict):
353 assert ('type' in record_dict)
354 new_record=make_record(dict=record_dict)
355 (type,hrn) = (new_record.type, new_record.hrn)
357 # make sure the record exists
358 record = dbsession.query(RegRecord).filter_by(type=type,hrn=hrn).first()
360 raise RecordNotFound("hrn=%s, type=%s"%(hrn,type))
361 record.just_updated()
363 # Use the pointer from the existing record, not the one that the user
364 # gave us. This prevents the user from inserting a forged pointer
365 pointer = record.pointer
367 # is there a change in keys ?
370 if getattr(new_record,'keys',None):
371 new_key=new_record.keys
372 if isinstance (new_key,types.ListType):
375 # take new_key into account
377 # update the openssl key and gid
378 pkey = convert_public_key(new_key)
380 urn = hrn_to_urn(hrn,type)
381 gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey)
382 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)
393 elif isinstance (record, RegAuthority):
394 pi_hrns = getattr(new_record,'pi',None)
395 if pi_hrns is not None: record.update_pis (pi_hrns)
397 # update the PLC information that was specified with the record
398 # xxx oddly enough, without this useless statement,
399 # record.__dict__ as received by the driver seems to be off
400 # anyway the driver should receive an object
401 # (and then extract __dict__ itself if needed)
402 print "DO NOT REMOVE ME before driver.update, record=%s"%record
405 (pointer, new_key_pointer) = self.driver.update (record.__dict__, new_record.__dict__, hrn, new_key)
408 if new_key and new_key_pointer:
409 record.reg_keys=[ RegKey (new_key, new_key_pointer)]
413 # update membership for researchers, pis, owners, operators
414 self.update_driver_relations (record, new_record)
418 # expecting an Xrn instance
419 def Remove(self, api, xrn, origin_hrn=None):
422 request=dbsession.query(RegRecord).filter_by(hrn=hrn)
423 if type and type not in ['all', '*']:
424 request=request.filter_by(type=type)
426 record = request.first()
428 msg="Could not find hrn %s"%hrn
429 if type: msg += " type=%s"%type
430 raise RecordNotFound(msg)
433 if type not in ['slice', 'user', 'node', 'authority'] :
434 raise UnknownSfaType(type)
436 credential = api.getCredential()
437 registries = api.registries
439 # Try to remove the object from the PLCDB of federated agg.
440 # This is attempted before removing the object from the local agg's PLCDB and sfa table
441 if hrn.startswith(api.hrn) and type in ['user', 'slice', 'authority']:
442 for registry in registries:
443 if registry not in [api.hrn]:
445 result=registries[registry].remove_peer_object(credential, record, origin_hrn)
449 # call testbed callback first
450 # IIUC this is done on the local testbed TOO because of the refreshpeer link
451 if not self.driver.remove(record.__dict__):
452 logger.warning("driver.remove failed")
455 dbsession.delete(record)
460 # This is a PLC-specific thing, won't work with other platforms
461 def get_key_from_incoming_ip (self, api):
462 # verify that the callers's ip address exist in the db and is an interface
463 # for a node in the db
464 (ip, port) = api.remote_addr
465 interfaces = self.driver.shell.GetInterfaces({'ip': ip}, ['node_id'])
467 raise NonExistingRecord("no such ip %(ip)s" % locals())
468 nodes = self.driver.shell.GetNodes([interfaces[0]['node_id']], ['node_id', 'hostname'])
470 raise NonExistingRecord("no such node using ip %(ip)s" % locals())
473 # look up the sfa record
474 record=dbsession.query(RegRecord).filter_by(type='node',pointer=node['node_id']).first()
476 raise RecordNotFound("node with pointer %s"%node['node_id'])
478 # generate a new keypair and gid
480 pkey = Keypair(create=True)
481 urn = hrn_to_urn(record.hrn, record.type)
482 gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey)
483 gid = gid_object.save_to_string(save_parents=True)
489 # attempt the scp the key
490 # and gid onto the node
491 # this will only work for planetlab based components
492 (kfd, key_filename) = tempfile.mkstemp()
493 (gfd, gid_filename) = tempfile.mkstemp()
494 pkey.save_to_file(key_filename)
495 gid_object.save_to_file(gid_filename, save_parents=True)
496 host = node['hostname']
497 key_dest="/etc/sfa/node.key"
498 gid_dest="/etc/sfa/node.gid"
500 #identity = "/etc/planetlab/root_ssh_key.rsa"
501 identity = "/etc/sfa/root_ssh_key"
502 scp_options=" -i %(identity)s " % locals()
503 scp_options+="-o StrictHostKeyChecking=no " % locals()
504 scp_key_command="%(scp)s %(scp_options)s %(key_filename)s root@%(host)s:%(key_dest)s" %\
506 scp_gid_command="%(scp)s %(scp_options)s %(gid_filename)s root@%(host)s:%(gid_dest)s" %\
509 all_commands = [scp_key_command, scp_gid_command]
511 for command in all_commands:
512 (status, output) = commands.getstatusoutput(command)
514 raise Exception, output
516 for filename in [key_filename, gid_filename]: