Beispiel #1
0
def run_command_start(options, reactor=None):
    """
    Subcommand "crossbar start".
    """
    assert reactor

    # do not allow to run more than one Crossbar.io instance
    # from the same Crossbar.io node directory
    #
    pid_data = check_is_running(options.cbdir)
    if pid_data:
        print(
            "Crossbar.io is already running from node directory {} (PID {}).".
            format(options.cbdir, pid_data['pid']))
        sys.exit(1)
    else:
        fp = os.path.join(options.cbdir, _PID_FILENAME)
        with open(fp, 'wb') as fd:
            argv = options.argv
            options_dump = vars(options)
            pid_data = {
                'pid': os.getpid(),
                'argv': argv,
                'options': {
                    x: y
                    for x, y in options_dump.items()
                    if x not in ["func", "argv"]
                }
            }
            fd.write("{}\n".format(
                json.dumps(pid_data,
                           sort_keys=False,
                           indent=4,
                           separators=(', ', ': '),
                           ensure_ascii=False)).encode('utf8'))

    # remove node PID file when reactor exits
    #
    def remove_pid_file():
        fp = os.path.join(options.cbdir, _PID_FILENAME)
        if os.path.isfile(fp):
            os.remove(fp)

    reactor.addSystemEventTrigger('after', 'shutdown', remove_pid_file)

    log = make_logger()

    # possibly generate new node key
    #
    from crossbar.controller.node import maybe_generate_key
    pubkey = maybe_generate_key(log, options.cbdir)

    # Print the banner.
    for line in BANNER.splitlines():
        log.info(click.style(("{:>40}").format(line), fg='yellow', bold=True))

    # bannerFormat = "{:<18} {:<24}"
    bannerFormat = "    {} {}"
    log.info(
        bannerFormat.format(
            "Crossbar.io Version:",
            click.style(crossbar.__version__, fg='yellow', bold=True)))
    if pubkey:
        log.info(
            bannerFormat.format("Node Public Key:",
                                click.style(pubkey, fg='yellow', bold=True)))
    log.info()

    log.info("Running from node directory '{cbdir}'", cbdir=options.cbdir)

    from twisted.python.reflect import qual
    log.info("Controller process starting ({python}-{reactor}) ..",
             python=platform.python_implementation(),
             reactor=qual(reactor.__class__).split('.')[-1])

    from crossbar.controller.node import Node
    from crossbar.common.checkconfig import InvalidConfigException

    # represents the running Crossbar.io node
    #
    node = Node(options.cbdir, reactor=reactor)

    # check and load the node configuration
    #
    try:
        if options.config:
            # load node config from file
            node.load(options.config)
        elif options.cdc:
            # load built-in CDC config
            node.load()
        else:
            # no config file, and not running CDC mode
            raise Exception(
                "Neither a node config was found, nor CDC mode is active.")
    except InvalidConfigException as e:
        log.error("Invalid node configuration")
        log.error("{e!s}", e=e)
        sys.exit(1)
    except:
        raise

    # now actually start the node ..
    #
    def start_crossbar():
        d = node.start(cdc_mode=options.cdc)

        def on_error(err):
            log.error("{e!s}", e=err.value)
            log.error("Could not start node")
            if reactor.running:
                reactor.stop()

        d.addErrback(on_error)

    reactor.callWhenRunning(start_crossbar)

    # enter event loop
    #
    try:
        reactor.run()
    except Exception:
        log.failure("Could not start reactor - {log_failure.value}")
Beispiel #2
0
def run_command_start(options, reactor=None):
    """
    Subcommand "crossbar start".
    """
    assert reactor

    # do not allow to run more than one Crossbar.io instance
    # from the same Crossbar.io node directory
    #
    pid_data = check_is_running(options.cbdir)
    if pid_data:
        print("Crossbar.io is already running from node directory {} (PID {}).".format(options.cbdir, pid_data['pid']))
        sys.exit(1)
    else:
        fp = os.path.join(options.cbdir, _PID_FILENAME)
        with open(fp, 'wb') as fd:
            argv = options.argv
            options_dump = vars(options)
            pid_data = {
                'pid': os.getpid(),
                'argv': argv,
                'options': {x: y for x, y in options_dump.items()
                            if x not in ["func", "argv"]}
            }
            fd.write("{}\n".format(
                json.dumps(
                    pid_data,
                    sort_keys=False,
                    indent=4,
                    separators=(', ', ': '),
                    ensure_ascii=False
                )
            ).encode('utf8'))

    # remove node PID file when reactor exits
    #
    def remove_pid_file():
        fp = os.path.join(options.cbdir, _PID_FILENAME)
        if os.path.isfile(fp):
            os.remove(fp)
    reactor.addSystemEventTrigger('after', 'shutdown', remove_pid_file)

    log = make_logger()

    # possibly generate new node key
    #
    from crossbar.controller.node import maybe_generate_key
    pubkey = maybe_generate_key(log, options.cbdir)

    # Print the banner.
    for line in BANNER.splitlines():
        log.info(click.style(("{:>40}").format(line), fg='yellow', bold=True))

    # bannerFormat = "{:<18} {:<24}"
    bannerFormat = "    {} {}"
    log.info(bannerFormat.format("Crossbar.io Version:", click.style(crossbar.__version__, fg='yellow', bold=True)))
    if pubkey:
        log.info(bannerFormat.format("Node Public Key:", click.style(pubkey, fg='yellow', bold=True)))
    log.info()

    log.info("Running from node directory '{cbdir}'", cbdir=options.cbdir)

    from twisted.python.reflect import qual
    log.info("Controller process starting ({python}-{reactor}) ..",
             python=platform.python_implementation(),
             reactor=qual(reactor.__class__).split('.')[-1])

    from crossbar.controller.node import Node
    from crossbar.common.checkconfig import InvalidConfigException

    # represents the running Crossbar.io node
    #
    node = Node(options.cbdir, reactor=reactor)

    # check and load the node configuration
    #
    try:
        if options.config:
            # load node config from file
            node.load(options.config)
        elif options.cdc:
            # load built-in CDC config
            node.load()
        else:
            # no config file, and not running CDC mode
            raise Exception("Neither a node config was found, nor CDC mode is active.")
    except InvalidConfigException as e:
        log.error("Invalid node configuration")
        log.error("{e!s}", e=e)
        sys.exit(1)
    except:
        raise

    # now actually start the node ..
    #
    def start_crossbar():
        d = node.start(cdc_mode=options.cdc)

        def on_error(err):
            log.error("{e!s}", e=err.value)
            log.error("Could not start node")
            if reactor.running:
                reactor.stop()
        d.addErrback(on_error)

    reactor.callWhenRunning(start_crossbar)

    # enter event loop
    #
    try:
        reactor.run()
    except Exception:
        log.failure("Could not start reactor - {log_failure.value}")