Cleanup the salt-key(salt.cli.SaltKey) binary parser.

Reused the output options and logging setup mix-ins.

Fixed a bug introduced in previous commit on `salt.utils.parsers.SaltCPOptionParser._mixin_after_parsed()`, function does not accept any arguments.
This commit is contained in:
Pedro Algarvio 2012-08-04 22:55:15 +01:00
parent f5aad4f8e2
commit 060f33a15a
4 changed files with 184 additions and 188 deletions

View File

@ -154,194 +154,30 @@ class SaltCP(parsers.SaltCPOptionParser):
cp_.run()
class SaltKey(object):
class SaltKey(parsers.SaltKeyOptionParser):
'''
Initialize the Salt key manager
'''
def __init__(self):
self.opts = self.__parse()
def __parse(self):
'''
Parse the command line options for the salt key
'''
parser = optparse.OptionParser(version="%%prog %s" % VERSION)
parser.add_option('-l',
'--list',
dest='list',
default='',
help=('List the public keys. Takes the args: '
'"pre", "un", "unaccepted": Unaccepted/unsigned keys '
'"acc", "accepted": Accepted/signed keys '
'"rej", "rejected": Rejected keys '
'"all": all keys'))
parser.add_option('-L',
'--list-all',
dest='list_all',
default=False,
action='store_true',
help='List all public keys. Deprecated: use "--list all"')
parser.add_option('-a',
'--accept',
dest='accept',
default='',
help='Accept the following key')
parser.add_option('-A',
'--accept-all',
dest='accept_all',
default=False,
action='store_true',
help='Accept all pending keys')
parser.add_option('-r',
'--reject',
dest='reject',
default='',
help='Reject the specified public key')
parser.add_option('-R',
'--reject-all',
dest='reject_all',
default=False,
action='store_true',
help='Reject all pending keys')
parser.add_option('-p',
'--print',
dest='print',
default='',
help='Print the specified public key')
parser.add_option('-P',
'--print-all',
dest='print_all',
default=False,
action='store_true',
help='Print all public keys')
parser.add_option('-d',
'--delete',
dest='delete',
default='',
help='Delete the named key')
parser.add_option('-D',
'--delete-all',
dest='delete_all',
default=False,
action='store_true',
help='Delete all keys')
parser.add_option('-q',
'--quiet',
dest='quiet',
default=False,
action='store_true',
help='Supress output')
parser.add_option('-y',
'--yes',
dest='yes',
default=False,
action='store_true',
help='Answer Yes to all questions presented, defaults to False'
)
parser.add_option('--key-logfile',
dest='key_logfile',
help=('Send all output to a file. '
'Default is /var/log/salt/key'))
parser.add_option('--gen-keys',
dest='gen_keys',
default='',
help='Set a name to generate a keypair for use with salt')
parser.add_option('--gen-keys-dir',
dest='gen_keys_dir',
default='.',
help=('Set the direcotry to save the generated keypair, '
'only works with "gen_keys_dir" option; default=.'))
parser.add_option('--keysize',
dest='keysize',
default=2048,
type=int,
help=('Set the keysize for the generated key, only works with '
'the "--gen-keys" option, the key size must be 2048 or '
'higher, otherwise it will be rounded up to 2048'
'; default=2048'))
parser.add_option('-c',
'--config',
dest='conf_file',
default='/etc/salt/master',
help='Pass in an alternative configuration file')
parser.add_option('--raw-out',
default=False,
action='store_true',
dest='raw_out',
help=('Print the output from the salt-key command in raw python '
'form, this is suitable for re-reading the output into '
'an executing python script with eval.'))
parser.add_option('--yaml-out',
default=False,
action='store_true',
dest='yaml_out',
help='Print the output from the salt-key command in yaml.')
parser.add_option('--json-out',
default=False,
action='store_true',
dest='json_out',
help='Print the output from the salt-key command in json.')
parser.add_option('--no-color',
default=False,
action='store_true',
dest='no_color',
help='Disable all colored output')
options, args = parser.parse_args()
opts = {}
opts.update(salt.config.master_config(options.conf_file))
for k, v in options.__dict__.items():
if k == 'keysize':
if v < 2048:
opts[k] = 2048
else:
opts[k] = v
elif v is not None:
opts[k] = v
# I decided to always set this to info, since it really all is info or
# error.
opts['loglevel'] = 'info'
return opts
def run(self):
'''
Execute saltkey
Execute salt-key
'''
self.parse_args()
verify_env([
os.path.join(self.opts['pki_dir'], 'minions'),
os.path.join(self.opts['pki_dir'], 'minions_pre'),
os.path.join(self.opts['pki_dir'], 'minions_rejected'),
os.path.dirname(self.opts['log_file']),
os.path.join(self.config['pki_dir'], 'minions'),
os.path.join(self.config['pki_dir'], 'minions_pre'),
os.path.join(self.config['pki_dir'], 'minions_rejected'),
os.path.dirname(self.config['log_file']),
],
self.opts['user'],
permissive=self.opts['permissive_pki_access'])
import salt.log
salt.log.setup_logfile_logger(self.opts['key_logfile'],
self.opts['loglevel'])
key = salt.cli.key.Key(self.opts)
self.config['user'],
permissive=self.config['permissive_pki_access']
)
self.setup_logfile_logger()
key = salt.cli.key.Key(self.config)
key.run()

