5 from pprint import pformat, PrettyPrinter
6 from optparse import OptionParser
8 from sfa.generic import Generic
9 from sfa.util.xrn import Xrn
10 from sfa.storage.record import Record
12 from sfa.trust.hierarchy import Hierarchy
13 from sfa.trust.gid import GID
14 from sfa.trust.certificate import convert_public_key
16 from sfa.client.common import optparse_listvalue_callback, optparse_dictvalue_callback, terminal_render, filter_records
17 from sfa.client.candidates import Candidates
18 from sfa.client.sfi import save_records_to_file
20 pprinter = PrettyPrinter(indent=4)
23 help_basedir=Hierarchy().basedir
25 help_basedir='*unable to locate Hierarchy().basedir'
27 def add_options(*args, **kwargs):
29 func.__dict__.setdefault('add_options', []).insert(0, (args, kwargs))
33 class Commands(object):
34 def _get_commands(self):
36 for attrib in dir(self):
37 if callable(getattr(self, attrib)) and not attrib.startswith('_'):
38 command_names.append(attrib)
42 class RegistryCommands(Commands):
43 def __init__(self, *args, **kwds):
44 self.api= Generic.the_flavour().make_api(interface='registry')
47 """Display the Registry version"""
48 version = self.api.manager.GetVersion(self.api, {})
49 pprinter.pprint(version)
51 @add_options('-x', '--xrn', dest='xrn', metavar='<xrn>', help='authority to list (hrn/urn - mandatory)')
52 @add_options('-t', '--type', dest='type', metavar='<type>', help='object type', default='all')
53 @add_options('-r', '--recursive', dest='recursive', metavar='<recursive>', help='list all child records',
54 action='store_true', default=False)
55 @add_options('-v', '--verbose', dest='verbose', action='store_true', default=False)
56 def list(self, xrn, type=None, recursive=False, verbose=False):
57 """List names registered at a given authority - possibly filtered by type"""
59 options_dict = {'recursive': recursive}
60 records = self.api.manager.List(self.api, xrn.get_hrn(), options=options_dict)
61 list = filter_records(type, records)
62 # terminal_render expects an options object
65 options.verbose=verbose
66 terminal_render (list, options)
69 @add_options('-x', '--xrn', dest='xrn', metavar='<xrn>', help='object hrn/urn (mandatory)')
70 @add_options('-t', '--type', dest='type', metavar='<type>', help='object type', default=None)
71 @add_options('-o', '--outfile', dest='outfile', metavar='<outfile>', help='save record to file')
72 @add_options('-f', '--format', dest='format', metavar='<display>', type='choice',
73 choices=('text', 'xml', 'simple'), help='display record in different formats')
74 def show(self, xrn, type=None, format=None, outfile=None):
75 """Display details for a registered object"""
76 records = self.api.manager.Resolve(self.api, xrn, type, details=True)
77 for record in records:
78 sfa_record = Record(dict=record)
79 sfa_record.dump(format)
81 save_records_to_file(outfile, records)
84 def _record_dict(self, xrn, type, email, key,
85 slices, researchers, pis,
86 url, description, extras):
93 record_dict['urn'] = xrn.get_urn()
94 record_dict['hrn'] = xrn.get_hrn()
95 record_dict['type'] = xrn.get_type()
97 record_dict['url'] = url
99 record_dict['description'] = description
102 pubkey = open(key, 'r').read()
105 record_dict['keys'] = [pubkey]
107 record_dict['slices'] = slices
109 record_dict['reg-researchers'] = researchers
111 record_dict['email'] = email
113 record_dict['reg-pis'] = pis
115 record_dict.update(extras)
119 @add_options('-x', '--xrn', dest='xrn', metavar='<xrn>', help='object hrn/urn', default=None)
120 @add_options('-t', '--type', dest='type', metavar='<type>', help='object type (mandatory)',)
121 @add_options('-a', '--all', dest='all', metavar='<all>', action='store_true', default=False, help='check all users GID')
122 @add_options('-v', '--verbose', dest='verbose', metavar='<verbose>', action='store_true', default=False, help='verbose mode: display user\'s hrn ')
123 def check_gid(self, xrn=None, type=None, all=None, verbose=None):
124 """Check the correspondance between the GID and the PubKey"""
127 from sfa.storage.model import RegRecord
128 db_query = self.api.dbsession().query(RegRecord).filter_by(type=type)
130 hrn = Xrn(xrn).get_hrn()
131 db_query = db_query.filter_by(hrn=hrn)
133 print "Use either -a or -x <xrn>, not both !!!"
135 elif not all and not xrn:
136 print "Use either -a or -x <xrn>, one of them is mandatory !!!"
139 records = db_query.all()
141 print "No Record found"
148 for record in records:
149 # get the pubkey stored in SFA DB
151 db_pubkey_str = record.reg_keys[0].key
153 db_pubkey_obj = convert_public_key(db_pubkey_str)
155 ERROR.append(record.hrn)
158 NOKEY.append(record.hrn)
161 # get the pubkey from the gid
163 gid_obj = GID(string = gid_str)
164 gid_pubkey_obj = gid_obj.get_pubkey()
166 # Check if gid_pubkey_obj and db_pubkey_obj are the same
167 check = gid_pubkey_obj.is_same(db_pubkey_obj)
169 OK.append(record.hrn)
171 NOK.append(record.hrn)
174 print "Users NOT having a PubKey: %s\n\
175 Users having a non RSA PubKey: %s\n\
176 Users having a GID/PubKey correpondence OK: %s\n\
177 Users having a GID/PubKey correpondence Not OK: %s\n"%(len(NOKEY), len(ERROR), len(OK), len(NOK))
179 print "Users NOT having a PubKey: %s and are: \n%s\n\n\
180 Users having a non RSA PubKey: %s and are: \n%s\n\n\
181 Users having a GID/PubKey correpondence OK: %s and are: \n%s\n\n\
182 Users having a GID/PubKey correpondence NOT OK: %s and are: \n%s\n\n"%(len(NOKEY),NOKEY, len(ERROR), ERROR, len(OK), OK, len(NOK), NOK)
186 @add_options('-x', '--xrn', dest='xrn', metavar='<xrn>', help='object hrn/urn (mandatory)')
187 @add_options('-t', '--type', dest='type', metavar='<type>', help='object type', default=None)
188 @add_options('-e', '--email', dest='email', default="",
189 help="email (mandatory for users)")
190 @add_options('-u', '--url', dest='url', metavar='<url>', default=None,
191 help="URL, useful for slices")
192 @add_options('-d', '--description', dest='description', metavar='<description>',
193 help='Description, useful for slices', default=None)
194 @add_options('-k', '--key', dest='key', metavar='<key>', help='public key string or file',
196 @add_options('-s', '--slices', dest='slices', metavar='<slices>', help='Set/replace slice xrns',
197 default='', type="str", action='callback', callback=optparse_listvalue_callback)
198 @add_options('-r', '--researchers', dest='researchers', metavar='<researchers>', help='Set/replace slice researchers',
199 default='', type="str", action='callback', callback=optparse_listvalue_callback)
200 @add_options('-p', '--pis', dest='pis', metavar='<PIs>',
201 help='Set/replace Principal Investigators/Project Managers',
202 default='', type="str", action='callback', callback=optparse_listvalue_callback)
203 @add_options('-X','--extra',dest='extras',default={},type='str',metavar="<EXTRA_ASSIGNS>",
204 action="callback", callback=optparse_dictvalue_callback, nargs=1,
205 help="set extra/testbed-dependent flags, e.g. --extra enabled=true")
206 def register(self, xrn, type=None, email='', key=None,
207 slices='', pis='', researchers='',
208 url=None, description=None, extras={}):
209 """Create a new Registry record"""
210 record_dict = self._record_dict(xrn=xrn, type=type, email=email, key=key,
211 slices=slices, researchers=researchers, pis=pis,
212 url=url, description=description, extras=extras)
213 self.api.manager.Register(self.api, record_dict)
216 @add_options('-x', '--xrn', dest='xrn', metavar='<xrn>', help='object hrn/urn (mandatory)')
217 @add_options('-t', '--type', dest='type', metavar='<type>', help='object type', default=None)
218 @add_options('-u', '--url', dest='url', metavar='<url>', help='URL', default=None)
219 @add_options('-d', '--description', dest='description', metavar='<description>',
220 help='Description', default=None)
221 @add_options('-k', '--key', dest='key', metavar='<key>', help='public key string or file',
223 @add_options('-s', '--slices', dest='slices', metavar='<slices>', help='Set/replace slice xrns',
224 default='', type="str", action='callback', callback=optparse_listvalue_callback)
225 @add_options('-r', '--researchers', dest='researchers', metavar='<researchers>', help='Set/replace slice researchers',
226 default='', type="str", action='callback', callback=optparse_listvalue_callback)
227 @add_options('-p', '--pis', dest='pis', metavar='<PIs>',
228 help='Set/replace Principal Investigators/Project Managers',
229 default='', type="str", action='callback', callback=optparse_listvalue_callback)
230 @add_options('-X','--extra',dest='extras',default={},type='str',metavar="<EXTRA_ASSIGNS>",
231 action="callback", callback=optparse_dictvalue_callback, nargs=1,
232 help="set extra/testbed-dependent flags, e.g. --extra enabled=true")
233 def update(self, xrn, type=None, email='', key=None,
234 slices='', pis='', researchers='',
235 url=None, description=None, extras={}):
236 """Update an existing Registry record"""
237 record_dict = self._record_dict(xrn=xrn, type=type, email=email, key=key,
238 slices=slices, researchers=researchers, pis=pis,
239 url=url, description=description, extras=extras)
240 self.api.manager.Update(self.api, record_dict)
242 @add_options('-x', '--xrn', dest='xrn', metavar='<xrn>', help='object hrn/urn (mandatory)')
243 @add_options('-t', '--type', dest='type', metavar='<type>', help='object type', default=None)
244 def remove(self, xrn, type=None):
245 """Remove given object from the registry"""
247 self.api.manager.Remove(self.api, xrn)
250 @add_options('-x', '--xrn', dest='xrn', metavar='<xrn>', help='object hrn/urn (mandatory)')
251 @add_options('-t', '--type', dest='type', metavar='<type>', help='object type', default=None)
252 def credential(self, xrn, type=None):
253 """Invoke GetCredential"""
254 cred = self.api.manager.GetCredential(self.api, xrn, type, self.api.hrn)
258 def import_registry(self):
259 """Run the importer"""
260 from sfa.importer import Importer
261 importer = Importer()
265 """Initialize or upgrade the db"""
266 from sfa.storage.dbschema import DBSchema
268 dbschema.init_or_upgrade()
270 @add_options('-a', '--all', dest='all', metavar='<all>', action='store_true', default=False,
271 help='Remove all registry records and all files in %s area' % help_basedir)
272 @add_options('-c', '--certs', dest='certs', metavar='<certs>', action='store_true', default=False,
273 help='Remove all cached certs/gids found in %s' % help_basedir )
274 @add_options('-0', '--no-reinit', dest='reinit', metavar='<reinit>', action='store_false', default=True,
275 help='Prevents new DB schema from being installed after cleanup')
276 def nuke(self, all=False, certs=False, reinit=True):
277 """Cleanup local registry DB, plus various additional filesystem cleanups optionally"""
278 from sfa.storage.dbschema import DBSchema
279 from sfa.util.sfalogging import _SfaLogger
280 logger = _SfaLogger(logfile='/var/log/sfa_import.log', loggername='importlog')
281 logger.setLevelFromOptVerbose(self.api.config.SFA_API_LOGLEVEL)
282 logger.info("Purging SFA records from database")
286 # for convenience we re-create the schema here, so there's no need for an explicit
287 # service sfa restart
288 # however in some (upgrade) scenarios this might be wrong
290 logger.info("re-creating empty schema")
291 dbschema.init_or_upgrade()
293 # remove the server certificate and all gids found in /var/lib/sfa/authorities
295 logger.info("Purging cached certificates")
296 for (dir, _, files) in os.walk('/var/lib/sfa/authorities'):
298 if file.endswith('.gid') or file == 'server.cert':
302 # just remove all files that do not match 'server.key' or 'server.cert'
304 logger.info("Purging registry filesystem cache")
305 preserved_files = [ 'server.key', 'server.cert']
306 for (dir,_,files) in os.walk(Hierarchy().basedir):
308 if file in preserved_files: continue
313 class CertCommands(Commands):
315 def __init__(self, *args, **kwds):
316 self.api= Generic.the_flavour().make_api(interface='registry')
318 def import_gid(self, xrn):
321 @add_options('-x', '--xrn', dest='xrn', metavar='<xrn>', help='object hrn/urn (mandatory)')
322 @add_options('-t', '--type', dest='type', metavar='<type>', help='object type', default=None)
323 @add_options('-o', '--outfile', dest='outfile', metavar='<outfile>', help='output file', default=None)
324 def export(self, xrn, type=None, outfile=None):
325 """Fetch an object's GID from the Registry"""
326 from sfa.storage.model import RegRecord
327 hrn = Xrn(xrn).get_hrn()
328 request=self.api.dbsession().query(RegRecord).filter_by(hrn=hrn)
329 if type: request = request.filter_by(type=type)
330 record=request.first()
332 gid = GID(string=record.gid)
334 # check the authorities hierarchy
335 hierarchy = Hierarchy()
337 auth_info = hierarchy.get_auth_info(hrn)
338 gid = auth_info.gid_object
340 print "Record: %s not found" % hrn
344 outfile = os.path.abspath('./%s.gid' % gid.get_hrn())
345 gid.save_to_file(outfile, save_parents=True)
347 @add_options('-g', '--gidfile', dest='gid', metavar='<gid>', help='path of gid file to display (mandatory)')
348 def display(self, gidfile):
349 """Print contents of a GID file"""
350 gid_path = os.path.abspath(gidfile)
351 if not gid_path or not os.path.isfile(gid_path):
352 print "No such gid file: %s" % gidfile
354 gid = GID(filename=gid_path)
355 gid.dump(dump_parents=True)
358 class AggregateCommands(Commands):
360 def __init__(self, *args, **kwds):
361 self.api= Generic.the_flavour().make_api(interface='aggregate')
364 """Display the Aggregate version"""
365 version = self.api.manager.GetVersion(self.api, {})
366 pprinter.pprint(version)
368 @add_options('-x', '--xrn', dest='xrn', metavar='<xrn>', help='object hrn/urn (mandatory)')
369 def status(self, xrn):
370 """Retrieve the status of the slivers belonging to the named slice (Status)"""
371 urns = [Xrn(xrn, 'slice').get_urn()]
372 status = self.api.manager.Status(self.api, urns, [], {})
373 pprinter.pprint(status)
375 @add_options('-r', '--rspec-version', dest='rspec_version', metavar='<rspec_version>',
376 default='GENI', help='version/format of the resulting rspec response')
377 def resources(self, rspec_version='GENI'):
378 """Display the available resources at an aggregate"""
379 options = {'geni_rspec_version': rspec_version}
381 resources = self.api.manager.ListResources(self.api, [], options)
385 @add_options('-x', '--xrn', dest='xrn', metavar='<xrn>', help='slice hrn/urn (mandatory)')
386 @add_options('-r', '--rspec', dest='rspec', metavar='<rspec>', help='rspec file (mandatory)')
387 def allocate(self, xrn, rspec):
388 """Allocate slivers"""
389 xrn = Xrn(xrn, 'slice')
390 slice_urn=xrn.get_urn()
391 rspec_string = open(rspec).read()
393 manifest = self.api.manager.Allocate(self.api, slice_urn, [], rspec_string, options)
397 @add_options('-x', '--xrn', dest='xrn', metavar='<xrn>', help='slice hrn/urn (mandatory)')
398 def provision(self, xrn):
399 """Provision slivers"""
400 xrn = Xrn(xrn, 'slice')
401 slice_urn=xrn.get_urn()
403 manifest = self.api.manager.provision(self.api, [slice_urn], [], options)
408 @add_options('-x', '--xrn', dest='xrn', metavar='<xrn>', help='slice hrn/urn (mandatory)')
409 def delete(self, xrn):
411 self.api.manager.Delete(self.api, [xrn], [], {})
416 class SliceManagerCommands(AggregateCommands):
418 def __init__(self, *args, **kwds):
419 self.api= Generic.the_flavour().make_api(interface='slicemgr')
424 CATEGORIES = {'certificate': CertCommands,
425 'registry': RegistryCommands,
426 'aggregate': AggregateCommands,
427 'slicemgr': SliceManagerCommands}
429 # returns (name,class) or (None,None)
430 def find_category (self, input):
431 full_name=Candidates (SfaAdmin.CATEGORIES.keys()).only_match(input)
432 if not full_name: return (None,None)
433 return (full_name,SfaAdmin.CATEGORIES[full_name])
435 def summary_usage (self, category=None):
436 print "Usage:", self.script_name + " category command [<options>]"
437 if category and category in SfaAdmin.CATEGORIES:
438 categories=[category]
440 categories=SfaAdmin.CATEGORIES
442 cls=SfaAdmin.CATEGORIES[c]
443 print "==================== category=%s"%c
444 names=cls.__dict__.keys()
447 method=cls.__dict__[name]
448 if name.startswith('_'): continue
450 format="%%-%ds"%margin
452 doc=getattr(method,'__doc__',None)
454 print "<missing __doc__>"
456 lines=[line.strip() for line in doc.split("\n")]
459 for extra_line in lines: print margin*" ",extra_line
463 argv = copy.deepcopy(sys.argv)
464 self.script_name = argv.pop(0)
465 # ensure category is specified
469 # ensure category is valid
470 category_input = argv.pop(0)
471 (category_name, category_class) = self.find_category (category_input)
472 if not category_name or not category_class:
473 self.summary_usage(category_name)
475 usage = "%%prog %s command [options]" % (category_name)
476 parser = OptionParser(usage=usage)
478 # ensure command is valid
479 category_instance = category_class()
480 commands = category_instance._get_commands()
482 # xxx what is this about ?
483 command_name = '__call__'
485 command_input = argv.pop(0)
486 command_name = Candidates (commands).only_match (command_input)
488 if command_name and hasattr(category_instance, command_name):
489 command = getattr(category_instance, command_name)
491 self.summary_usage(category_name)
493 # ensure options are valid
494 usage = "%%prog %s %s [options]" % (category_name, command_name)
495 parser = OptionParser(usage=usage)
496 for args, kwdargs in getattr(command, 'add_options', []):
497 parser.add_option(*args, **kwdargs)
498 (opts, cmd_args) = parser.parse_args(argv)
499 cmd_kwds = vars(opts)
501 # dont overrride meth
502 for k, v in cmd_kwds.items():
508 #print "invoking %s *=%s **=%s"%(command.__name__,cmd_args, cmd_kwds)
509 command(*cmd_args, **cmd_kwds)
512 print "Possible wrong number of arguments supplied"
514 #traceback.print_exc()
515 print command.__doc__
520 print "Command failed, please check log for more info"