Exemplo n.º 1
0
def get_argument_parser(parser=None):
    if not parser:
        parser = argparse.ArgumentParser()

    _add_debug_options(parser)

    parser.add_argument('--reactor',
                        default=None,
                        choices=['select', 'poll', 'epoll', 'kqueue', 'iocp'],
                        help='Explicit Twisted reactor selection (optional).')

    parser.add_argument('--loglevel',
                        default='info',
                        choices=['none', 'error', 'warn', 'info', 'debug', 'trace'],
                        help='Initial log level.')

    parser.add_argument('-c',
                        '--cbdir',
                        type=six.text_type,
                        required=True,
                        help="Crossbar.io node directory (required).")

    parser.add_argument('-r',
                        '--realm',
                        type=six.text_type,
                        required=True,
                        help='Crossbar.io node (management) realm (required).')

    parser.add_argument('-p',
                        '--personality',
                        required=True,
                        choices=['standalone', 'fabric', 'fabriccenter'],
                        help='Crossbar.io personality (required).')

    parser.add_argument('-k',
                        '--klass',
                        required=True,
                        type=six.text_type,
                        help='Crossbar.io worker class (required).')

    parser.add_argument('-n',
                        '--node',
                        required=True,
                        type=six.text_type,
                        help='Crossbar.io node ID (required).')

    parser.add_argument('-w',
                        '--worker',
                        type=six.text_type,
                        required=True,
                        help='Crossbar.io worker ID (required).')

    parser.add_argument('--title',
                        type=six.text_type,
                        default=None,
                        help='Worker process title to set (optional).')

    parser.add_argument('--expose_controller',
                        type=bool,
                        default=False,
                        help='Expose node controller session to all components (this feature requires Crossbar.io Fabric extension).')

    parser.add_argument('--expose_shared',
                        type=bool,
                        default=False,
                        help='Expose a shared object to all components (this feature requires Crossbar.io Fabric extension).')

    parser.add_argument('--shutdown',
                        type=six.text_type,
                        default=None,
                        help='Shutdown method')

    return parser