View File

@ -668,15 +668,172 @@ class SaltCPOptionParser(OptionParser, ConfigDirMixIn, TimeoutMixIn,
usage = "%prog [options] '<target>' SOURCE DEST"
def _mixin_after_parsed(self, options, args):
def _mixin_after_parsed(self):
# salt-cp needs arguments
if len(args) <= 1:
if len(self.args) <= 1:
self.print_help()
self.exit(1)
if options.list:
self.config['tgt'] = args[0].split(',')
if self.options.list:
self.config['tgt'] = self.args[0].split(',')
else:
self.config['tgt'] = args[0]
self.config['src'] = args[1:-1]
self.config['dest'] = args[-1]
self.config['tgt'] = self.args[0]
self.config['src'] = self.args[1:-1]
self.config['dest'] = self.args[-1]
class SaltKeyOptionParser(OptionParser, ConfigDirMixIn, LogLevelMixIn,
OutputOptionsMixIn):
__metaclass__ = OptionParserMeta
_skip_console_logging_config_ = True
description = "XXX: Add salt-key description"
usage = "%prog [options]"
def _mixin_setup(self):
actions_group = optparse.OptionGroup(self, "Actions")
actions_group.add_option(
'-l', '--list',
default='',
help=('List the public keys. Takes the args: '
'"pre", "un", "unaccepted": Unaccepted/unsigned keys '
'"acc", "accepted": Accepted/signed keys '
'"rej", "rejected": Rejected keys '
'"all": all keys')
)
actions_group.add_option(
'-L', '--list-all',
default=False,
action='store_true',
help='List all public keys. Deprecated: use "--list all"'
)
actions_group.add_option(
'-a', '--accept',
default='',
help='Accept the following key'
)
actions_group.add_option(
'-A', '--accept-all',
default=False,
action='store_true',
help='Accept all pending keys'
)
actions_group.add_option(
'-r', '--reject',
default='',
help='Reject the specified public key'
)
actions_group.add_option(
'-R', '--reject-all',
default=False,
action='store_true',
help='Reject all pending keys'
)
actions_group.add_option(
'-p', '--print',
default='',
help='Print the specified public key'
)
actions_group.add_option(
'-P', '--print-all',
default=False,
action='store_true',
help='Print all public keys'
)
actions_group.add_option(
'-d', '--delete',
default='',
help='Delete the named key'
)
actions_group.add_option(
'-D', '--delete-all',
default=False,
action='store_true',
help='Delete all keys'
)
self.add_option_group(actions_group)
self.add_option(
'--key-logfile',
help=("DEPRECATED: Please use '--log-file' instead.\n"
"Send all output to a file.")
)
self.add_option(
'--log-file',
default='/var/log/salt/key',
help=('Send all output to a file. Default is %default')
)
self.add_option(
'-q', '--quiet',
default=False,
action='store_true',
help='Suppress output'
)
self.add_option(
'-y', '--yes',
default=False,
action='store_true',
help='Answer Yes to all questions presented, defaults to False'
)
key_options_group = optparse.OptionGroup(self, "Key Generation Options")
self.add_option_group(key_options_group)
key_options_group.add_option(
'--gen-keys',
default='',
help='Set a name to generate a keypair for use with salt'
)
key_options_group.add_option(
'--gen-keys-dir',
default='.',
help=('Set the directory to save the generated keypair, only '
'works with "gen_keys_dir" option; default=.')
)
key_options_group.add_option(
'--keysize',
default=2048,
type=int,
help=('Set the keysize for the generated key, only works with '
'the "--gen-keys" option, the key size must be 2048 or '
'higher, otherwise it will be rounded up to 2048; '
'; default=%default')
)
def setup_config(self):
return config.master_config(self.get_config_file_path('master'))
def process_keysize(self):
if self.options.keysize < 2048:
self.error("The minimum value for keysize is 2048")
elif self.options.keysize > 32768:
self.error("The maximum value for keysize is 32768")
def process_key_logfile(self):
if self.options.key_logfile:
sys.stderr.write("The '--key-logfile' option is deprecated and "
"will be removed in the future. Please use "
"'--log-file' instead.")
self.config["log_file"] = self.options.key_logfile
def _mixin_after_parsed(self):
# It was decided to always set this to info, since it really all is
# info or error.
self.config['loglevel'] = 'info'

View File

@ -379,7 +379,7 @@ class ShellCase(TestCase):
'''
Execute salt-key
'''
mconf = os.path.join(INTEGRATION_TEST_DIR, 'files', 'conf', 'master')
mconf = os.path.join(INTEGRATION_TEST_DIR, 'files', 'conf')
arg_str = '-c {0} {1}'.format(mconf, arg_str)
return self.run_script('salt-key', arg_str)

View File

@ -7,10 +7,13 @@ import integration
from integration import TestDaemon
class KeyTest(integration.ShellCase):
class KeyTest(integration.ShellCase, integration.ShellCaseCommonTestsMixIn):
'''
Test salt-key script
'''
_call_binary_ = 'salt-key'
def test_list(self):
'''
test salt-key -L