예제 #1
0
    shell_call('docker rm %s' % name, terminal=True)
    shell_call('docker build -t %s docker/%s' % (name, folder), terminal=True)


supported_os = [
    'ubuntu1604', 'ubuntu1404', 'ubuntu1404-plus', 'ubuntu1004', 'debian8',
    'centos6', 'centos7'
]

usage = "usage: %prog -h"

option_list = (
    Option(
        '--rebuild',
        action='store_true',
        dest='rebuild',
        help='Rebuild before run (False by default)',
        default=False,
    ),
    Option(
        '--drop',
        action='store_true',
        dest='drop',
        help='Drop everything before run (False by default)',
        default=False,
    ),
    Option(
        '--background',
        action='store_true',
        dest='background',
        help='Run in background (False by default)',
예제 #2
0
def main():
    optionsTable = [
        Option('--enable-deploy',
               action='store_true',
               help='Allow rhncfg-client to deploy files.',
               default=0),
        Option('--enable-diff',
               action='store_true',
               help='Allow rhncfg-client to diff files.',
               default=0),
        Option('--enable-upload',
               action='store_true',
               help='Allow rhncfg-client to upload files.',
               default=0),
        Option('--enable-mtime-upload',
               action='store_true',
               help='Allow rhncfg-client to upload mtime.',
               default=0),
        Option(
            '--enable-run',
            action='store_true',
            help='Allow rhncfg-client the ability to execute remote scripts.',
            default=0),
        Option('--enable-all',
               action='store_true',
               help='Allow rhncfg-client to do everything.',
               default=0),
        Option('--disable-deploy',
               action='store_true',
               help='Disable deployment.',
               default=0),
        Option('--disable-diff',
               action='store_true',
               help='Disable diff.',
               default=0),
        Option('--disable-upload',
               action='store_true',
               help='Disable upload.',
               default=0),
        Option('--disable-mtime-upload',
               action='store_true',
               help='Disable mtime upload.',
               default=0),
        Option('--disable-run',
               action='store_true',
               help='Disable remote script execution.',
               default=0),
        Option('--disable-all',
               action='store_true',
               help='Disable all options.',
               default=0),
        Option('-f',
               '--force',
               action='store_true',
               help='Force the operation without confirmation',
               default=0),
        Option(
            '--report',
            action='store_true',
            help='Report the status of the mode settings (enabled or disabled)',
            default=0),
    ]

    parser = OptionParser(option_list=optionsTable)
    (options, args) = parser.parse_args()

    creator = ModeControllerCreator.get_controller_creator()
    controller = creator.create_controller()
    controller.set_force(options.force)

    runcreator = ModeControllerCreator.get_run_controller_creator()
    runcontroller = runcreator.create_controller()
    runcontroller.set_force(options.force)

    if options.enable_deploy:
        controller.on('deploy')

    if options.enable_diff:
        controller.on('diff')

    if options.enable_upload:
        controller.on('upload')

    if options.enable_mtime_upload:
        controller.on('mtime_upload')

    if options.enable_all:
        controller.all_on()
        runcontroller.all_on()

    if options.enable_run:
        runcontroller.on('run')
        runcontroller.off('all')

    if options.disable_deploy:
        controller.off('deploy')

    if options.disable_diff:
        controller.off('diff')

    if options.disable_upload:
        controller.off('upload')

    if options.disable_mtime_upload:
        controller.off('mtime_upload')

    if options.disable_all:
        controller.all_off()
        runcontroller.all_off()

    if options.disable_run:
        runcontroller.off('run')
        runcontroller.off('all')

    if options.report:
        mode_list = ['deploy', 'diff', 'upload', 'mtime_upload']

        for m in mode_list:
            rstring = "%s is %s"
            status = "disabled"
            if controller.is_on(m):
                status = "enabled"
            print rstring % (m, status)

        status = "disabled"
        if runcontroller.is_on('all'):
            runcontroller.off('all')
            runcontroller.on('run')

        if runcontroller.is_on('run'):
            status = "enabled"
        print rstring % ('run', status)
예제 #3
0
config_tree = None
server_root = None
mpm_query = None
exists_config_define = None

OK = 1

# End of _apache.py

sys.modules["_apache"] = sys.modules["__main__"]

from spacewalk.server import rhnSQL
from spacewalk.common import rhn_rpm

options_table = [
    Option("-v", "--verbose", action="count", help="Increase verbosity"),
    Option("--commit", action="store_true", help="Commit work"),
    Option("--backup-file",
           action="store",
           help="Backup packages into this file"),
    Option("--prefix",
           action="store",
           default='/pub',
           help="Prefix to find files in"),
]


class Runner:
    def __init__(self):
        self.options = None
        self._channels_hash = None
예제 #4
0
class Command(object):
    """Base class for command-line applications.

    :keyword app: The current app.
    :keyword get_app: Callable returning the current app if no app provided.

    """
    Error = Error
    UsageError = UsageError
    Parser = OptionParser

    #: Arg list used in help.
    args = ''

    #: Application version.
    version = VERSION_BANNER

    #: If false the parser will raise an exception if positional
    #: args are provided.
    supports_args = True

    #: List of options (without preload options).
    option_list = ()

    # module Rst documentation to parse help from (if any)
    doc = None

    # Some programs (multi) does not want to load the app specified
    # (Issue #1008).
    respects_app_option = True

    #: List of options to parse before parsing other options.
    preload_options = (
        Option('-A', '--app', default=None),
        Option('-b', '--broker', default=None),
        Option('--loader', default=None),
        Option('--config', default=None),
        Option('--workdir', default=None, dest='working_directory'),
        Option('--no-color', '-C', action='store_true', default=None),
        Option('--quiet', '-q', action='store_true'),
    )

    #: Enable if the application should support config from the cmdline.
    enable_config_from_cmdline = False

    #: Default configuration namespace.
    namespace = 'celery'

    #: Text to print at end of --help
    epilog = None

    #: Text to print in --help before option list.
    description = ''

    #: Set to true if this command doesn't have subcommands
    leaf = True

    # used by :meth:`say_remote_command_reply`.
    show_body = True
    # used by :meth:`say_chat`.
    show_reply = True

    prog_name = 'celery'

    def __init__(self, app=None, get_app=None, no_color=False,
                 stdout=None, stderr=None, quiet=False, on_error=None,
                 on_usage_error=None):
        self.app = app
        self.get_app = get_app or self._get_default_app
        self.stdout = stdout or sys.stdout
        self.stderr = stderr or sys.stderr
        self._colored = None
        self._no_color = no_color
        self.quiet = quiet
        if not self.description:
            self.description = self.__doc__
        if on_error:
            self.on_error = on_error
        if on_usage_error:
            self.on_usage_error = on_usage_error

    def run(self, *args, **options):
        """This is the body of the command called by :meth:`handle_argv`."""
        raise NotImplementedError('subclass responsibility')

    def on_error(self, exc):
        self.error(self.colored.red('Error: {0}'.format(exc)))

    def on_usage_error(self, exc):
        self.handle_error(exc)

    def on_concurrency_setup(self):
        pass

    def __call__(self, *args, **kwargs):
        random.seed()  # maybe we were forked.
        self.verify_args(args)
        try:
            ret = self.run(*args, **kwargs)
            return ret if ret is not None else EX_OK
        except self.UsageError as exc:
            self.on_usage_error(exc)
            return exc.status
        except self.Error as exc:
            self.on_error(exc)
            return exc.status

    def verify_args(self, given, _index=0):
        S = getargspec(self.run)
        _index = 1 if S.args and S.args[0] == 'self' else _index
        required = S.args[_index:-len(S.defaults) if S.defaults else None]
        missing = required[len(given):]
        if missing:
            raise self.UsageError('Missing required {0}: {1}'.format(
                text.pluralize(len(missing), 'argument'),
                ', '.join(missing)
            ))

    def execute_from_commandline(self, argv=None):
        """Execute application from command-line.

        :keyword argv: The list of command-line arguments.
                       Defaults to ``sys.argv``.

        """
        if argv is None:
            argv = list(sys.argv)
        # Should we load any special concurrency environment?
        self.maybe_patch_concurrency(argv)
        self.on_concurrency_setup()

        # Dump version and exit if '--version' arg set.
        self.early_version(argv)
        argv = self.setup_app_from_commandline(argv)
        self.prog_name = os.path.basename(argv[0])
        return self.handle_argv(self.prog_name, argv[1:])

    def run_from_argv(self, prog_name, argv=None, command=None):
        return self.handle_argv(prog_name,
                                sys.argv if argv is None else argv, command)

    def maybe_patch_concurrency(self, argv=None):
        argv = argv or sys.argv
        pool_option = self.with_pool_option(argv)
        if pool_option:
            maybe_patch_concurrency(argv, *pool_option)
            short_opts, long_opts = pool_option

    def usage(self, command):
        return '%prog {0} [options] {self.args}'.format(command, self=self)

    def get_options(self):
        """Get supported command-line options."""
        return self.option_list

    def expanduser(self, value):
        if isinstance(value, string_t):
            return os.path.expanduser(value)
        return value

    def ask(self, q, choices, default=None):
        """Prompt user to choose from a tuple of string values.

        :param q: the question to ask (do not include questionark)
        :param choice: tuple of possible choices, must be lowercase.
        :param default: Default value if any.

        If a default is not specified the question will be repeated
        until the user gives a valid choice.

        Matching is done case insensitively.

        """
        schoices = choices
        if default is not None:
            schoices = [c.upper() if c == default else c.lower()
                        for c in choices]
        schoices = '/'.join(schoices)

        p = '{0} ({1})? '.format(q.capitalize(), schoices)
        while 1:
            val = input(p).lower()
            if val in choices:
                return val
            elif default is not None:
                break
        return default

    def handle_argv(self, prog_name, argv, command=None):
        """Parse command-line arguments from ``argv`` and dispatch
        to :meth:`run`.

        :param prog_name: The program name (``argv[0]``).
        :param argv: Command arguments.

        Exits with an error message if :attr:`supports_args` is disabled
        and ``argv`` contains positional arguments.

        """
        options, args = self.prepare_args(
            *self.parse_options(prog_name, argv, command))
        return self(*args, **options)

    def prepare_args(self, options, args):
        if options:
            options = {
                k: self.expanduser(v)
                for k, v in items(vars(options)) if not k.startswith('_')
            }
        args = [self.expanduser(arg) for arg in args]
        self.check_args(args)
        return options, args

    def check_args(self, args):
        if not self.supports_args and args:
            self.die(ARGV_DISABLED.format(', '.join(args)), EX_USAGE)

    def error(self, s):
        self.out(s, fh=self.stderr)

    def out(self, s, fh=None):
        print(s, file=fh or self.stdout)

    def die(self, msg, status=EX_FAILURE):
        self.error(msg)
        sys.exit(status)

    def early_version(self, argv):
        if '--version' in argv:
            print(self.version, file=self.stdout)
            sys.exit(0)

    def parse_options(self, prog_name, arguments, command=None):
        """Parse the available options."""
        # Don't want to load configuration to just print the version,
        # so we handle --version manually here.
        self.parser = self.create_parser(prog_name, command)
        return self.parser.parse_args(arguments)

    def create_parser(self, prog_name, command=None):
        option_list = (
            self.preload_options +
            self.get_options() +
            tuple(self.app.user_options['preload'])
        )
        return self.prepare_parser(self.Parser(
            prog=prog_name,
            usage=self.usage(command),
            version=self.version,
            epilog=self.epilog,
            formatter=HelpFormatter(),
            description=self.description,
            option_list=option_list,
        ))

    def prepare_parser(self, parser):
        docs = [self.parse_doc(doc) for doc in (self.doc, __doc__) if doc]
        for doc in docs:
            for long_opt, help in items(doc):
                option = parser.get_option(long_opt)
                if option is not None:
                    option.help = ' '.join(help).format(default=option.default)
        return parser

    def setup_app_from_commandline(self, argv):
        preload_options = self.parse_preload_options(argv)
        quiet = preload_options.get('quiet')
        if quiet is not None:
            self.quiet = quiet
        try:
            self.no_color = preload_options['no_color']
        except KeyError:
            pass
        workdir = preload_options.get('working_directory')
        if workdir:
            os.chdir(workdir)
        app = (preload_options.get('app') or
               os.environ.get('CELERY_APP') or
               self.app)
        preload_loader = preload_options.get('loader')
        if preload_loader:
            # Default app takes loader from this env (Issue #1066).
            os.environ['CELERY_LOADER'] = preload_loader
        loader = (preload_loader,
                  os.environ.get('CELERY_LOADER') or
                  'default')
        broker = preload_options.get('broker', None)
        if broker:
            os.environ['CELERY_BROKER_URL'] = broker
        config = preload_options.get('config')
        if config:
            os.environ['CELERY_CONFIG_MODULE'] = config
        if self.respects_app_option:
            if app:
                self.app = self.find_app(app)
            elif self.app is None:
                self.app = self.get_app(loader=loader)
            if self.enable_config_from_cmdline:
                argv = self.process_cmdline_config(argv)
        else:
            self.app = Celery(fixups=[])

        user_preload = tuple(self.app.user_options['preload'] or ())
        if user_preload:
            user_options = self.preparse_options(argv, user_preload)
            for user_option in user_preload:
                user_options.setdefault(user_option.dest, user_option.default)
            signals.user_preload_options.send(
                sender=self, app=self.app, options=user_options,
            )
        return argv

    def find_app(self, app):
        from celery.app.utils import find_app
        return find_app(app, symbol_by_name=self.symbol_by_name)

    def symbol_by_name(self, name, imp=import_from_cwd):
        return symbol_by_name(name, imp=imp)
    get_cls_by_name = symbol_by_name  # XXX compat

    def process_cmdline_config(self, argv):
        try:
            cargs_start = argv.index('--')
        except ValueError:
            return argv
        argv, cargs = argv[:cargs_start], argv[cargs_start + 1:]
        self.app.config_from_cmdline(cargs, namespace=self.namespace)
        return argv

    def parse_preload_options(self, args):
        return self.preparse_options(args, self.preload_options)

    def preparse_options(self, args, options):
        acc = {}
        opts = {}
        for opt in options:
            for t in (opt._long_opts, opt._short_opts):
                opts.update(dict(zip(t, [opt] * len(t))))
        index = 0
        length = len(args)
        while index < length:
            arg = args[index]
            if arg.startswith('--'):
                if '=' in arg:
                    key, value = arg.split('=', 1)
                    opt = opts.get(key)
                    if opt:
                        acc[opt.dest] = value
                else:
                    opt = opts.get(arg)
                    if opt and opt.takes_value():
                        # optparse also supports ['--opt', 'value']
                        # (Issue #1668)
                        acc[opt.dest] = args[index + 1]
                        index += 1
                    elif opt and opt.action == 'store_true':
                        acc[opt.dest] = True
            elif arg.startswith('-'):
                opt = opts.get(arg)
                if opt:
                    if opt.takes_value():
                        try:
                            acc[opt.dest] = args[index + 1]
                        except IndexError:
                            raise ValueError(
                                'Missing required argument for {0}'.format(
                                    arg))
                        index += 1
                    elif opt.action == 'store_true':
                        acc[opt.dest] = True
            index += 1
        return acc

    def parse_doc(self, doc):
        options, in_option = defaultdict(list), None
        for line in doc.splitlines():
            if line.startswith('.. cmdoption::'):
                m = find_long_opt.match(line)
                if m:
                    in_option = m.groups()[0].strip()
                assert in_option, 'missing long opt'
            elif in_option and line.startswith(' ' * 4):
                options[in_option].append(
                    find_rst_ref.sub(r'\1', line.strip()).replace('`', ''))
        return options

    def with_pool_option(self, argv):
        """Return tuple of ``(short_opts, long_opts)`` if the command
        supports a pool argument, and used to monkey patch eventlet/gevent
        environments as early as possible.

        E.g::
              has_pool_option = (['-P'], ['--pool'])
        """
        pass

    def node_format(self, s, nodename, **extra):
        return node_format(s, nodename, **extra)

    def host_format(self, s, **extra):
        return host_format(s, **extra)

    def _get_default_app(self, *args, **kwargs):
        from celery._state import get_current_app
        return get_current_app()  # omit proxy

    def pretty_list(self, n):
        c = self.colored
        if not n:
            return '- empty -'
        return '\n'.join(
            str(c.reset(c.white('*'), ' {0}'.format(item))) for item in n
        )

    def pretty_dict_ok_error(self, n):
        c = self.colored
        try:
            return (c.green('OK'),
                    text.indent(self.pretty(n['ok'])[1], 4))
        except KeyError:
            pass
        return (c.red('ERROR'),
                text.indent(self.pretty(n['error'])[1], 4))

    def say_remote_command_reply(self, replies):
        c = self.colored
        node = next(iter(replies))  # <-- take first.
        reply = replies[node]
        status, preply = self.pretty(reply)
        self.say_chat('->', c.cyan(node, ': ') + status,
                      text.indent(preply, 4) if self.show_reply else '')

    def pretty(self, n):
        OK = str(self.colored.green('OK'))
        if isinstance(n, list):
            return OK, self.pretty_list(n)
        if isinstance(n, dict):
            if 'ok' in n or 'error' in n:
                return self.pretty_dict_ok_error(n)
            else:
                return OK, json.dumps(n, sort_keys=True, indent=4)
        if isinstance(n, string_t):
            return OK, string(n)
        return OK, pformat(n)

    def say_chat(self, direction, title, body=''):
        c = self.colored
        if direction == '<-' and self.quiet:
            return
        dirstr = not self.quiet and c.bold(c.white(direction), ' ') or ''
        self.out(c.reset(dirstr, title))
        if body and self.show_body:
            self.out(body)

    @property
    def colored(self):
        if self._colored is None:
            self._colored = term.colored(enabled=not self.no_color)
        return self._colored

    @colored.setter
    def colored(self, obj):
        self._colored = obj

    @property
    def no_color(self):
        return self._no_color

    @no_color.setter
    def no_color(self, value):
        self._no_color = value
        if self._colored is not None:
            self._colored.enabled = not self._no_color
예제 #5
0
def processCommandline(cfg):

    up2date_cfg = dict(cfg.items())

    if isinstance(up2date_cfg['serverURL'], type([])):
        rhn_parent = urlparse.urlparse(up2date_cfg['serverURL'][0])[1]
    else:
        rhn_parent = urlparse.urlparse(up2date_cfg['serverURL'])[1]

    httpProxy = urlparse.urlparse(up2date_cfg['httpProxy'])[1]
    httpProxyUsername = up2date_cfg['proxyUser']
    httpProxyPassword = up2date_cfg['proxyPassword']

    if not httpProxy:
        httpProxyUsername, httpProxyPassword = '', ''
    if not httpProxyUsername:
        httpProxyPassword = ''
    ca_cert = ''
    defaultVersion = '5.2'

    # parse options
    optionsTable = [
        Option(
            '-s',
            '--server',
            action='store',
            default=rhn_parent,
            help="alternative server hostname to connect to, default is %s" %
            repr(rhn_parent)),
        Option(
            '--http-proxy',
            action='store',
            default=httpProxy,
            help=
            "alternative HTTP proxy to connect to (HOSTNAME:PORT), default is %s"
            % repr(httpProxy)),
        Option('--http-proxy-username',
               action='store',
               default=httpProxyUsername,
               help="alternative HTTP proxy usename, default is %s" %
               repr(httpProxyUsername)),
        Option('--http-proxy-password',
               action='store',
               default=httpProxyPassword,
               help="alternative HTTP proxy password, default is %s" %
               repr(httpProxyPassword)),
        Option('--ca-cert',
               action='store',
               default=ca_cert,
               help="alternative SSL certificate to use, default is %s" %
               repr(ca_cert)),
        Option('--no-ssl',
               action='store_true',
               help='turn off SSL (not advisable), default is on.'),
        Option(
            '--version',
            action='store',
            default=defaultVersion,
            help=
            'which X.Y version of the Spacewalk Proxy are you upgrading to?' +
            ' Default is your current proxy version (' + defaultVersion + ')'),
        Option('--deactivate',
               action='store_true',
               help='deactivate proxy, if already activated'),
        Option('-l',
               '--list-available-versions',
               action='store_true',
               help='print list of versions available to this system'),
        Option('--non-interactive',
               action='store_true',
               help='non-interactive mode'),
        Option('-q',
               '--quiet',
               action='store_true',
               help='quiet non-interactive mode.'),
    ]
    parser = OptionParser(option_list=optionsTable)
    options, _args = parser.parse_args()

    if options.server:
        if options.server.find('http') != 0:
            options.server = 'https://' + options.server
        options.server = urlparse.urlparse(options.server)[1]

    if options.no_ssl:
        if not options.quiet:
            sys.stderr.write('warning: user disabled SSL\n')
        options.ca_cert = ''

    if not options.http_proxy:
        options.http_proxy_username, options.http_proxy_password = '', ''

    if not options.http_proxy_username:
        options.http_proxy_password = ''
    exploded_version = options.version.split('.')
    # Pad it to be at least 2 components
    if len(exploded_version) == 1:
        exploded_version.append('0')

    # Make it a string
    options.version = '.'.join(exploded_version[:2])

    if options.quiet:
        options.non_interactive = 1

    return options
예제 #6
0
 def add_options(group, options):
     for opt in options:
         if plumber.input_fmt == 'recipe' and opt.option.long_switch == 'test':
             group(Option('--test', dest='test', action='callback', callback=recipe_test))
         else:
             option_recommendation_to_cli_option(group, opt)
예제 #7
0
def main():
    parser = PosOptionParser(
        usage='Usage: python %prog [options] INTERVAL SOURCE',
        description='Generates a set of subsequent ' +
        'CPU utilization levels read from a file. ' +
        '                                         ' +
        'Copyright (C) 2012 Anton Beloglazov. ' +
        'Released under Apache 2.0 license.')
    parser.add_positional_argument(
        Option('--INTERVAL',
               action='store_true',
               help='interval between subsequent CPU ' +
               'utilization levels in seconds'))
    parser.add_positional_argument(
        Option('--SOURCE',
               action='store_true',
               help='source file containing a new line ' +
               'separated list of CPU utilization levels ' +
               'specified as numbers in the [0, 100] range'))
    parser.add_option('-n',
                      '--ncpus',
                      type='int',
                      dest='ncpus',
                      default=1,
                      help='number of CPU cores to utilize [default: 1]')
    parser.add_option(
        '-t',
        '--timeout',
        type='int',
        dest='timeout',
        default=0,
        help='number of seconds for generated CPU load  [default: 0 (infinite)]'
    )

    (options, args) = parser.parse_args()

    if len(args) != 2:
        parser.error('incorrect number of arguments')

    try:
        interval = int(args[0])
    except ValueError:
        parser.error('interval must be an integer > 0')
    if interval <= 0:
        parser.error('interval must be an integer > 0')

    if options.timeout < 0:
        parser.error('timeout must be a integer >= 0.0')

    filename = args[1]
    if not os.access(filename, os.R_OK):
        parser.error('cannot read file: ' + filename)

    utilization = []
    for line in open(filename):
        if line.strip():
            try:
                n = float(line)
                if n < 0 or n > 100:
                    raise ValueError
                utilization.append(int(n))
            except ValueError:
                parser.error('the source file must only ' +
                             'contain new line separated ' +
                             'numbers in the [0, 100] range')

    if interval <= 0:
        parser.error('interval must be an integer >= 0')

    process(interval, utilization, options)
TaylorF2ReducedSpin metric.
"""
__author__ = "Leo Singer <*****@*****.**>"


# Command line interface.
from optparse import Option, OptionParser
from lalinference.bayestar import command
import sys

parser = OptionParser(
    formatter = command.NewlinePreservingHelpFormatter(),
    description = __doc__,
    usage = '%prog [options] --mass1 MSUN --mass2 MSUN [INPUT.xml[.gz]] [-o OUTPUT.xml[.gz]]',
    option_list = [
        Option("-o", "--output", metavar="OUTPUT.xml[.gz]", default="/dev/stdout",
            help="Name of output file [default: %default]"),
        Option("--mass1", type=float, metavar="MSUN"),
        Option("--mass2", type=float, metavar="MSUN"),
        Option("--snr", type=float, metavar="SNR")
    ]
)
opts, args = parser.parse_args()
infilename = command.get_input_filename(parser, args)
command.check_required_arguments(parser, opts, "mass1", "mass2", "snr")


# Python standard library imports.
import os

# LIGO-LW XML imports.
from glue.ligolw.utils import process as ligolw_process
예제 #9
0
__license__ = ""
__maintainer__ = "Mike Belov"
__email__ = "*****@*****.**"


def test_configuration_and_enviroment(config, pid, wait_for_cloud):
    return configreader.test(config, pid, wait_for_cloud)


usage = "usage: %prog [start|stop|configtest] [options]"

option_list = (
    Option(
        '--config',
        action='store',
        dest='config',
        type='string',
        help='path to the config file',
        default=None,
    ),
    Option(
        '--pid',
        action='store',
        dest='pid',
        type='string',
        help='path to the pid file',
        default=None,
    ),
    Option(
        '--foreground',
        action='store_true',
        dest='foreground',
예제 #10
0
파일: rhncli.py 프로젝트: xkollar/spacewalk
    t.ugettext = t.gettext
_ = t.ugettext

sys.path.append("/usr/share/rhn/")

from up2date_client import config
from up2date_client import up2dateAuth
from up2date_client import up2dateErrors
from up2date_client import up2dateLog
from up2date_client import up2dateUtils
from up2date_client import pkgUtils

_optionsTable = [
    Option("-v",
           "--verbose",
           action="count",
           default=0,
           help=_("Show additional output")),
    Option("--proxy", action="store", help=_("Specify an http proxy to use")),
    Option(
        "--proxyUser",
        action="store",
        help=_("Specify a username to use with an authenticated http proxy")),
    Option(
        "--proxyPassword",
        action="store",
        help=_("Specify a password to use with an authenticated http proxy")),
]


class RhnCli(object):
예제 #11
0
파일: make.py 프로젝트: datamail321/kunquat
        if type(value) == bool:
            first_word = var_name.split('_')[0]
            if first_word == 'enable':
                negated_name = name.replace('enable', 'disable', 1)
            elif first_word == 'with':
                negated_name = name.replace('with', 'without', 1)
            else:
                assert False

            if value == True:
                negated_desc = (desc.replace('enable', 'disable', 1)
                                if desc.startswith('enable') else
                                ('do not ' + desc))
                full_desc = '{} (default: enabled)'.format(negated_desc)
                neg_opt = Option(negated_name,
                                 action='store_false',
                                 dest=var_name,
                                 help=full_desc)

                pos_opt = Option(name,
                                 action='store_true',
                                 dest=var_name,
                                 help=SUPPRESS_HELP)
            else:
                full_desc = '{} (default: disabled)'.format(desc)
                pos_opt = Option(name,
                                 action='store_true',
                                 dest=var_name,
                                 help=full_desc)
                neg_opt = Option(negated_name,
                                 action='store_false',
                                 dest=var_name,
예제 #12
0
파일: org.py 프로젝트: yanheven/spacewalk
def do_org_create(self, args):
    options = [
        Option('-n', '--org-name', action='store'),
        Option('-u', '--username', action='store'),
        Option('-P', '--prefix', action='store'),
        Option('-f', '--first-name', action='store'),
        Option('-l', '--last-name', action='store'),
        Option('-e', '--email', action='store'),
        Option('-p', '--password', action='store'),
        Option('', '--pam', action='store_true')
    ]

    (args, options) = parse_arguments(args, options)

    if is_interactive(options):
        options.org_name = prompt_user('Organization Name:', noblank=True)
        options.username = prompt_user('Username:'******'Prefix (%s):' % ', '.join(_PREFIXES),
                                     noblank=True)
        options.first_name = prompt_user('First Name:', noblank=True)
        options.last_name = prompt_user('Last Name:', noblank=True)
        options.email = prompt_user('Email:', noblank=True)
        options.pam = self.user_confirm('PAM Authentication [y/N]:',
                                        nospacer=True,
                                        integer=False,
                                        ignore_yes=True)

        options.password = ''
        while options.password == '':
            password1 = getpass('Password: '******'Repeat Password: '******'':
                logging.warning('Password must be at least 5 characters')
            else:
                logging.warning("Passwords don't match")
    else:
        if not options.org_name:
            logging.error('An organization name is required')
            return

        if not options.username:
            logging.error('A username is required')
            return

        if not options.first_name:
            logging.error('A first name is required')
            return

        if not options.last_name:
            logging.error('A last name is required')
            return

        if not options.email:
            logging.error('An email address is required')
            return

        if not options.password:
            logging.error('A password is required')
            return

        if not options.pam:
            options.pam = False

        if not options.prefix:
            options.prefix = 'Dr.'

    if options.prefix[-1] != '.' and options.prefix != 'Miss':
        options.prefix = options.prefix + '.'

    self.client.org.create(self.session, options.org_name,
                           options.username, options.password,
                           options.prefix.capitalize(), options.first_name,
                           options.last_name, options.email, options.pam)
예제 #13
0
def main(args=None, locals_=None, banner=None, welcome_message=None):
    """
    banner is displayed directly after the version information.
    welcome_message is passed on to Repl and displayed in the statusbar.
    """
    translations.init()

    config, options, exec_args = bpargs.parse(
        args, ('curtsies options', None, [
            Option('--log',
                   '-L',
                   action='count',
                   help=_("log debug messages to bpython.log")),
            Option('--paste',
                   '-p',
                   action='store_true',
                   help=_("start by pasting lines of a file into session")),
        ]))
    if options.log is None:
        options.log = 0
    logging_levels = [logging.ERROR, logging.INFO, logging.DEBUG]
    level = logging_levels[min(len(logging_levels) - 1, options.log)]
    logging.getLogger('curtsies').setLevel(level)
    logging.getLogger('bpython').setLevel(level)
    if options.log:
        handler = logging.FileHandler(filename='bpython.log')
        logging.getLogger('curtsies').addHandler(handler)
        logging.getLogger('curtsies').propagate = False
        logging.getLogger('bpython').addHandler(handler)
        logging.getLogger('bpython').propagate = False

    interp = None
    paste = None
    if exec_args:
        if not options:
            raise ValueError("don't pass in exec_args without options")
        exit_value = ()
        if options.paste:
            paste = curtsies.events.PasteEvent()
            encoding = inspection.get_encoding_file(exec_args[0])
            with io.open(exec_args[0], encoding=encoding) as f:
                sourcecode = f.read()
            paste.events.extend(sourcecode)
        else:
            try:
                interp = Interp(locals=locals_)
                bpargs.exec_code(interp, exec_args)
            except SystemExit as e:
                exit_value = e.args
            if not options.interactive:
                return extract_exit_value(exit_value)
    else:
        # expected for interactive sessions (vanilla python does it)
        sys.path.insert(0, '')

    if not options.quiet:
        print(bpargs.version_banner())
    if banner is not None:
        print(banner)
    global repl
    repl = FullCurtsiesRepl(config, locals_, welcome_message, interp, paste)
    try:
        with repl.input_generator:
            with repl.window as win:
                with repl:
                    repl.height, repl.width = win.t.height, win.t.width
                    exit_value = repl.mainloop()
    except (SystemExitFromCodeGreenlet, SystemExit) as e:
        exit_value = e.args
    return extract_exit_value(exit_value)
예제 #14
0
def main(args=None, locals_=None, banner=None):
    translations.init()

    # TODO: maybe support displays other than raw_display?
    config, options, exec_args = bpargs.parse(args, ('Urwid options', None, [
        Option('--twisted',
               '-T',
               action='store_true',
               help=_('Run twisted reactor.')),
        Option('--reactor',
               '-r',
               help=_('Select specific reactor (see --help-reactors). '
                      'Implies --twisted.')),
        Option('--help-reactors',
               action='store_true',
               help=_('List available reactors for -r.')),
        Option('--plugin',
               '-p',
               help=_('twistd plugin to run (use twistd for a list). '
                      'Use "--" to pass further options to the plugin.')),
        Option('--server',
               '-s',
               type='int',
               help=_('Port to run an eval server on (forces Twisted).')),
    ]))

    if options.help_reactors:
        try:
            from twisted.application import reactors
            # Stolen from twisted.application.app (twistd).
            for r in reactors.getReactorTypes():
                print('    %-4s\t%s' % (r.shortName, r.description))
        except ImportError:
            sys.stderr.write('No reactors are available. Please install '
                             'twisted for reactor support.\n')
        return

    palette = [(name, COLORMAP[color.lower()], 'default',
                'bold' if color.isupper() else 'default')
               for name, color in config.color_scheme.items()]
    palette.extend([('bold ' + name, color + ',bold', background, monochrome)
                    for name, color, background, monochrome in palette])

    if options.server or options.plugin:
        options.twisted = True

    if options.reactor:
        try:
            from twisted.application import reactors
        except ImportError:
            sys.stderr.write('No reactors are available. Please install '
                             'twisted for reactor support.\n')
            return
        try:
            # XXX why does this not just return the reactor it installed?
            reactor = reactors.installReactor(options.reactor)
            if reactor is None:
                from twisted.internet import reactor
        except reactors.NoSuchReactor:
            sys.stderr.write('Reactor %s does not exist\n' %
                             (options.reactor, ))
            return
        event_loop = TwistedEventLoop(reactor)
    elif options.twisted:
        try:
            from twisted.internet import reactor
        except ImportError:
            sys.stderr.write('No reactors are available. Please install '
                             'twisted for reactor support.\n')
            return
        event_loop = TwistedEventLoop(reactor)
    else:
        # None, not urwid.SelectEventLoop(), to work with
        # screens that do not support external event loops.
        event_loop = None
    # TODO: there is also a glib event loop. Do we want that one?

    # __main__ construction from bpython.cli
    if locals_ is None:
        main_mod = sys.modules['__main__'] = ModuleType('__main__')
        locals_ = main_mod.__dict__

    if options.plugin:
        try:
            from twisted import plugin
            from twisted.application import service
        except ImportError:
            sys.stderr.write(
                'No twisted plugins are available. Please install '
                'twisted for twisted plugin support.\n')
            return

        for plug in plugin.getPlugins(service.IServiceMaker):
            if plug.tapname == options.plugin:
                break
        else:
            sys.stderr.write('Plugin %s does not exist\n' % (options.plugin, ))
            return
        plugopts = plug.options()
        plugopts.parseOptions(exec_args)
        serv = plug.makeService(plugopts)
        locals_['service'] = serv
        reactor.callWhenRunning(serv.startService)
        exec_args = []
    interpreter = repl.Interpreter(locals_, locale.getpreferredencoding())

    # This nabs sys.stdin/out via urwid.MainLoop
    myrepl = URWIDRepl(event_loop, palette, interpreter, config)

    if options.server:
        factory = EvalFactory(myrepl)
        reactor.listenTCP(options.server, factory, interface='127.0.0.1')

    if options.reactor:
        # Twisted sets a sigInt handler that stops the reactor unless
        # it sees a different custom signal handler.
        def sigint(*args):
            reactor.callFromThread(myrepl.keyboard_interrupt)

        signal.signal(signal.SIGINT, sigint)

    # Save stdin, stdout and stderr for later restoration
    orig_stdin = sys.stdin
    orig_stdout = sys.stdout
    orig_stderr = sys.stderr

    # urwid's screen start() and stop() calls currently hit sys.stdin
    # directly (via RealTerminal.tty_signal_keys), so start the screen
    # before swapping sys.std*, and swap them back before restoring
    # the screen. This also avoids crashes if our redirected sys.std*
    # are called before we get around to starting the mainloop
    # (urwid raises an exception if we try to draw to the screen
    # before starting it).
    def run_with_screen_before_mainloop():
        try:
            # Currently we just set this to None because I do not
            # expect code hitting stdin to work. For example: exit()
            # (not sys.exit, site.py's exit) tries to close sys.stdin,
            # which breaks urwid's shutdown. bpython.cli sets this to
            # a fake object that reads input through curses and
            # returns it. When using twisted I do not think we can do
            # that because sys.stdin.read and friends block, and we
            # cannot re-enter the reactor. If using urwid's own
            # mainloop we *might* be able to do something similar and
            # re-enter its mainloop.
            sys.stdin = None  #FakeStdin(myrepl)
            sys.stdout = myrepl
            sys.stderr = myrepl

            myrepl.main_loop.set_alarm_in(0, start)

            while True:
                try:
                    myrepl.main_loop.run()
                except KeyboardInterrupt:
                    # HACK: if we run under a twisted mainloop this should
                    # never happen: we have a SIGINT handler set.
                    # If we use the urwid select-based loop we just restart
                    # that loop if interrupted, instead of trying to cook
                    # up an equivalent to reactor.callFromThread (which
                    # is what our Twisted sigint handler does)
                    myrepl.main_loop.set_alarm_in(
                        0, lambda *args: myrepl.keyboard_interrupt())
                    continue
                break

        finally:
            sys.stdin = orig_stdin
            sys.stderr = orig_stderr
            sys.stdout = orig_stdout

    # This needs more thought. What needs to happen inside the mainloop?
    def start(main_loop, user_data):
        if exec_args:
            bpargs.exec_code(interpreter, exec_args)
            if not options.interactive:
                raise urwid.ExitMainLoop()
        if not exec_args:
            sys.path.insert(0, '')
            # this is CLIRepl.startup inlined.
            filename = os.environ.get('PYTHONSTARTUP')
            if filename and os.path.isfile(filename):
                with open(filename, 'r') as f:
                    if py3:
                        interpreter.runsource(f.read(), filename, 'exec')
                    else:
                        interpreter.runsource(f.read(),
                                              filename,
                                              'exec',
                                              encode=False)

        if banner is not None:
            repl.write(banner)
            repl.write('\n')
        myrepl.start()

        # This bypasses main_loop.set_alarm_in because we must *not*
        # hit the draw_screen call (it's unnecessary and slow).
        def run_find_coroutine():
            if find_coroutine():
                main_loop.event_loop.alarm(0, run_find_coroutine)

        run_find_coroutine()

    myrepl.main_loop.screen.run_wrapper(run_with_screen_before_mainloop)

    if config.flush_output and not options.quiet:
        sys.stdout.write(myrepl.getstdout())
    if hasattr(sys.stdout, "flush"):
        sys.stdout.flush()
    return repl.extract_exit_value(myrepl.exit_value)
예제 #15
0
    'ubuntu1604', 'ubuntu1604-plus', 'ubuntu1604-mysql8', 'ubuntu1404',
    'ubuntu1404-plus', 'debian8', 'centos6', 'centos7', 'alpine', 'gentoo'
]

usage = "usage: %prog -h"


def get_comma_separated_args(option, opt, value, parser):
    setattr(parser.values, option.dest, value.split(','))


option_list = (
    Option(
        '--rebuild',
        action='store_true',
        dest='rebuild',
        help='Rebuild before run (False by default)',
        default=False,
    ),
    Option(
        '--build-arg',
        action='append',
        dest='build_args',
        help='Build arguments for docker build',
        default=[],
        type='str',
    ),
    Option(
        '--drop',
        action='store_true',
        dest='drop',
예제 #16
0
def get_opt_parser():
    # use module docstring for help output
    p = OptionParser(usage=f"{sys.argv[0]} [OPTIONS] <PAR files>\n\n" +
                     __doc__,
                     version="%prog " + nibabel.__version__)
    p.add_option(
        Option("-v",
               "--verbose",
               action="store_true",
               dest="verbose",
               default=False,
               help="""Make some noise."""))
    p.add_option(
        Option("-o",
               "--output-dir",
               action="store",
               type="string",
               dest="outdir",
               default=None,
               help=one_line("""Destination directory for NIfTI files.
                             Default: current directory.""")))
    p.add_option(
        Option("-c",
               "--compressed",
               action="store_true",
               dest="compressed",
               default=False,
               help="Whether to write compressed NIfTI files or not."))
    p.add_option(
        Option("-p",
               "--permit-truncated",
               action="store_true",
               dest="permit_truncated",
               default=False,
               help=one_line(
                   """Permit conversion of truncated recordings. Support for
                   this is experimental, and results *must* be checked
                   afterward for validity.""")))
    p.add_option(
        Option("-b",
               "--bvs",
               action="store_true",
               dest="bvs",
               default=False,
               help=one_line("""Output bvals/bvecs files in addition to NIFTI
                   image.""")))
    p.add_option(
        Option("-d",
               "--dwell-time",
               action="store_true",
               default=False,
               dest="dwell_time",
               help=one_line(
                   """Calculate the scan dwell time. If supplied, the magnetic
                   field strength should also be supplied using
                   --field-strength (default 3). The field strength must be
                   supplied because it is not encoded in the PAR/REC
                   format.""")))
    p.add_option(
        Option("--field-strength",
               action="store",
               type="float",
               dest="field_strength",
               help=one_line(
                   """The magnetic field strength of the recording, only needed
                   for --dwell-time. The field strength must be supplied
                   because it is not encoded in the PAR/REC format.""")))
    p.add_option(
        Option("-i",
               "--volume-info",
               action="store_true",
               dest="vol_info",
               default=False,
               help=one_line(
                   """Export .PAR volume labels corresponding to the fourth
                   dimension of the data.  The dimension info will be stored in
                   CSV format with the first row containing dimension labels
                   and the subsequent rows (one per volume), the corresponding
                   indices.  Only labels that vary along the 4th dimension are
                   exported (e.g. for a single volume structural scan there
                   are no dynamic labels and no output file will be created).
                   """)))
    p.add_option(
        Option("--origin",
               action="store",
               dest="origin",
               default="scanner",
               help=one_line(
                   """Reference point of the q-form transformation of the NIfTI
                   image. If 'scanner' the (0,0,0) coordinates will refer to
                   the scanner's iso center. If 'fov', this coordinate will be
                   the center of the recorded volume (field of view). Default:
                   'scanner'.""")))
    p.add_option(
        Option("--minmax",
               action="store",
               nargs=2,
               dest="minmax",
               help=one_line(
                   """Minimum and maximum settings to be stored in the NIfTI
                   header. If any of them is set to 'parse', the scaled data is
                   scanned for the actual minimum and maximum.  To bypass this
                   potentially slow and memory intensive step (the data has to
                   be scaled and fully loaded into memory), fixed values can be
                   provided as space-separated pair, e.g. '5.4 120.4'. It is
                   possible to set a fixed minimum as scan for the actual
                   maximum (and vice versa). Default: 'parse parse'.""")))
    p.set_defaults(minmax=('parse', 'parse'))
    p.add_option(
        Option("--store-header",
               action="store_true",
               dest="store_header",
               default=False,
               help=one_line(
                   """If set, all information from the PAR header is stored in
                   an extension of the NIfTI file header.  Default: off""")))
    p.add_option(
        Option("--scaling",
               action="store",
               dest="scaling",
               default='dv',
               help=one_line(
                   """Choose data scaling setting. The PAR header defines two
                   different data scaling settings: 'dv' (values displayed on
                   console) and 'fp' (floating point values). Either one can be
                   chosen, or scaling can be disabled completely ('off').  Note
                   that neither method will actually scale the data, but just
                   store the corresponding settings in the NIfTI header, unless
                   non-uniform scaling is used, in which case the data is
                   stored in the file in scaled form. Default: 'dv'""")))
    p.add_option(
        Option('--keep-trace',
               action="store_true",
               dest='keep_trace',
               default=False,
               help=one_line("""Do not discard the diagnostic Philips DTI
                             trace volume, if it exists in the data.""")))
    p.add_option(
        Option("--overwrite",
               action="store_true",
               dest="overwrite",
               default=False,
               help=one_line("""Overwrite file if it exists. Default:
                             False""")))
    p.add_option(
        Option("--strict-sort",
               action="store_true",
               dest="strict_sort",
               default=False,
               help=one_line("""Use additional keys in determining the order
                to sort the slices within the .REC file.  This may be necessary
                for more complicated scans with multiple echos,
                cardiac phases, ASL label states, etc.""")))
    return p
예제 #17
0
def optionParse():
    """ We parse in 3 steps:
        (1) parse options
        (2) set the defaults based on any options we override on the commandline
            - this is nice for things like (what dir we are working in etc).
        (3) reparse the options with defaults set

        Reset the default values DEFS given the options found.
    """

    # force certain "first options". Not beautiful but it works.
    if len(sys.argv) > 1:
        if sys.argv[1] not in ('-h', '--help', '--gen-ca', '--gen-server',
                               '--gen-client'):
            # first option was not something we understand. Force a base --help
            del (sys.argv[1:])
            sys.argv.append('--help')

    if '--gen-ca' in sys.argv:
        reInitDEFS(1)
    else:
        reInitDEFS(0)
    ##
    # STEP 1: preliminarily parse options
    ##
    # print 'XXX STEP1'

    optionList, usage = _getOptionList(DEFS)

    optionListNoHelp = optionList[:]
    fake_help = Option("-h", "--help", action="count", help='')
    optionListNoHelp.append(fake_help)
    options, args = OptionParser(option_list=optionListNoHelp,
                                 add_help_option=0).parse_args()

    ##
    # STEP 2: repopulate DEFS dict based on commandline
    #         and the *-openssl.cnf files
    ##
    # print 'XXX STEP2'
    figureDEFS_dirs(options)  # build directory structure
    figureDEFS_CA(options)  # CA key set stuff
    figureDEFS_server(options)  # server key set stuff
    figureDEFS_distinguishing(options)  # distinguishing name stuff

    ##
    # STEP 3: reparse options again only if --help is in the commandline
    #         so that we can give a --help with correct defaults set.
    ##
    # print 'XXX STEP3'

    if '-h' in sys.argv or '--help' in sys.argv:
        # DEFS should be mapped with new values now... let's reparse the options.
        # The correct help text should be presented and all defaults
        # should be mapped as expected.
        optionList, usage = _getOptionList(DEFS)
        options, args = OptionParser(option_list=optionList,
                                     usage=usage).parse_args()

    # we take no extra commandline arguments that are not linked to an option
    if args:
        sys.stderr.write("\nERROR: these arguments make no sense in this "
                         "context (try --help): %s\n" % repr(args))
        sys.exit(errnoGeneralError)

    return options
예제 #18
0
 def make(self):
     args_copy = copy.deepcopy(self.args)
     kwargs_copy = copy.deepcopy(self.kwargs)
     return Option(*args_copy, **kwargs_copy)
예제 #19
0
def processCommandline():
    "process the command-line"
    credentials = Credentials()

    optionsTable = [
        Option('-c',
               '--channel',
               action='append',
               dest='channels',
               help=_('name of channel you want to (un)subscribe')),
        Option('-a',
               '--add',
               action='store_true',
               help=_('subscribe to channel')),
        Option('-r',
               '--remove',
               action='store_true',
               help=_('unsubscribe from channel')),
        Option('-l', '--list', action='store_true', help=_('list channels')),
        Option('-b',
               '--base',
               action='store_true',
               help=_('show base channel of a system')),
        Option('-L',
               '--available-channels',
               action='store_true',
               help=_('list all available child channels')),
        Option('-v',
               '--verbose',
               action='store_true',
               help=_('verbose output')),
        Option('-u',
               '--user',
               action='callback',
               callback=credentials.user_callback,
               nargs=1,
               type='string',
               help=_('your user name')),
        Option('-p',
               '--password',
               action='callback',
               callback=credentials.password_callback,
               nargs=1,
               type='string',
               help=_('your password')),
    ]
    optionParser = OptionParser(option_list=optionsTable)
    opts, args = optionParser.parse_args()

    # we take no extra commandline arguments that are not linked to an option
    if args:
        systemExit(
            1,
            _("ERROR: these arguments make no sense in this context (try --help)"
              ))

    # remove confusing stuff
    delattr(opts, 'user')
    delattr(opts, 'password')

    return opts, credentials
def processCommandline():
    options = [
        Option('--sanity-only',
               action='store_true',
               help="confirm certificate sanity. Does not activate " +
               "the Red Hat Satellite locally or remotely."),
        Option('--ignore-expiration',
               action='store_true',
               help='execute regardless of the expiration ' +
               'of the RHN Certificate (not recommended).'),
        Option('--ignore-version-mismatch',
               action='store_true',
               help='execute regardless of version ' +
               'mismatch of existing and new certificate.'),
        Option('-v',
               '--verbose',
               action='count',
               help='be verbose ' +
               '(accumulable: -vvv means "be *really* verbose").'),
        Option('--dump-version',
               action='store',
               help="requested version of XML dump"),
        Option('--manifest',
               action='store',
               help='the RHSM manifest path/filename to activate for CDN'),
        Option('--rhn-cert',
               action='store',
               help='this option is deprecated, use --manifest instead'),
        Option('--deactivate',
               action='store_true',
               help='deactivate CDN-activated Satellite'),
        Option('--disconnected',
               action='store_true',
               help="activate locally, not subscribe to remote repository"),
        Option('--manifest-info',
               action='store_true',
               help="show information about currently activated manifest"),
        Option('--manifest-download',
               action='store_true',
               help="download new manifest from RHSM to temporary location"),
        Option('--manifest-refresh',
               action='store_true',
               help="download new manifest from RHSM and activate it"),
        Option('--manifest-reconcile-request',
               action='store_true',
               help="request regeneration of entitlement certificates")
    ]

    parser = OptionParser(option_list=options)
    options, args = parser.parse_args()

    initCFG('server.satellite')
    if options.verbose is None:
        options.verbose = 0
    CFG.set('DEBUG', options.verbose)
    rhnLog.initLOG(LOG_PATH, options.verbose)
    log2disk(0, "Command: %s" % str(sys.argv))

    # we take no extra commandline arguments that are not linked to an option
    if args:
        writeError(
            "These arguments make no sense in this context (try --help): %s" %
            repr(args))
        sys.exit(1)

    # No need to check further if deactivating
    if options.deactivate:
        return options

    if options.sanity_only:
        options.disconnected = 1

    if options.manifest_refresh:
        options.manifest_download = 1

    if CFG.DISCONNECTED and not options.disconnected:
        msg = """Satellite server has been setup to run in disconnected mode.
       Either correct server configuration in /etc/rhn/rhn.conf
       or use --disconnected to activate it locally."""
        writeError(msg)
        sys.exit(1)

    options.http_proxy = idn_ascii_to_puny(CFG.HTTP_PROXY)
    options.http_proxy_username = CFG.HTTP_PROXY_USERNAME
    options.http_proxy_password = CFG.HTTP_PROXY_PASSWORD
    log(1, 'HTTP_PROXY: %s' % options.http_proxy)
    log(1, 'HTTP_PROXY_USERNAME: %s' % options.http_proxy_username)
    log(1, 'HTTP_PROXY_PASSWORD: <password>')

    return options
예제 #21
0
            mc = mtotal * np.power(eta, 3. / 5.)
            m1, m2 = bppu.mc2ms(mc, eta)
        elif has_q:
            m1 = mtotal / (1 + samples['q'])
            m2 = mtotal - m1
        else:
            raise ValueError("Chirp mass given with no mass ratio.")
    return mc, eta, m1, m2, mtotal


if __name__ == "__main__":
    parser = OptionParser(description=__doc__,
                          usage="%prog [options] [INPUT]",
                          option_list=[
                              Option("-o",
                                     "--output",
                                     metavar="FILE.xml",
                                     help="name of output XML file"),
                              Option("--num-of-injs",
                                     metavar="NUM",
                                     type=int,
                                     default=200,
                                     help="number of injections"),
                              Option("--approx",
                                     metavar="APPROX",
                                     default="SpinTaylorT4threePointFivePN",
                                     help="approximant to be injected"),
                              Option("--taper",
                                     metavar="TAPER",
                                     default="TAPER_NONE",
                                     help="Taper methods for injections"),
                              Option("--flow",
예제 #22
0
"""
Create summary plots for sky maps of found injections, binned cumulatively by
false alarm rate.
"""
from __future__ import division
__author__ = "Leo Singer <*****@*****.**>"

# Command line interface.
from optparse import Option, OptionParser
from lalinference.bayestar import command

opts, args = OptionParser(
    formatter=command.NewlinePreservingHelpFormatter(),
    description=__doc__,
    option_list=[
        Option("--cumulative", action="store_true"),
        Option("--normed", action="store_true"),
        Option("--group-by",
               choices=("far", "snr"),
               metavar="far|snr",
               default="far",
               help="Group plots by false alarm rate (FAR) or " +
               "signal to noise ratio (SNR) [default: %default]"),
        Option(
            "--pp-confidence-interval",
            type=float,
            metavar="PCT",
            default=95,
            help="If all inputs files have the same number of "
            "samples, overlay binomial confidence bands for this percentage on "
            "the P--P plot [default: %default]")
예제 #23
0
class Command(object):
    """Base class for command line applications.

    :keyword app: The current app.
    :keyword get_app: Callable returning the current app if no app provided.

    """
    #: Arg list used in help.
    args = ''

    #: Application version.
    version = celery.__version__

    #: If false the parser will raise an exception if positional
    #: args are provided.
    supports_args = True

    #: List of options (without preload options).
    option_list = ()

    #: List of options to parse before parsing other options.
    preload_options = (
        Option("--app",
               default=None,
               action="store",
               dest="app",
               help="Name of the app instance to use. "),
        Option("--loader",
               default=None,
               action="store",
               dest="loader",
               help="Name of the loader class to use. "
               "Taken from the environment variable CELERY_LOADER, "
               "or 'default' if that is not set."),
        Option("--config",
               default="celeryconfig",
               action="store",
               dest="config_module",
               help="Name of the module to read configuration from."))

    #: Enable if the application should support config from the cmdline.
    enable_config_from_cmdline = False

    #: Default configuration namespace.
    namespace = "celery"

    Parser = OptionParser

    def __init__(self, app=None, get_app=None):
        self.app = app
        self.get_app = get_app or self._get_default_app

    def run(self, *args, **options):
        """This is the body of the command called by :meth:`handle_argv`."""
        raise NotImplementedError("subclass responsibility")

    def execute_from_commandline(self, argv=None):
        """Execute application from command line.

        :keyword argv: The list of command line arguments.
                       Defaults to ``sys.argv``.

        """
        if argv is None:
            argv = list(sys.argv)
        argv = self.setup_app_from_commandline(argv)
        prog_name = os.path.basename(argv[0])
        return self.handle_argv(prog_name, argv[1:])

    def usage(self):
        """Returns the command-line usage string for this app."""
        return "%%prog [options] %s" % (self.args, )

    def get_options(self):
        """Get supported command line options."""
        return self.option_list

    def handle_argv(self, prog_name, argv):
        """Parses command line arguments from ``argv`` and dispatches
        to :meth:`run`.

        :param prog_name: The program name (``argv[0]``).
        :param argv: Command arguments.

        Exits with an error message if :attr:`supports_args` is disabled
        and ``argv`` contains positional arguments.

        """
        options, args = self.parse_options(prog_name, argv)
        if not self.supports_args and args:
            sys.stderr.write("\nUnrecognized command line arguments: %r\n" %
                             (", ".join(args), ))
            sys.stderr.write("\nTry --help?\n")
            sys.exit(1)
        return self.run(*args, **vars(options))

    def parse_options(self, prog_name, arguments):
        """Parse the available options."""
        # Don't want to load configuration to just print the version,
        # so we handle --version manually here.
        if "--version" in arguments:
            print(self.version)
            sys.exit(0)
        parser = self.create_parser(prog_name)
        options, args = parser.parse_args(arguments)
        return options, args

    def create_parser(self, prog_name):
        return self.Parser(prog=prog_name,
                           usage=self.usage(),
                           version=self.version,
                           option_list=(self.preload_options +
                                        self.get_options()))

    def setup_app_from_commandline(self, argv):
        preload_options = self.parse_preload_options(argv)
        app = (preload_options.pop("app", None) or os.environ.get("CELERY_APP")
               or self.app)
        loader = (preload_options.pop("loader", None)
                  or os.environ.get("CELERY_LOADER") or "default")
        config_module = preload_options.pop("config_module", None)
        if config_module:
            os.environ["CELERY_CONFIG_MODULE"] = config_module
        if app:
            self.app = self.get_cls_by_name(app)
        else:
            self.app = self.get_app(loader=loader)
        if self.enable_config_from_cmdline:
            argv = self.process_cmdline_config(argv)
        return argv

    def get_cls_by_name(self, name):
        from celery.utils import get_cls_by_name, import_from_cwd
        return get_cls_by_name(name, imp=import_from_cwd)

    def process_cmdline_config(self, argv):
        try:
            cargs_start = argv.index('--')
        except ValueError:
            return argv
        argv, cargs = argv[:cargs_start], argv[cargs_start + 1:]
        self.app.config_from_cmdline(cargs, namespace=self.namespace)
        return argv

    def parse_preload_options(self, args):
        acc = {}
        preload_options = dict(
            (opt._long_opts[0], opt.dest) for opt in self.preload_options)
        for arg in args:
            if arg.startswith('--') and '=' in arg:
                key, value = arg.split('=', 1)
                dest = preload_options.get(key)
                if dest:
                    acc[dest] = value
        return acc

    def _get_default_app(self, *args, **kwargs):
        return celery.Celery(*args, **kwargs)
예제 #24
0
def processCommandline():
    options = [
        Option('--systemid',
               action='store',
               help='(FOR TESTING ONLY) alternative systemid path/filename. ' +
               'The system default is used if not specified.'),
        Option('--rhn-cert',
               action='store',
               help='new RHN certificate path/filename (default is' +
               ' %s - the saved RHN cert).' % DEFAULT_RHN_CERT_LOCATION),
        Option('--no-ssl',
               action='store_true',
               help='(FOR TESTING ONLY) disables SSL'),
        Option('--sanity-only',
               action='store_true',
               help="confirm certificate sanity. Does not activate" +
               "the Red Hat Satellite locally or remotely."),
        Option('--ignore-expiration',
               action='store_true',
               help='execute regardless of the expiration' +
               'of the RHN Certificate (not recommended).'),
        Option('--ignore-version-mismatch',
               action='store_true',
               help='execute regardless of version ' +
               'mismatch of existing and new certificate.'),
        Option('-v',
               '--verbose',
               action='count',
               help='be verbose ' +
               '(accumulable: -vvv means "be *really* verbose").'),
        Option('--dump-version',
               action='store',
               help="requested version of XML dump"),
        Option('--manifest',
               action='store',
               help='the RHSM manifest path/filename to activate for CDN'),
    ]

    options, args = OptionParser(option_list=options).parse_args()

    # we take no extra commandline arguments that are not linked to an option
    if args:
        msg = "ERROR: these arguments make no sense in this context (try --help): %s\n" % repr(
            args)
        raise ValueError(msg)

    initCFG('server.satellite')

    # systemid
    if not options.systemid:
        options.systemid = DEFAULT_SYSTEMID_LOCATION
    options.systemid = fileutils.cleanupAbsPath(options.systemid)

    if not options.rhn_cert and not options.manifest:
        print "NOTE: using backup cert as default: %s" % DEFAULT_RHN_CERT_LOCATION
        options.rhn_cert = DEFAULT_RHN_CERT_LOCATION

    if options.manifest:
        if not cdn_activation:
            sys.stderr.write(
                "ERROR: Package spacewalk-backend-cdn has to be installed for using --manifest.\n"
            )
            sys.exit(1)
        cdn_manifest = Manifest(options.manifest)
        tmp_cert_path = cdn_manifest.get_certificate_path()
        if tmp_cert_path is not None:
            options.rhn_cert = tmp_cert_path

    options.rhn_cert = fileutils.cleanupAbsPath(options.rhn_cert)
    if not os.path.exists(options.rhn_cert):
        sys.stderr.write("ERROR: RHN Cert (%s) does not exist\n" %
                         options.rhn_cert)
        sys.exit(1)

    if not options.sanity_only and CFG.DISCONNECTED:
        sys.stderr.write(
            """ERROR: Satellite server has been setup to run in disconnected mode.
       Correct server configuration in /etc/rhn/rhn.conf.
""")
        sys.exit(1)

    options.server = ''
    if not options.sanity_only:
        if not CFG.RHN_PARENT:
            sys.stderr.write(
                "ERROR: rhn_parent is not set in /etc/rhn/rhn.conf\n")
            sys.exit(1)
        options.server = idn_ascii_to_puny(
            rhnLib.parseUrl(CFG.RHN_PARENT)[1].split(':')[0])
        print 'RHN_PARENT: %s' % options.server

    options.http_proxy = idn_ascii_to_puny(CFG.HTTP_PROXY)
    options.http_proxy_username = CFG.HTTP_PROXY_USERNAME
    options.http_proxy_password = CFG.HTTP_PROXY_PASSWORD
    options.ca_cert = CFG.CA_CHAIN
    if options.verbose:
        print 'HTTP_PROXY: %s' % options.http_proxy
        print 'HTTP_PROXY_USERNAME: %s' % options.http_proxy_username
        print 'HTTP_PROXY_PASSWORD: <password>'
        if not options.no_ssl:
            print 'CA_CERT: %s' % options.ca_cert

    return options
예제 #25
0
import traceback

import hal
from optparse import Option, OptionParser
import gtk
import gtk.glade
import gobject
import signal

import gladevcp.makepins
from gladevcp.gladebuilder import GladeBuilder
from gladevcp import xembed
from hal_glib import GStat
GSTAT = GStat()

options = [ Option( '-c', dest='component', metavar='NAME'
                  , help="Set component name to NAME. Default is basename of UI file")
          , Option( '-d', action='store_true', dest='debug'
                  , help="Enable debug output")
          , Option( '-g', dest='geometry', default="", help="""Set geometry WIDTHxHEIGHT+XOFFSET+YOFFSET.
Values are in pixel units, XOFFSET/YOFFSET is referenced from top left of screen
use -g WIDTHxHEIGHT for just setting size or -g +XOFFSET+YOFFSET for just position""")
          , Option( '-H', dest='halfile', metavar='FILE'
                  , help="execute hal statements from FILE with halcmd after the component is set up and ready")
          , Option( '-m', dest='maximum', default=False, help="Force panel window to maxumize")
          , Option( '-r', dest='gtk_rc', default="",
                    help="read custom GTK rc file to set widget style")
          , Option( '-R', dest='gtk_workaround', action='store_false',default=True,
                    help="disable workaround for GTK bug to properly read ~/.gtkrc-2.0 gtkrc files")
          , Option( '-t', dest='theme', default="", help="Set gtk theme. Default is system theme")
          , Option( '-x', dest='parent', type=int, metavar='XID'
                  , help="Reparent gladevcp into an existing window XID instead of creating a new top level window")
예제 #26
0
import sys
import xmlrpclib
from time import strptime
from datetime import datetime

from optparse import OptionParser, Option
from spacewalk.common.cli import getUsernamePassword, xmlrpc_login, xmlrpc_logout

_topdir = '/usr/share/rhn'
if _topdir not in sys.path:
    sys.path.append(_topdir)

client = None

options_table = [
    Option("-v", "--verbose", action="count", help="Increase verbosity"),
    Option("-u", "--username", action="store", help="Username"),
    Option("-p", "--password", action="store", help="Password"),
    Option("-d", "--delete", action="count", help="Delete snapshots."),
    Option("-l", "--list", action="count", help="List snapshot summary."),
    Option("-L",
           "--long-list",
           action="count",
           help="Display comprehensive snapshot list."),
    Option("-a",
           "--all",
           action="count",
           help="Include all snapshots based on criteria provided."),
    Option(
        "--start-date",
        action="store",
예제 #27
0
class Command(object):
    """Base class for command-line applications.

    :keyword app: The current app.
    :keyword get_app: Callable returning the current app if no app provided.

    """
    Parser = OptionParser

    #: Arg list used in help.
    args = ''

    #: Application version.
    version = celery.VERSION_BANNER

    #: If false the parser will raise an exception if positional
    #: args are provided.
    supports_args = True

    #: List of options (without preload options).
    option_list = ()

    # module Rst documentation to parse help from (if any)
    doc = None

    # Some programs (multi) does not want to load the app specified
    # (Issue #1008).
    respects_app_option = True

    #: List of options to parse before parsing other options.
    preload_options = (
        Option('-A', '--app', default=None),
        Option('-b', '--broker', default=None),
        Option('--loader', default=None),
        Option('--config', default='celeryconfig', dest='config_module'),
    )

    #: Enable if the application should support config from the cmdline.
    enable_config_from_cmdline = False

    #: Default configuration namespace.
    namespace = 'celery'

    #: Text to print at end of --help
    epilog = None

    #: Text to print in --help before option list.
    description = ''

    #: Set to true if this command doesn't have subcommands
    leaf = True

    def __init__(self, app=None, get_app=None):
        self.app = app
        self.get_app = get_app or self._get_default_app

    def run(self, *args, **options):
        """This is the body of the command called by :meth:`handle_argv`."""
        raise NotImplementedError('subclass responsibility')

    def execute_from_commandline(self, argv=None):
        """Execute application from command-line.

        :keyword argv: The list of command-line arguments.
                       Defaults to ``sys.argv``.

        """
        if argv is None:
            argv = list(sys.argv)
        # Should we load any special concurrency environment?
        self.maybe_patch_concurrency(argv)
        self.on_concurrency_setup()

        # Dump version and exit if '--version' arg set.
        self.early_version(argv)
        argv = self.setup_app_from_commandline(argv)
        prog_name = os.path.basename(argv[0])
        return self.handle_argv(prog_name, argv[1:])

    def run_from_argv(self, prog_name, argv=None):
        return self.handle_argv(prog_name, sys.argv if argv is None else argv)

    def maybe_patch_concurrency(self, argv=None):
        argv = argv or sys.argv
        pool_option = self.with_pool_option(argv)
        if pool_option:
            maybe_patch_concurrency(argv, *pool_option)
            short_opts, long_opts = pool_option

    def on_concurrency_setup(self):
        pass

    def usage(self, command):
        """Returns the command-line usage string for this app."""
        return '%%prog [options] {0.args}'.format(self)

    def get_options(self):
        """Get supported command-line options."""
        return self.option_list

    def expanduser(self, value):
        if isinstance(value, basestring):
            return os.path.expanduser(value)
        return value

    def handle_argv(self, prog_name, argv):
        """Parses command-line arguments from ``argv`` and dispatches
        to :meth:`run`.

        :param prog_name: The program name (``argv[0]``).
        :param argv: Command arguments.

        Exits with an error message if :attr:`supports_args` is disabled
        and ``argv`` contains positional arguments.

        """
        options, args = self.prepare_args(*self.parse_options(prog_name, argv))
        return self.run(*args, **options)

    def prepare_args(self, options, args):
        if options:
            options = dict((k, self.expanduser(v))
                           for k, v in vars(options).iteritems()
                           if not k.startswith('_'))
        args = [self.expanduser(arg) for arg in args]
        self.check_args(args)
        return options, args

    def check_args(self, args):
        if not self.supports_args and args:
            self.die(ARGV_DISABLED.format(', '.join(args)), EX_USAGE)

    def die(self, msg, status=EX_FAILURE):
        print(msg, file=sys.stderr)
        sys.exit(status)

    def early_version(self, argv):
        if '--version' in argv:
            print(self.version)
            sys.exit(0)

    def parse_options(self, prog_name, arguments):
        """Parse the available options."""
        # Don't want to load configuration to just print the version,
        # so we handle --version manually here.
        parser = self.create_parser(prog_name)
        return parser.parse_args(arguments)

    def create_parser(self, prog_name, command=None):
        return self.prepare_parser(
            self.Parser(prog=prog_name,
                        usage=self.usage(command),
                        version=self.version,
                        epilog=self.epilog,
                        formatter=HelpFormatter(),
                        description=self.description,
                        option_list=(self.preload_options +
                                     self.get_options())))

    def prepare_parser(self, parser):
        docs = [self.parse_doc(doc) for doc in (self.doc, __doc__) if doc]
        for doc in docs:
            for long_opt, help in doc.iteritems():
                option = parser.get_option(long_opt)
                if option is not None:
                    option.help = ' '.join(help).format(default=option.default)
        return parser

    def prepare_preload_options(self, options):
        """Optional handler to do additional processing of preload options.

        Configuration must not have been initialized
        until after this is called.

        """
        pass

    def setup_app_from_commandline(self, argv):
        preload_options = self.parse_preload_options(argv)
        self.prepare_preload_options(preload_options)
        app = (preload_options.get('app') or os.environ.get('CELERY_APP')
               or self.app)
        loader = (preload_options.get('loader')
                  or os.environ.get('CELERY_LOADER') or 'default')
        broker = preload_options.get('broker', None)
        if broker:
            os.environ['CELERY_BROKER_URL'] = broker
        config_module = preload_options.get('config_module')
        if config_module:
            os.environ['CELERY_CONFIG_MODULE'] = config_module
        if self.respects_app_option:
            if app and self.respects_app_option:
                self.app = self.find_app(app)
            elif self.app is None:
                self.app = self.get_app(loader=loader)
            if self.enable_config_from_cmdline:
                argv = self.process_cmdline_config(argv)
        else:
            self.app = celery.Celery()
        return argv

    def find_app(self, app):
        try:
            sym = self.symbol_by_name(app)
        except AttributeError:
            # last part was not an attribute, but a module
            sym = import_from_cwd(app)
        if isinstance(sym, ModuleType):
            if getattr(sym, '__path__', None):
                return self.find_app('{0}.celery:'.format(app.replace(':',
                                                                      '')))
            return sym.celery
        return sym

    def symbol_by_name(self, name):
        return symbol_by_name(name, imp=import_from_cwd)

    get_cls_by_name = symbol_by_name  # XXX compat

    def process_cmdline_config(self, argv):
        try:
            cargs_start = argv.index('--')
        except ValueError:
            return argv
        argv, cargs = argv[:cargs_start], argv[cargs_start + 1:]
        self.app.config_from_cmdline(cargs, namespace=self.namespace)
        return argv

    def parse_preload_options(self, args):
        acc = {}
        opts = {}
        for opt in self.preload_options:
            for t in (opt._long_opts, opt._short_opts):
                opts.update(dict(izip(t, [opt.dest] * len(t))))
        index = 0
        length = len(args)
        while index < length:
            arg = args[index]
            if arg.startswith('--') and '=' in arg:
                key, value = arg.split('=', 1)
                dest = opts.get(key)
                if dest:
                    acc[dest] = value
            elif arg.startswith('-'):
                dest = opts.get(arg)
                if dest:
                    acc[dest] = args[index + 1]
                    index += 1
            index += 1
        return acc

    def parse_doc(self, doc):
        options, in_option = defaultdict(list), None
        for line in doc.splitlines():
            if line.startswith('.. cmdoption::'):
                m = find_long_opt.match(line)
                if m:
                    in_option = m.groups()[0].strip()
                assert in_option, 'missing long opt'
            elif in_option and line.startswith(' ' * 4):
                options[in_option].append(
                    find_rst_ref.sub(r'\1', line.strip()).replace('`', ''))
        return options

    def with_pool_option(self, argv):
        """Returns tuple of ``(short_opts, long_opts)`` if the command
        supports a pool argument, and used to monkey patch eventlet/gevent
        environments as early as possible.

        E.g::
              has_pool_option = (['-P'], ['--pool'])
        """
        pass

    def simple_format(self, s, match=find_sformat, expand=r'\1', **keys):
        if s:
            host = socket.gethostname()
            name, _, domain = host.partition('.')
            keys = dict({'%': '%', 'h': host, 'n': name, 'd': domain}, **keys)
            return match.sub(lambda m: keys[m.expand(expand)], s)

    def _get_default_app(self, *args, **kwargs):
        from celery._state import get_current_app
        return get_current_app()  # omit proxy
예제 #28
0
"""
nodemgr command line actions and options
"""
import node
from storage import Storage
from rcOptParser import OptParser
from optparse import Option

PROG = "nodemgr"

OPT = Storage({
    "api":
    Option("--api",
           default=None,
           action="store",
           dest="api",
           help="Specify a collector api url different from the "
           "one set in node.conf."),
    "access":
    Option("--access",
           default="rwo",
           action="store",
           dest="access",
           help="The access mode of the volume. rwo, roo, rwx, rox."),
    "add":
    Option("--add",
           default=None,
           action="store",
           help="A list member to add to the value pointed by :opt:`--param`. "
           "If :opt:`--index` is set, insert the new element at the "
           "specified position in the list."),
예제 #29
0
def _getOptionsTree(defs):
    """ passing in the defaults dictionary (which is not static)
        build the options tree dependent on whats on the commandline
    """

    _optCAKeyPassword = make_option('-p',
                                    '--password',
                                    action='store',
                                    type="string",
                                    help='CA password')
    _optCaKey = make_option('--ca-key',
                            action='store',
                            type="string",
                            help='CA private key filename (default: %s)' %
                            defs['--ca-key'])
    _optCaCert = make_option('--ca-cert',
                             action='store',
                             type="string",
                             help='CA certificate filename (default: %s)' %
                             defs['--ca-cert'])

    #_optServerKeyPassword = make_option('-p', '--password', action='store', type="string", help='password to generate the web server's SSL private key')
    _optCertExp = make_option(
        '--cert-expiration',
        action='store',
        type="int",
        help='expiration of certificate (default: %s days)' %
        (int(defs['--cert-expiration'])))

    _optServerKey = make_option(
        '--server-key',
        action='store',
        type="string",
        help="the web server's SSL private key filename (default: %s)" %
        defs['--server-key'])
    _optServerCertReq = make_option(
        '--server-cert-req',
        action='store',
        type="string",
        help=
        "location of the web server's SSL certificate request filename (default: %s)"
        % defs['--server-cert-req'])
    _optServerCert = make_option(
        '--server-cert',
        action='store',
        type="string",
        help='the web server SSL certificate filename (default: %s)' %
        defs['--server-cert'])

    _optCaForce = make_option(
        '-f',
        '--force',
        action='store_true',
        help=
        'forcibly create a new CA SSL private key and/or public certificate')

    _optCaKeyOnly = make_option(
        '--key-only',
        action='store_true',
        help=
        '(rarely used) only generate a CA SSL private key. Review "--gen-ca --key-only --help" for more information.'
    )
    _optCaCertOnly = make_option(
        '--cert-only',
        action='store_true',
        help=
        '(rarely used) only generate a CA SSL public certificate. Review "--gen-ca --cert-only --help" for more information.'
    )

    _optServerKeyOnly = make_option(
        '--key-only',
        action='store_true',
        help=
        """(rarely used) only generate the web server's SSL private key. Review "--gen-server --key-only --help" for more information."""
    )
    _optServerCertReqOnly = make_option(
        '--cert-req-only',
        action='store_true',
        help=
        """(rarely used) only generate the web server's SSL certificate request. Review "--gen-server --cert-req-only --help" for more information."""
    )
    _optServerCertOnly = make_option(
        '--cert-only',
        action='store_true',
        help=
        """(rarely used) only generate the web server's SSL certificate. Review "--gen-server --cert-only --help" for more information."""
    )

    _optCaCertRpm = make_option(
        '--ca-cert-rpm',
        action='store',
        type="string",
        help=
        '(rarely changed) RPM name that houses the CA SSL public certificate (the base filename, not filename-version-release.noarch.rpm).'
    )
    _optServerRpm = make_option(
        '--server-rpm',
        action='store',
        type="string",
        help=
        "(rarely changed) RPM name that houses the web server's SSL key set (the base filename, not filename-version-release.noarch.rpm)."
    )
    _optServerTar = make_option(
        '--server-tar',
        action='store',
        type="string",
        help=
        "(rarely changed) name of tar archive of the web server's SSL key set and CA SSL public certificate that is used solely by the hosted RHN Proxy installation routines (the base filename, not filename-version-release.tar)."
    )

    _optRpmPackager = make_option(
        '--rpm-packager',
        action='store',
        type="string",
        help=
        '(rarely used) packager of the generated RPM, such as "RHN Admin <*****@*****.**>".'
    )
    _optRpmVender = make_option(
        '--rpm-vendor',
        action='store',
        type="string",
        help=
        '(rarely used) vendor of the generated RPM, such as "IS/IT Example Corp.".'
    )

    _optRpmOnly = make_option(
        '--rpm-only',
        action='store_true',
        help=
        '(rarely used) only generate a deployable RPM. (and tar archive if used during the --gen-server step) Review "<baseoption> --rpm-only --help" for more information.'
    )
    _optNoRpm = make_option(
        '--no-rpm',
        action='store_true',
        help='(rarely used) do everything *except* generate an RPM.')

    _optSetHostname = make_option(
        '--set-hostname',
        action='store',
        type="string",
        help=
        'hostname of the web server you are installing the key set on (default: %s)'
        % repr(defs['--set-hostname']))

    _optSetCname = make_option(
        '--set-cname',
        action='append',
        type="string",
        help='cname alias of the web server, can be specified multiple times')

    _buildRpmOptions = [_optRpmPackager, _optRpmVender, _optRpmOnly]

    _genOptions = [
        make_option(
            '-v',
            '--verbose',
            action='count',
            help='be verbose. Accumulative: -vvv means "be *really* verbose".'
        ),
        make_option('-d',
                    '--dir',
                    action='store',
                    help="build directory (default: %s)" % defs['--dir']),
        make_option('-q',
                    '--quiet',
                    action='store_true',
                    help="be quiet. No output."),
    ]

    _genConfOptions = [
        make_option('--set-country',
                    action='store',
                    type="string",
                    help='2 letter country code (default: %s)' %
                    repr(defs['--set-country'])),
        make_option('--set-state',
                    action='store',
                    type="string",
                    help='state or province (default: %s)' %
                    repr(defs['--set-state'])),
        make_option('--set-city',
                    action='store',
                    type="string",
                    help='city or locality (default: %s)' %
                    repr(defs['--set-city'])),
        make_option(
            '--set-org',
            action='store',
            type="string",
            help=
            'organization or company name, such as "Red Hat Inc." (default: %s)'
            % repr(defs['--set-org'])),
        make_option('--set-org-unit',
                    action='store',
                    type="string",
                    help='organizational unit, such as "RHN" (default: %s)' %
                    repr(defs['--set-org-unit'])),
        make_option('--set-email',
                    action='store',
                    type="string",
                    help='email address (default: %s)' %
                    repr(defs['--set-email'])),
    ]

    _caConfOptions = [
        make_option('--set-common-name',
                    action='store',
                    type="string",
                    help='common name (default: %s)' %
                    repr(defs['--set-common-name'])),
    ] + _genConfOptions

    _serverConfOptions = [_optSetHostname, _optSetCname] + _genConfOptions

    # CA generation options
    _caOptions = [
        _optCaForce,
        _optCAKeyPassword,
        _optCaKey,
    ]

    # CA cert generation options
    _caCertOptions = [
        _optCaForce,
        _optCAKeyPassword,
        _optCaKey,
        _optCaCert,
        _optCertExp,
    ] + _caConfOptions

    # server key generation options
    _serverKeyOptions = [
        #_optServerKeyPassword,
        _optServerKey,
    ]

    # server cert req generation options
    _serverCertReqOptions = [
        #_optServerKeyPassword,
        _optServerKey,
        _optServerCertReq,
    ]

    # server cert generation options
    _serverCertOptions = [
        _optCAKeyPassword,
        _optCaCert,
        _optCaKey,
        _optServerCertReq,
        Option(
            '--startdate',
            action='store',
            type="string",
            default=defs['--startdate'],
            help=
            "start date for the web server's SSL certificate validity (format: YYMMDDHHMMSSZ - where Z is a letter; default is 1 week ago: %s)"
            % defs['--startdate']),
        _optServerCert,
        _optCertExp,
    ]

    # the base options
    _optGenCa = make_option(
        '--gen-ca',
        action='store_true',
        help=
        'generate a Certificate Authority (CA) key pair and public RPM. Review "--gen-ca --help" for more information.'
    )
    _optGenServer = make_option(
        "--gen-server",
        action='store_true',
        help=
        """generate the web server's SSL key set, RPM and tar archive. Review "--gen-server --help" for more information."""
    )

    # CA build option tree set possibilities
    _caSet = [_optGenCa] + _caOptions + _caCertOptions \
      + _genOptions + [_optCaKeyOnly, _optCaCertOnly] + _buildRpmOptions \
      + [_optCaCertRpm, _optNoRpm]
    _caKeyOnlySet = [_optGenCa] + _caOptions + _genOptions \
      + [_optCaKeyOnly]
    _caCertOnlySet = [_optGenCa] + _caOptions + _caCertOptions \
      + _genOptions + [_optCaCertOnly]
    _caRpmOnlySet = [_optGenCa, _optCaKey, _optCaCert] \
      + _buildRpmOptions + [_optCaCertRpm] + _genOptions

    # server build option tree set possibilities
    _serverSet = [_optGenServer] + _serverKeyOptions + _serverCertReqOptions \
      + _serverCertOptions + _serverConfOptions + _genOptions \
      + [_optServerKeyOnly, _optServerCertReqOnly, _optServerCertOnly] \
      + _buildRpmOptions + [_optServerRpm, _optServerTar, _optNoRpm]
    _serverKeyOnlySet = [_optGenServer] + _serverKeyOptions \
      + _genOptions + [_optServerKeyOnly]
    _serverCertReqOnlySet = [_optGenServer] + _serverKeyOptions \
      + _serverCertReqOptions + _serverConfOptions \
      + _genOptions + [_optServerCertReqOnly]
    _serverCertOnlySet = [_optGenServer] + _serverCertOptions \
      + _genOptions + [_optServerCertOnly]
    _serverRpmOnlySet = [_optGenServer, _optServerKey, _optServerCertReq, _optServerCert, _optSetHostname, _optSetCname ] \
      + _buildRpmOptions + [_optServerRpm, _optServerTar] + _genOptions

    optionsTree = {
        '--gen-ca': _caSet,
        '--gen-server': _serverSet,
    }

    # quick check about the --*-only options
    _onlyOpts = ['--key-only', '--cert-req-only', '--cert-only', '--rpm-only']
    _onlyIntersection = setIntersection(sys.argv, _onlyOpts)
    if len(_onlyIntersection) > 1:
        sys.stderr.write("""\
ERROR: cannot use these options in combination:
       %s\n""" % repr(_onlyIntersection))
        sys.exit(errnoGeneralError)
    _onlyIntersection = setIntersection(sys.argv, ['--rpm-only', '--no-rpm'])
    if len(_onlyIntersection) > 1:
        sys.stderr.write("""\
ERROR: cannot use these options in combination:
       %s\n""" % repr(_onlyIntersection))
        sys.exit(errnoGeneralError)

    if '--key-only' in sys.argv:
        optionsTree['--gen-ca'] = _caKeyOnlySet
        optionsTree['--gen-server'] = _serverKeyOnlySet
    elif '--cert-only' in sys.argv:
        optionsTree['--gen-ca'] = _caCertOnlySet
        optionsTree['--gen-server'] = _serverCertOnlySet
    elif '--cert-req-key-only' in sys.argv:
        optionsTree['--gen-server'] = _serverCertReqOnlySet
    elif '--rpm-only' in sys.argv:
        optionsTree['--gen-ca'] = _caRpmOnlySet
        optionsTree['--gen-server'] = _serverRpmOnlySet

    baseOptions = [_optGenCa, _optGenServer]
    return optionsTree, baseOptions
예제 #30
0
class inspect(Command):
    choices = {"active": 1.0,
               "active_queues": 1.0,
               "scheduled": 1.0,
               "reserved": 1.0,
               "stats": 1.0,
               "revoked": 1.0,
               "registered_tasks": 1.0,
               "enable_events": 1.0,
               "disable_events": 1.0,
               "ping": 0.2,
               "add_consumer": 1.0,
               "cancel_consumer": 1.0}
    option_list = Command.option_list + (
                Option("--timeout", "-t", type="float", dest="timeout",
                    default=None,
                    help="Timeout in seconds (float) waiting for reply"),
                Option("--destination", "-d", dest="destination",
                    help="Comma separated list of destination node names."))

    def usage(self, command):
        return "%%prog %s [options] %s [%s]" % (
                command, self.args, "|".join(self.choices.keys()))

    def run(self, *args, **kwargs):
        self.quiet = kwargs.get("quiet", False)
        if not args:
            raise Error("Missing inspect command. See --help")
        command = args[0]
        if command == "help":
            raise Error("Did you mean 'inspect --help'?")
        if command not in self.choices:
            raise Error("Unknown inspect command: %s" % command)

        destination = kwargs.get("destination")
        timeout = kwargs.get("timeout") or self.choices[command]
        if destination and isinstance(destination, basestring):
            destination = map(str.strip, destination.split(","))

        def on_reply(body):
            c = self.colored
            node = body.keys()[0]
            reply = body[node]
            status, preply = self.prettify(reply)
            self.say("->", c.cyan(node, ": ") + status, indent(preply))

        self.say("<-", command)
        i = self.app.control.inspect(destination=destination,
                                     timeout=timeout,
                                     callback=on_reply)
        replies = getattr(i, command)(*args[1:])
        if not replies:
            raise Error("No nodes replied within time constraint.")
        return replies

    def say(self, direction, title, body=""):
        c = self.colored
        if direction == "<-" and self.quiet:
            return
        dirstr = not self.quiet and c.bold(c.white(direction), " ") or ""
        self.out(c.reset(dirstr, title))
        if body and not self.quiet:
            self.out(body)