Exemplo n.º 2
0
def main(prog, args, reactor, personality):
    """
    Entry point of Crossbar.io CLI.
    """
    from crossbar import _util
    _util.set_flags_from_args(args)

    term_print('CROSSBAR:MAIN_ENTRY')

    # print banner and usage notes when started with empty args
    #
    if args is not None and '--help' not in args:
        # if all args are options (start with "-"), then we don't have a command,
        # but we need one! hence, print a usage message
        if not [x for x in args if not x.startswith('-')]:
            _print_usage(prog, personality)
            return

    # create the top-level parser
    #
    parser = argparse.ArgumentParser(prog=prog, description=personality.DESC)

    _add_debug_options(parser)

    # create subcommand parser
    #
    subparsers = parser.add_subparsers(dest='command',
                                       title='commands',
                                       help='Command to run (required)')
    subparsers.required = True

    # #############################################################

    # "init" command
    #
    parser_init = subparsers.add_parser(
        'init', help='Initialize a new Crossbar.io node.')

    parser_init.add_argument(
        '--appdir',
        type=str,
        default=None,
        help=
        "Application base directory where to create app and node from template."
    )

    parser_init.set_defaults(func=_run_command_init)

    # "start" command
    #
    parser_start = subparsers.add_parser('start',
                                         help='Start a Crossbar.io node.')

    _add_log_arguments(parser_start)
    _add_cbdir_config(parser_start)

    parser_start.add_argument(
        '--shutdownafter',
        type=int,
        default=None,
        help='Automatically shutdown node after this many seconds.')

    if _HAS_VMPROF:
        parser_start.add_argument(
            '--vmprof',
            action='store_true',
            help='Profile node controller and native worker using vmprof.')

    parser_start.set_defaults(func=_run_command_start)

    # "stop" command
    #
    parser_stop = subparsers.add_parser('stop',
                                        help='Stop a Crossbar.io node.')

    parser_stop.add_argument(
        '--cbdir',
        type=str,
        default=None,
        help=
        "Crossbar.io node directory (overrides ${CROSSBAR_DIR} and the default ./.crossbar)"
    )

    parser_stop.set_defaults(func=_run_command_stop)

    # "status" command
    #
    parser_status = subparsers.add_parser(
        'status', help='Checks whether a Crossbar.io node is running.')

    parser_status.add_argument(
        '--cbdir',
        type=str,
        default=None,
        help=
        "Crossbar.io node directory (overrides ${CROSSBAR_DIR} and the default ./.crossbar)"
    )

    parser_status.add_argument(
        '--assert',
        type=str,
        default=None,
        choices=['running', 'stopped'],
        help=
        ("If given, assert the node is in this state, otherwise exit with error."
         ))

    parser_status.set_defaults(func=_run_command_status)

    # "check" command
    #
    parser_check = subparsers.add_parser(
        'check', help='Check a Crossbar.io node`s local configuration file.')

    _add_cbdir_config(parser_check)

    parser_check.set_defaults(func=_run_command_check)

    # "convert" command
    #
    parser_convert = subparsers.add_parser(
        'convert',
        help=
        'Convert a Crossbar.io node`s local configuration file from JSON to YAML or vice versa.'
    )

    _add_cbdir_config(parser_convert)

    parser_convert.set_defaults(func=_run_command_convert)

    # "upgrade" command
    #
    parser_upgrade = subparsers.add_parser(
        'upgrade',
        help=
        'Upgrade a Crossbar.io node`s local configuration file to current configuration file format.'
    )

    _add_cbdir_config(parser_upgrade)

    parser_upgrade.set_defaults(func=_run_command_upgrade)

    # "keygen" command
    #
    parser_keygen = subparsers.add_parser(
        'keygen',
        help=
        'Generate public/private keypairs for use with autobahn.wamp.cryptobox.KeyRing'
    )
    parser_keygen.set_defaults(func=_run_command_keygen)

    # "keys" command
    #
    parser_keys = subparsers.add_parser(
        'keys',
        help=
        'Print Crossbar.io release and node key (public key part by default).')

    parser_keys.add_argument(
        '--cbdir',
        type=str,
        default=None,
        help=
        "Crossbar.io node directory (overrides ${CROSSBAR_DIR} and the default ./.crossbar)"
    )

    parser_keys.add_argument(
        '--private',
        action='store_true',
        help='Print the node private key instead of the public key.')

    parser_keys.set_defaults(func=_run_command_keys)

    # "version" command
    #
    parser_version = subparsers.add_parser('version',
                                           help='Print software versions.')

    parser_version.set_defaults(func=_run_command_version)

    # "legal" command
    #
    parser_legal = subparsers.add_parser(
        'legal', help='Print legal and licensing information.')

    parser_legal.set_defaults(func=_run_command_legal)

    # INTERNAL USE! start a worker (this is used by the controller to start worker processes
    # but cannot be used outside that context.
    # argparse.SUPPRESS does not work here =( so we obfuscate the name to discourage use.
    #
    parser_worker = subparsers.add_parser('_exec_worker',
                                          help='Program internal use.')
    parser_worker = worker_main.get_argument_parser(parser_worker)

    parser_worker.set_defaults(func=worker_main._run_command_exec_worker)

    # #############################################################

    # parse cmd line args
    #
    options = parser.parse_args(args)
    options.argv = [prog] + args

    if hasattr(options, 'shutdownafter') and options.shutdownafter:
        options.shutdownafter = float(options.shutdownafter)

    # colored logging does not work on Windows, so overwrite it!
    # FIXME: however, printing the banner in color works at least now:
    # So maybe we can get the actual log output also working in color.
    if sys.platform == 'win32':
        options.color = False

    # Crossbar.io node directory
    #
    if hasattr(options, 'cbdir'):
        if not options.cbdir:
            if "CROSSBAR_DIR" in os.environ:
                options.cbdir = os.environ['CROSSBAR_DIR']
            elif os.path.isdir('.crossbar'):
                options.cbdir = '.crossbar'
            else:
                options.cbdir = '.'

        options.cbdir = os.path.abspath(options.cbdir)

        # convenience: if --cbdir points to a config file, take
        # the config file's base dirname as node directory
        if os.path.isfile(options.cbdir):
            options.cbdir = os.path.dirname(options.cbdir)

        # convenience: auto-create directory if not existing
        if not os.path.isdir(options.cbdir):
            try:
                os.mkdir(options.cbdir)
            except Exception as e:
                print("Could not create node directory: {}".format(e))
                sys.exit(1)
            else:
                print("Auto-created node directory {}".format(options.cbdir))

    # Crossbar.io node configuration file
    #
    if hasattr(options, 'config'):
        # if not explicit config filename is given, try to auto-detect .
        if not options.config:
            for f in ['config.yaml', 'config.json']:
                fn = os.path.join(options.cbdir, f)
                if os.path.isfile(fn) and os.access(fn, os.R_OK):
                    options.config = f
                    break

    # Log directory
    #
    if hasattr(options, 'logdir'):
        if options.logdir:
            options.logdir = os.path.abspath(
                os.path.join(options.cbdir, options.logdir))
            if not os.path.isdir(options.logdir):
                try:
                    os.mkdir(options.logdir)
                except Exception as e:
                    print("Could not create log directory: {}".format(e))
                    sys.exit(1)
                else:
                    print("Auto-created log directory {}".format(
                        options.logdir))

    # Start the logger
    #
    _start_logging(options, reactor)
    term_print('CROSSBAR:LOGGING_STARTED')

    # run the subcommand selected
    #
    try:
        options.func(options, reactor=reactor, personality=personality)
    except SystemExit as e:
        # SystemExit(0) is okay! Anything other than that is bad and should be
        # re-raised.
        if e.args[0] != 0:
            raise
Exemplo n.º 3
0
def get_argument_parser(parser=None):
    if not parser:
        parser = argparse.ArgumentParser()

    _add_debug_options(parser)

    parser.add_argument('--reactor',
                        default=None,
                        choices=['select', 'poll', 'epoll', 'kqueue', 'iocp'],
                        help='Explicit Twisted reactor selection (optional).')

    parser.add_argument('--loglevel',
                        default='info',
                        choices=['none', 'error', 'warn', 'info', 'debug', 'trace'],
                        help='Initial log level.')

    parser.add_argument('-c',
                        '--cbdir',
                        type=six.text_type,
                        required=True,
                        help="Crossbar.io node directory (required).")

    parser.add_argument('-r',
                        '--realm',
                        type=six.text_type,
                        required=True,
                        help='Crossbar.io node (management) realm (required).')

    parser.add_argument('-p',
                        '--personality',
                        required=True,
                        type=six.text_type,
                        help='Crossbar.io personality _class_ name, eg "crossbar.personality.Personality" (required).')

    parser.add_argument('-k',
                        '--klass',
                        required=True,
                        type=six.text_type,
                        help='Crossbar.io worker class, eg "crossbar.worker.container.ContainerController" (required).')

    parser.add_argument('-n',
                        '--node',
                        required=True,
                        type=six.text_type,
                        help='Crossbar.io node ID (required).')

    parser.add_argument('-w',
                        '--worker',
                        type=six.text_type,
                        required=True,
                        help='Crossbar.io worker ID (required).')

    parser.add_argument('--title',
                        type=six.text_type,
                        default=None,
                        help='Worker process title to set (optional).')

    parser.add_argument('--expose_controller',
                        type=bool,
                        default=False,
                        help='Expose node controller session to all components (this feature requires crossbarfx).')

    parser.add_argument('--expose_shared',
                        type=bool,
                        default=False,
                        help='Expose a shared object to all components (this feature requires crossbarfx).')

    parser.add_argument('--shutdown',
                        type=six.text_type,
                        default=None,
                        help='Shutdown method')

    return parser
Exemplo n.º 4
0
def get_argument_parser(parser=None):
    if not parser:
        parser = argparse.ArgumentParser()

    _add_debug_options(parser)

    parser.add_argument('--reactor',
                        default=None,
                        choices=['select', 'poll', 'epoll', 'kqueue', 'iocp'],
                        help='Explicit Twisted reactor selection (optional).')

    parser.add_argument(
        '--loglevel',
        default='info',
        choices=['none', 'error', 'warn', 'info', 'debug', 'trace'],
        help='Initial log level.')

    parser.add_argument('-c',
                        '--cbdir',
                        type=str,
                        required=True,
                        help="Crossbar.io node directory (required).")

    parser.add_argument('-r',
                        '--realm',
                        type=str,
                        required=True,
                        help='Crossbar.io node (management) realm (required).')

    parser.add_argument(
        '-p',
        '--personality',
        required=True,
        type=str,
        help=
        'Crossbar.io personality _class_ name, eg "crossbar.personality.Personality" (required).'
    )

    parser.add_argument(
        '-k',
        '--klass',
        required=True,
        type=str,
        help=
        'Crossbar.io worker class, eg "crossbar.worker.container.ContainerController" (required).'
    )

    parser.add_argument('-n',
                        '--node',
                        required=True,
                        type=str,
                        help='Crossbar.io node ID (required).')

    parser.add_argument('-w',
                        '--worker',
                        type=str,
                        required=True,
                        help='Crossbar.io worker ID (required).')

    parser.add_argument(
        '-e',
        '--extra',
        type=str,
        required=False,
        help=
        'Crossbar.io worker extra configuration from worker.options.extra (optional).'
    )

    parser.add_argument('--title',
                        type=str,
                        default=None,
                        help='Worker process title to set (optional).')

    parser.add_argument(
        '--expose_controller',
        type=bool,
        default=False,
        help=
        'Expose node controller session to all components (this feature requires crossbar).'
    )

    parser.add_argument(
        '--expose_shared',
        type=bool,
        default=False,
        help=
        'Expose a shared object to all components (this feature requires crossbar).'
    )

    parser.add_argument('--shutdown',
                        type=str,
                        default=None,
                        help='Shutdown method')

    parser.add_argument('--restart',
                        type=str,
                        default=None,
                        help='Restart method')

    if _HAS_VMPROF:
        parser.add_argument(
            '--vmprof',
            action='store_true',
            help='Profile node controller and native worker using vmprof.')

    return parser
Exemplo n.º 5
0
def main(prog, args, reactor, personality):
    """
    Entry point of Crossbar.io CLI.
    """
    from crossbar import _util
    _util.set_flags_from_args(args)

    term_print('CROSSBAR:MAIN_ENTRY')

    # print banner and usage notes when started with empty args
    #
    if args is not None and '--help' not in args:
        # if all args are options (start with "-"), then we don't have a command,
        # but we need one! hence, print a usage message
        if not [x for x in args if not x.startswith('-')]:
            _print_usage(prog, personality)
            return

    # create the top-level parser
    #
    parser = argparse.ArgumentParser(prog=prog, description=personality.DESC)

    _add_debug_options(parser)

    # create subcommand parser
    #
    subparsers = parser.add_subparsers(dest='command',
                                       title='commands',
                                       help='Command to run (required)')
    subparsers.required = True

    # #############################################################

    # "init" command
    #
    parser_init = subparsers.add_parser('init',
                                        help='Initialize a new Crossbar.io node.')

    parser_init.add_argument('--appdir',
                             type=six.text_type,
                             default=None,
                             help="Application base directory where to create app and node from template.")

    parser_init.set_defaults(func=_run_command_init)

    # "start" command
    #
    parser_start = subparsers.add_parser('start',
                                         help='Start a Crossbar.io node.')

    _add_log_arguments(parser_start)
    _add_cbdir_config(parser_start)

    parser_start.add_argument('--shutdownafter',
                              type=int,
                              default=None,
                              help='Automatically shutdown node after this many seconds.')

    parser_start.set_defaults(func=_run_command_start)

    # "stop" command
    #
    parser_stop = subparsers.add_parser('stop',
                                        help='Stop a Crossbar.io node.')

    parser_stop.add_argument('--cbdir',
                             type=six.text_type,
                             default=None,
                             help="Crossbar.io node directory (overrides ${CROSSBAR_DIR} and the default ./.crossbar)")

    parser_stop.set_defaults(func=_run_command_stop)

    # "status" command
    #
    parser_status = subparsers.add_parser('status',
                                          help='Checks whether a Crossbar.io node is running.')

    parser_status.add_argument('--cbdir',
                               type=six.text_type,
                               default=None,
                               help="Crossbar.io node directory (overrides ${CROSSBAR_DIR} and the default ./.crossbar)")

    parser_status.add_argument('--assert',
                               type=six.text_type,
                               default=None,
                               choices=['running', 'stopped'],
                               help=("If given, assert the node is in this state, otherwise exit with error."))

    parser_status.set_defaults(func=_run_command_status)

    # "check" command
    #
    parser_check = subparsers.add_parser('check',
                                         help='Check a Crossbar.io node`s local configuration file.')

    _add_cbdir_config(parser_check)

    parser_check.set_defaults(func=_run_command_check)

    # "convert" command
    #
    parser_convert = subparsers.add_parser('convert',
                                           help='Convert a Crossbar.io node`s local configuration file from JSON to YAML or vice versa.')

    _add_cbdir_config(parser_convert)

    parser_convert.set_defaults(func=_run_command_convert)

    # "upgrade" command
    #
    parser_upgrade = subparsers.add_parser('upgrade',
                                           help='Upgrade a Crossbar.io node`s local configuration file to current configuration file format.')

    _add_cbdir_config(parser_upgrade)

    parser_upgrade.set_defaults(func=_run_command_upgrade)

    # "keygen" command
    #
    if False:
        parser_keygen = subparsers.add_parser(
            'keygen',
            help='Generate public/private keypairs for use with autobahn.wamp.cryptobox.KeyRing'
        )
        parser_keygen.set_defaults(func=_run_command_keygen)

    # "keys" command
    #
    parser_keys = subparsers.add_parser('keys',
                                        help='Print Crossbar.io release and node key (public key part by default).')

    parser_keys.add_argument('--cbdir',
                             type=six.text_type,
                             default=None,
                             help="Crossbar.io node directory (overrides ${CROSSBAR_DIR} and the default ./.crossbar)")

    parser_keys.add_argument('--generate',
                             action='store_true',
                             help='Generate a new node key pair if none exists, or loads/checks existing.')

    parser_keys.add_argument('--private',
                             action='store_true',
                             help='Print the node private key instead of the public key.')

    parser_keys.set_defaults(func=_run_command_keys)

    # "version" command
    #
    parser_version = subparsers.add_parser('version',
                                           help='Print software versions.')

    parser_version.set_defaults(func=_run_command_version)

    # "legal" command
    #
    parser_legal = subparsers.add_parser('legal',
                                         help='Print legal and licensing information.')

    parser_legal.set_defaults(func=_run_command_legal)

    # INTERNAL USE! start a worker (this is used by the controller to start worker processes
    # but cannot be used outside that context.
    # argparse.SUPPRESS does not work here =( so we obfuscate the name to discourage use.
    #
    parser_worker = subparsers.add_parser('_exec_worker', help='Program internal use.')
    parser_worker = worker_main.get_argument_parser(parser_worker)

    parser_worker.set_defaults(func=worker_main._run_command_exec_worker)

    # #############################################################

    # parse cmd line args
    #
    options = parser.parse_args(args)
    options.argv = [prog] + args

    if hasattr(options, 'shutdownafter') and options.shutdownafter:
        options.shutdownafter = float(options.shutdownafter)

    # colored logging does not work on Windows, so overwrite it!
    # FIXME: however, printing the banner in color works at least now:
    # So maybe we can get the actual log output also working in color.
    if sys.platform == 'win32':
        options.color = False

    # Crossbar.io node directory
    #
    if hasattr(options, 'cbdir'):
        if not options.cbdir:
            if "CROSSBAR_DIR" in os.environ:
                options.cbdir = os.environ['CROSSBAR_DIR']
            elif os.path.isdir('.crossbar'):
                options.cbdir = '.crossbar'
            else:
                options.cbdir = '.'

        options.cbdir = os.path.abspath(options.cbdir)

        # convenience: if --cbdir points to a config file, take
        # the config file's base dirname as node directory
        if os.path.isfile(options.cbdir):
            options.cbdir = os.path.dirname(options.cbdir)

        # convenience: auto-create directory if not existing
        if not os.path.isdir(options.cbdir):
            try:
                os.mkdir(options.cbdir)
            except Exception as e:
                print("Could not create node directory: {}".format(e))
                sys.exit(1)
            else:
                print("Auto-created node directory {}".format(options.cbdir))

    # Crossbar.io node configuration file
    #
    if hasattr(options, 'config'):
        # if not explicit config filename is given, try to auto-detect .
        if not options.config:
            for f in ['config.yaml', 'config.json']:
                fn = os.path.join(options.cbdir, f)
                if os.path.isfile(fn) and os.access(fn, os.R_OK):
                    options.config = f
                    break

    # Log directory
    #
    if hasattr(options, 'logdir'):
        if options.logdir:
            options.logdir = os.path.abspath(os.path.join(options.cbdir, options.logdir))
            if not os.path.isdir(options.logdir):
                try:
                    os.mkdir(options.logdir)
                except Exception as e:
                    print("Could not create log directory: {}".format(e))
                    sys.exit(1)
                else:
                    print("Auto-created log directory {}".format(options.logdir))

    # Start the logger
    #
    _start_logging(options, reactor)
    term_print('CROSSBAR:LOGGING_STARTED')

    # run the subcommand selected
    #
    try:
        options.func(options, reactor=reactor, personality=personality)
    except SystemExit as e:
        # SystemExit(0) is okay! Anything other than that is bad and should be
        # re-raised.
        if e.args[0] != 0:
            raise