Пример #1
0
def start():
    """The primary entry point for launching the daemon."""
    conf.initialize_settings()

    parser = argparse.ArgumentParser(description="Launch lbrynet-daemon")
    parser.add_argument(
        "--wallet",
        help="lbryum or ptc for testing, default lbryum",
        type=str,
        default=conf.settings['wallet']
    )
    parser.add_argument(
        "--http-auth", dest="useauth", action="store_true", default=conf.settings['use_auth_http']
    )
    parser.add_argument(
        '--quiet', dest='quiet', action="store_true",
        help='Disable all console output.'
    )
    parser.add_argument(
        '--verbose', nargs="*",
        help=('Enable debug output. Optionally specify loggers for which debug output '
              'should selectively be applied.')
    )
    parser.add_argument(
        '--version', action="store_true",
        help='Show daemon version and quit'
    )

    args = parser.parse_args()
    update_settings_from_args(args)  # 将use_auth_http(useauth)和wallet的值更新到配置类Config的self._data['cli']中

    if args.version:
        version = system_info.get_platform(get_ip=False)
        version['installation_id'] = conf.settings.installation_id
        print utils.json_dumps_pretty(version)
        return

    lbrynet_log = conf.settings.get_log_filename()
    log_support.configure_logging(lbrynet_log, not args.quiet, args.verbose)  # 日志相关
    log.debug('Final Settings: %s', conf.settings.get_current_settings_dict())

    try:
        log.debug('Checking for an existing lbrynet daemon instance')
        # 用于检查是否有lbrynet-daemon的服务开启
        JSONRPCProxy.from_url(conf.settings.get_api_connection_string()).status()
        log.info("lbrynet-daemon is already running")
        return
    except Exception:
        log.debug('No lbrynet instance found, continuing to start')

    log.info("Starting lbrynet-daemon from command line")

    # 检查是否能够连接到internet
    # (默认是以socket方式连接到lbry.io官网,可以改为国内网站,如baidu.com,如果成功则返回True)
    if test_internet_connection():
        analytics_manager = analytics.Manager.new_instance()  # 各种配置信息的初始化以及配置第三方的数据分析
        start_server_and_listen(args.useauth, analytics_manager)
        reactor.run()  # 事件循环管理器,单例reactor(异步回调也是事件触发)
    else:
        log.info("Not connected to internet, unable to start")
Пример #2
0
def start():
    conf.initialize_settings()

    parser = argparse.ArgumentParser(description="Launch lbrynet-daemon")
    parser.add_argument(
        "--wallet",
        help="lbryum or ptc for testing, default lbryum",
        type=str,
        default=conf.settings['wallet']
    )
    parser.add_argument(
        "--http-auth", dest="useauth", action="store_true", default=conf.settings['use_auth_http']
    )
    parser.add_argument(
        '--quiet', dest='quiet', action="store_true",
        help='Disable all console output.'
    )
    parser.add_argument(
        '--verbose', nargs="*",
        help=('Enable debug output. Optionally specify loggers for which debug output '
              'should selectively be applied.')
    )
    parser.add_argument(
        '--version', action="store_true",
        help='Show daemon version and quit'
    )

    args = parser.parse_args()
    update_settings_from_args(args)

    if args.version:
        version = system_info.get_platform(get_ip=False)
        version['installation_id'] = conf.settings.installation_id
        print utils.json_dumps_pretty(version)
        return

    lbrynet_log = conf.settings.get_log_filename()
    log_support.configure_logging(lbrynet_log, not args.quiet, args.verbose)
    log.debug('Final Settings: %s', conf.settings.get_current_settings_dict())

    try:
        log.debug('Checking for an existing lbrynet daemon instance')
        JSONRPCProxy.from_url(conf.settings.get_api_connection_string()).status()
        log.info("lbrynet-daemon is already running")
        return
    except Exception:
        log.debug('No lbrynet instance found, continuing to start')

    log.info("Starting lbrynet-daemon from command line")

    if test_internet_connection():
        analytics_manager = analytics.Manager.new_instance()
        start_server_and_listen(args.useauth, analytics_manager)
        reactor.run()
    else:
        log.info("Not connected to internet, unable to start")
def start(argv=None, conf_path=None):
    if conf_path is not None:
        conf.conf_file = conf_path

    conf.initialize_settings()

    parser = argparse.ArgumentParser()
    parser.add_argument("--http-auth",
                        dest="useauth",
                        action="store_true",
                        default=conf.settings['use_auth_http'])
    parser.add_argument('--quiet',
                        dest='quiet',
                        action="store_true",
                        help='Disable all console output.')
    parser.add_argument(
        '--verbose',
        nargs="*",
        help=
        ('Enable debug output. Optionally specify loggers for which debug output '
         'should selectively be applied.'))
    parser.add_argument('--version',
                        action="store_true",
                        help='Show daemon version and quit')

    args = parser.parse_args(argv)
    if args.useauth:
        conf.settings.update({'use_auth_http': args.useauth},
                             data_types=(conf.TYPE_CLI, ))

    if args.version:
        version = system_info.get_platform(get_ip=False)
        version['installation_id'] = conf.settings.installation_id
        print(utils.json_dumps_pretty(version))
        return

    lbrynet_log = conf.settings.get_log_filename()
    log_support.configure_logging(lbrynet_log, not args.quiet, args.verbose)
    log_support.configure_loggly_handler()
    log.debug('Final Settings: %s', conf.settings.get_current_settings_dict())

    log.info("Starting lbrynet-daemon from command line")

    if test_internet_connection():
        daemon = Daemon()
        daemon.start_listening()
        reactor.run()
    else:
        log.info("Not connected to internet, unable to start")
Пример #4
0
def main():
    if len(sys.argv[1:]):
        method, args = sys.argv[1], sys.argv[2:]
    else:
        print_help()
        return

    if method in ['help', '--help', '-h']:
        if len(args) == 1:
            print_help_for_command(args[0])
        else:
            print_help()
        return

    if method not in Daemon.callable_methods:
        print_error("\"%s\" is not a valid command." % method)
        return

    fn = Daemon.callable_methods[method]
    if hasattr(fn, "_flags"):
        flag_names = fn._flags
    else:
        flag_names = {}

    parsed = docopt(fn.__doc__, args)
    kwargs = set_flag_vals(flag_names, parsed)
    colorama.init()
    conf.initialize_settings()
    api = LBRYAPIClient.get_client()

    try:
        status = api.status()
    except URLError as err:
        if isinstance(err, HTTPError) and err.code == UNAUTHORIZED:
            print_error(
                "Daemon requires authentication, but none was provided.",
                suggest_help=False)
        else:
            print_error(
                "Could not connect to daemon. Are you sure it's running?",
                suggest_help=False)
        return 1

    if status['startup_status']['code'] != "started":
        print "Daemon is in the process of starting. Please try again in a bit."
        message = status['startup_status']['message']
        if message:
            if (status['startup_status']['code'] == LOADING_WALLET_CODE
                    and status['blockchain_status']['blocks_behind'] > 0):
                message += '. Blocks left: ' + str(
                    status['blockchain_status']['blocks_behind'])
            print "  Status: " + message
        return 1

    # TODO: check if port is bound. Error if its not

    try:
        result = api.call(method, **kwargs)
        if isinstance(result, basestring):
            # printing the undumped string is prettier
            print result
        else:
            print utils.json_dumps_pretty(result)
    except (RPCError, KeyError, JSONRPCException, HTTPError) as err:
        error_data = None
        if isinstance(err, HTTPError):
            error_body = err.read()
            try:
                error_data = json.loads(error_body)
            except ValueError:
                print(
                    "There was an error, and the response was not valid JSON.\n"
                    + "Raw JSONRPC response:\n" + error_body)
                return 1

            print_error(error_data['error']['message'] + "\n",
                        suggest_help=False)
        else:
            print_error("Something went wrong\n", suggest_help=False)

        print_help_for_command(method)

        if 'data' in error_data['error'] and 'traceback' in error_data[
                'error']['data']:
            print "Here's the traceback for the error you encountered:"
            print "\n".join(error_data['error']['data']['traceback'])
        return 1
Пример #5
0
def main():
    argv = sys.argv[1:]

    # check if a config file has been specified. If so, shift
    # all the arguments so that the parsing can continue without
    # noticing
    if len(argv) and argv[0] == "--conf":
        if len(argv) < 2:
            print_error("No config file specified for --conf option")
            print_help()
            return

        conf.conf_file = argv[1]
        argv = argv[2:]

    if len(argv):
        method, args = argv[0], argv[1:]
    else:
        print_help()
        return

    if method in ['help', '--help', '-h']:
        if len(args) == 1:
            print_help_for_command(args[0])
        else:
            print_help()
        return

    elif method in ['version', '--version']:
        print utils.json_dumps_pretty(get_platform(get_ip=False))
        return

    if method not in Daemon.callable_methods:
        if method not in Daemon.deprecated_methods:
            print_error("\"%s\" is not a valid command." % method)
            return
        new_method = Daemon.deprecated_methods[method]._new_command
        print_error("\"%s\" is deprecated, using \"%s\"." % (method, new_method))
        method = new_method

    fn = Daemon.callable_methods[method]

    parsed = docopt(fn.__doc__, args)
    kwargs = set_kwargs(parsed)
    colorama.init()
    conf.initialize_settings()

    try:
        api = LBRYAPIClient.get_client()
        api.status()
    except (URLError, ConnectionError) as err:
        if isinstance(err, HTTPError) and err.code == UNAUTHORIZED:
            api = AuthAPIClient.config()
            # this can happen if the daemon is using auth with the --http-auth flag
            # when the config setting is to not use it
            try:
                api.status()
            except:
                print_error("Daemon requires authentication, but none was provided.",
                            suggest_help=False)
                return 1
        else:
            print_error("Could not connect to daemon. Are you sure it's running?",
                        suggest_help=False)
            return 1

    # TODO: check if port is bound. Error if its not

    try:
        result = api.call(method, kwargs)
        if isinstance(result, basestring):
            # printing the undumped string is prettier
            print result
        else:
            print utils.json_dumps_pretty(result)
    except (RPCError, KeyError, JSONRPCException, HTTPError) as err:
        if isinstance(err, HTTPError):
            error_body = err.read()
            try:
                error_data = json.loads(error_body)
            except ValueError:
                print (
                    "There was an error, and the response was not valid JSON.\n" +
                    "Raw JSONRPC response:\n" + error_body
                )
                return 1

            print_error(error_data['error']['message'] + "\n", suggest_help=False)

            if 'data' in error_data['error'] and 'traceback' in error_data['error']['data']:
                print "Here's the traceback for the error you encountered:"
                print "\n".join(error_data['error']['data']['traceback'])

            print_help_for_command(method)
        elif isinstance(err, RPCError):
            print_error(err.msg, suggest_help=False)
            # print_help_for_command(method)
        else:
            print_error("Something went wrong\n", suggest_help=False)
            print str(err)

        return 1
Пример #6
0
def main():
    parser = argparse.ArgumentParser(add_help=False)
    _, arguments = parser.parse_known_args()

    conf.initialize_settings()
    api = LBRYAPIClient.get_client()

    try:
        status = api.status()
    except URLError as err:
        if isinstance(err, HTTPError) and err.code == UNAUTHORIZED:
            print_error(
                "Daemon requires authentication, but none was provided.",
                suggest_help=False)
        else:
            print_error(
                "Could not connect to daemon. Are you sure it's running?",
                suggest_help=False)
        return 1

    if status['startup_status']['code'] != "started":
        print "Daemon is in the process of starting. Please try again in a bit."
        message = status['startup_status']['message']
        if message:
            if (status['startup_status']['code'] == LOADING_WALLET_CODE
                    and status['blockchain_status']['blocks_behind'] > 0):
                message += '. Blocks left: ' + str(
                    status['blockchain_status']['blocks_behind'])
            print "  Status: " + message
        return 1

    if len(arguments) < 1:
        print_help(api)
        return 1

    method = arguments[0]
    try:
        params = parse_params(arguments[1:])
    except InvalidParameters as e:
        print_error(e.message)
        return 1

    # TODO: check if port is bound. Error if its not

    if method in ['--help', '-h', 'help']:
        if len(params) == 0:
            print_help(api)
        elif 'command' not in params:
            print_error(
                'To get help on a specific command, use `{} help command=COMMAND_NAME`'
                .format(os.path.basename(sys.argv[0])))
        else:
            print_help_response(api.call('help', params))

    elif method not in api.commands():
        print_error("'" + method + "' is not a valid command.")

    else:
        try:
            result = api.call(method, params)
            if isinstance(result, basestring):
                # printing the undumped string is prettier
                print result
            else:
                print utils.json_dumps_pretty(result)
        except (RPCError, KeyError, JSONRPCException) as err:
            # TODO: The api should return proper error codes
            # and messages so that they can be passed along to the user
            # instead of this generic message.
            # https://app.asana.com/0/158602294500137/200173944358192
            print "Something went wrong, here's the usage for %s:" % method
            print_help_response(api.call('help', {'command': method}))
            if hasattr(err, 'msg'):
                print "Here's the traceback for the error you encountered:"
                print err.msg
            return 1
Пример #7
0
def main():
    colorama.init()
    parser = argparse.ArgumentParser(add_help=False)
    _, arguments = parser.parse_known_args()

    conf.initialize_settings()
    api = LBRYAPIClient.get_client()

    try:
        status = api.status()
    except URLError as err:
        if isinstance(err, HTTPError) and err.code == UNAUTHORIZED:
            print_error("Daemon requires authentication, but none was provided.",
                        suggest_help=False)
        else:
            print_error("Could not connect to daemon. Are you sure it's running?",
                        suggest_help=False)
        return 1

    if status['startup_status']['code'] != "started":
        print "Daemon is in the process of starting. Please try again in a bit."
        message = status['startup_status']['message']
        if message:
            if (
                status['startup_status']['code'] == LOADING_WALLET_CODE
                and status['blockchain_status']['blocks_behind'] > 0
            ):
                message += '. Blocks left: ' + str(status['blockchain_status']['blocks_behind'])
            print "  Status: " + message
        return 1

    if len(arguments) < 1:
        print_help(api)
        return 1

    method = arguments[0]
    try:
        params = parse_params(arguments[1:])
    except InvalidParameters as e:
        print_error(e.message)
        return 1

    # TODO: check if port is bound. Error if its not

    if method in ['--help', '-h', 'help']:
        if len(params) == 0:
            print_help(api)
        elif 'command' not in params:
            print_error(
                'To get help on a specific command, use `{} help command=COMMAND_NAME`'.format(
                    os.path.basename(sys.argv[0]))
            )
        else:
            print_help_for_command(api, params['command'])

    elif method not in api.commands():
        print_error("'" + method + "' is not a valid command.")

    else:
        try:
            result = api.call(method, params)
            if isinstance(result, basestring):
                # printing the undumped string is prettier
                print result
            else:
                print utils.json_dumps_pretty(result)
        except (RPCError, KeyError, JSONRPCException, HTTPError) as err:
            error_data = None
            if isinstance(err, HTTPError):
                error_body = err.read()
                try:
                    error_data = json.loads(error_body)
                except ValueError:
                    print (
                        "There was an error, and the response was not valid JSON.\n" +
                        "Raw JSONRPC response:\n" + error_body
                    )
                    return 1

                print_error(error_data['error']['message'] + "\n", suggest_help=False)
            else:
                print_error("Something went wrong\n", suggest_help=False)

            print_help_for_command(api, method)
            if 'data' in error_data['error'] and 'traceback' in error_data['error']['data']:
                print "Here's the traceback for the error you encountered:"
                print "\n".join(error_data['error']['data']['traceback'])
            return 1
Пример #8
0
def start():
    """The primary entry point for launching the daemon."""

    # postpone loading the config file to after the CLI arguments
    # have been parsed, as they may contain an alternate config file location
    conf.initialize_settings(load_conf_file=False)

    parser = argparse.ArgumentParser(description="Launch lbrynet-daemon")
    parser.add_argument("--conf",
                        help="specify an alternative configuration file",
                        type=str,
                        default=None)
    parser.add_argument("--http-auth",
                        dest="useauth",
                        action="store_true",
                        default=conf.settings['use_auth_http'])
    parser.add_argument('--quiet',
                        dest='quiet',
                        action="store_true",
                        help='Disable all console output.')
    parser.add_argument(
        '--verbose',
        nargs="*",
        help=
        ('Enable debug output. Optionally specify loggers for which debug output '
         'should selectively be applied.'))
    parser.add_argument('--version',
                        action="store_true",
                        help='Show daemon version and quit')

    args = parser.parse_args()
    update_settings_from_args(args)

    conf.settings.load_conf_file_settings()

    if args.version:
        version = system_info.get_platform(get_ip=False)
        version['installation_id'] = conf.settings.installation_id
        print utils.json_dumps_pretty(version)
        return

    lbrynet_log = conf.settings.get_log_filename()
    log_support.configure_logging(lbrynet_log, not args.quiet, args.verbose)
    log_support.configure_loggly_handler()
    log.debug('Final Settings: %s', conf.settings.get_current_settings_dict())

    try:
        log.debug('Checking for an existing lbrynet daemon instance')
        JSONRPCProxy.from_url(
            conf.settings.get_api_connection_string()).status()
        log.info("lbrynet-daemon is already running")
        return
    except Exception:
        log.debug('No lbrynet instance found, continuing to start')

    log.info("Starting lbrynet-daemon from command line")

    if test_internet_connection():
        daemon = Daemon()
        daemon.start_listening()
        reactor.run()
    else:
        log.info("Not connected to internet, unable to start")
Пример #9
0
def main():
    if len(sys.argv[1:]):
        method, args = sys.argv[1], sys.argv[2:]
    else:
        print_help()
        return

    if method in ['help', '--help', '-h']:
        if len(args) == 1:
            print_help_for_command(args[0])
        else:
            print_help()
        return

    elif method in ['version', '--version']:
        print utils.json_dumps_pretty(get_platform(get_ip=False))
        return

    if method not in Daemon.callable_methods:
        if method not in Daemon.deprecated_methods:
            print_error("\"%s\" is not a valid command." % method)
            return
        new_method = Daemon.deprecated_methods[method]._new_command
        print_error("\"%s\" is deprecated, using \"%s\"." % (method, new_method))
        method = new_method

    fn = Daemon.callable_methods[method]
    if hasattr(fn, "_flags"):
        flag_names = fn._flags
    else:
        flag_names = {}

    parsed = docopt(fn.__doc__, args)
    kwargs = set_flag_vals(flag_names, parsed)
    colorama.init()
    conf.initialize_settings()
    api = LBRYAPIClient.get_client()

    try:
        status = api.status()
    except URLError as err:
        if isinstance(err, HTTPError) and err.code == UNAUTHORIZED:
            print_error("Daemon requires authentication, but none was provided.",
                        suggest_help=False)
        else:
            print_error("Could not connect to daemon. Are you sure it's running?",
                        suggest_help=False)
        return 1

    status_code = status['startup_status']['code']

    if status_code != "started" and method not in Daemon.allowed_during_startup:
        print "Daemon is in the process of starting. Please try again in a bit."
        message = status['startup_status']['message']
        if message:
            if (
                status['startup_status']['code'] == LOADING_WALLET_CODE
                and status['blockchain_status']['blocks_behind'] > 0
            ):
                message += '. Blocks left: ' + str(status['blockchain_status']['blocks_behind'])
            print "  Status: " + message
        return 1

    # TODO: check if port is bound. Error if its not

    try:
        result = api.call(method, **kwargs)
        if isinstance(result, basestring):
            # printing the undumped string is prettier
            print result
        else:
            print utils.json_dumps_pretty(result)
    except (RPCError, KeyError, JSONRPCException, HTTPError) as err:
        if isinstance(err, HTTPError):
            error_body = err.read()
            try:
                error_data = json.loads(error_body)
            except ValueError:
                print (
                    "There was an error, and the response was not valid JSON.\n" +
                    "Raw JSONRPC response:\n" + error_body
                )
                return 1

            print_error(error_data['error']['message'] + "\n", suggest_help=False)

            if 'data' in error_data['error'] and 'traceback' in error_data['error']['data']:
                print "Here's the traceback for the error you encountered:"
                print "\n".join(error_data['error']['data']['traceback'])

            print_help_for_command(method)
        elif isinstance(err, RPCError):
            print_error(err.msg, suggest_help=False)
            # print_help_for_command(method)
        else:
            print_error("Something went wrong\n", suggest_help=False)
            print str(err)

        return 1
Пример #10
0
def main():
    argv = sys.argv[1:]

    # check if a config file has been specified. If so, shift
    # all the arguments so that the parsing can continue without
    # noticing
    if len(argv) and argv[0] == "--conf":
        if len(argv) < 2:
            print_error("No config file specified for --conf option")
            print_help()
            return

        conf.conf_file = argv[1]
        argv = argv[2:]

    if len(argv):
        method, args = argv[0], argv[1:]
    else:
        print_help()
        return

    if method in ['help', '--help', '-h']:
        if len(args) == 1:
            print_help_for_command(args[0])
        else:
            print_help()
        return

    elif method in ['version', '--version']:
        print utils.json_dumps_pretty(get_platform(get_ip=False))
        return

    if method not in Daemon.callable_methods:
        if method not in Daemon.deprecated_methods:
            print_error("\"%s\" is not a valid command." % method)
            return
        new_method = Daemon.deprecated_methods[method]._new_command
        print_error("\"%s\" is deprecated, using \"%s\"." %
                    (method, new_method))
        method = new_method

    fn = Daemon.callable_methods[method]
    if hasattr(fn, "_flags"):
        flag_names = fn._flags
    else:
        flag_names = {}

    parsed = docopt(fn.__doc__, args)
    kwargs = set_flag_vals(flag_names, parsed)
    colorama.init()
    conf.initialize_settings()
    api = LBRYAPIClient.get_client()

    try:
        status = api.status()
    except URLError as err:
        if isinstance(err, HTTPError) and err.code == UNAUTHORIZED:
            print_error(
                "Daemon requires authentication, but none was provided.",
                suggest_help=False)
        else:
            print_error(
                "Could not connect to daemon. Are you sure it's running?",
                suggest_help=False)
        return 1

    status_code = status['startup_status']['code']

    if status_code != "started" and method not in Daemon.allowed_during_startup:
        print "Daemon is in the process of starting. Please try again in a bit."
        message = status['startup_status']['message']
        if message:
            if (status['startup_status']['code'] == LOADING_WALLET_CODE
                    and status['blockchain_status']['blocks_behind'] > 0):
                message += '. Blocks left: ' + str(
                    status['blockchain_status']['blocks_behind'])
            print "  Status: " + message
        return 1

    # TODO: check if port is bound. Error if its not

    try:
        result = api.call(method, **kwargs)
        if isinstance(result, basestring):
            # printing the undumped string is prettier
            print result
        else:
            print utils.json_dumps_pretty(result)
    except (RPCError, KeyError, JSONRPCException, HTTPError) as err:
        if isinstance(err, HTTPError):
            error_body = err.read()
            try:
                error_data = json.loads(error_body)
            except ValueError:
                print(
                    "There was an error, and the response was not valid JSON.\n"
                    + "Raw JSONRPC response:\n" + error_body)
                return 1

            print_error(error_data['error']['message'] + "\n",
                        suggest_help=False)

            if 'data' in error_data['error'] and 'traceback' in error_data[
                    'error']['data']:
                print "Here's the traceback for the error you encountered:"
                print "\n".join(error_data['error']['data']['traceback'])

            print_help_for_command(method)
        elif isinstance(err, RPCError):
            print_error(err.msg, suggest_help=False)
            # print_help_for_command(method)
        else:
            print_error("Something went wrong\n", suggest_help=False)
            print str(err)

        return 1
Пример #11
0
def start():
    """The primary entry point for launching the daemon."""

    # postpone loading the config file to after the CLI arguments
    # have been parsed, as they may contain an alternate config file location
    conf.initialize_settings(load_conf_file=False)

    parser = argparse.ArgumentParser(description="Launch lbrynet-daemon")
    parser.add_argument(
        "--conf",
        help="specify an alternative configuration file",
        type=str,
        default=None
    )
    parser.add_argument(
        "--wallet",
        help="lbryum or ptc for testing, default lbryum",
        type=str,
        default=conf.settings['wallet']
    )
    parser.add_argument(
        "--http-auth", dest="useauth", action="store_true", default=conf.settings['use_auth_http']
    )
    parser.add_argument(
        '--quiet', dest='quiet', action="store_true",
        help='Disable all console output.'
    )
    parser.add_argument(
        '--verbose', nargs="*",
        help=('Enable debug output. Optionally specify loggers for which debug output '
              'should selectively be applied.')
    )
    parser.add_argument(
        '--version', action="store_true",
        help='Show daemon version and quit'
    )

    args = parser.parse_args()
    update_settings_from_args(args)

    conf.settings.load_conf_file_settings()

    if args.version:
        version = system_info.get_platform(get_ip=False)
        version['installation_id'] = conf.settings.installation_id
        print utils.json_dumps_pretty(version)
        return

    lbrynet_log = conf.settings.get_log_filename()
    log_support.configure_logging(lbrynet_log, not args.quiet, args.verbose)
    log.debug('Final Settings: %s', conf.settings.get_current_settings_dict())

    try:
        log.debug('Checking for an existing lbrynet daemon instance')
        JSONRPCProxy.from_url(conf.settings.get_api_connection_string()).status()
        log.info("lbrynet-daemon is already running")
        return
    except Exception:
        log.debug('No lbrynet instance found, continuing to start')

    log.info("Starting lbrynet-daemon from command line")

    if test_internet_connection():
        analytics_manager = analytics.Manager.new_instance()
        start_server_and_listen(args.useauth, analytics_manager)
        reactor.run()
    else:
        log.info("Not connected to internet, unable to start")
Пример #12
0
def main():
    if len(sys.argv[1:]):
        method, args = sys.argv[1], sys.argv[2:]
    else:
        print_help()
        return

    if method in ['help', '--help', '-h']:
        if len(args) == 1:
            print_help_for_command(args[0])
        else:
            print_help()
        return

    elif method in ['version', '--version']:
        print utils.json_dumps_pretty(get_platform(get_ip=False))
        return

    if method not in Daemon.callable_methods:
        if method not in Daemon.deprecated_methods:
            print_error("\"%s\" is not a valid command." % method)
            return
        new_method = Daemon.deprecated_methods[method]._new_command
        print_error("\"%s\" is deprecated, using \"%s\"." %
                    (method, new_method))
        method = new_method

    fn = Daemon.callable_methods[method]
    if hasattr(fn, "_flags"):
        flag_names = fn._flags
    else:
        flag_names = {}

    parsed = docopt(fn.__doc__,
                    args)  # 第二个参数argv表示docopt不去系统的sys.argv[1:]而使用传入的参数
    kwargs = set_flag_vals(flag_names, parsed)  # 取出有值的命令行参数(并且是排序的字典对象)
    colorama.init()  # 终端颜色
    # 将一些配置信息(conf.py中的固定的和可变的, 以及环境变量的和数据目录下配置文件的)设置为Config类的属性(_data属性)
    conf.initialize_settings()  # 将配置信息设置到conf.py中的Config类
    api = LBRYAPIClient.get_client()  # 根据配置中use_auth_http的值来决定api的类型

    try:
        # api是JSONRPCProxy对象
        # status是通过__getattr__来实现访问的
        # 把status作为JSONRPCProxy类的_serviceName属性,重新实例化JSONRPCProxy对象并访问rpc服务
        status = api.status()
    except URLError as err:
        if isinstance(err, HTTPError) and err.code == UNAUTHORIZED:
            print_error(
                "Daemon requires authentication, but none was provided.",
                suggest_help=False)
        else:
            print_error(
                "Could not connect to daemon. Are you sure it's running?",
                suggest_help=False)
        return 1

    status_code = status['startup_status']['code']

    if status_code != "started" and method not in Daemon.allowed_during_startup:
        print "Daemon is in the process of starting. Please try again in a bit."
        message = status['startup_status']['message']
        if message:
            if (status['startup_status']['code'] == LOADING_WALLET_CODE
                    and status['blockchain_status']['blocks_behind'] > 0):
                message += '. Blocks left: ' + str(
                    status['blockchain_status']['blocks_behind'])
            print "  Status: " + message
        return 1

    # TODO: check if port is bound. Error if its not

    try:
        result = api.call(method, **kwargs)
        if isinstance(result, basestring):
            # printing the undumped string is prettier
            print result
        else:
            print utils.json_dumps_pretty(result)
    except (RPCError, KeyError, JSONRPCException, HTTPError) as err:
        if isinstance(err, HTTPError):
            error_body = err.read()
            try:
                error_data = json.loads(error_body)
            except ValueError:
                print(
                    "There was an error, and the response was not valid JSON.\n"
                    + "Raw JSONRPC response:\n" + error_body)
                return 1

            print_error(error_data['error']['message'] + "\n",
                        suggest_help=False)

            if 'data' in error_data['error'] and 'traceback' in error_data[
                    'error']['data']:
                print "Here's the traceback for the error you encountered:"
                print "\n".join(error_data['error']['data']['traceback'])

            print_help_for_command(method)
        elif isinstance(err, RPCError):
            print_error(err.msg, suggest_help=True)
            # print_help_for_command(method)
        else:
            print_error("Something went wrong\n", suggest_help=False)
            print str(err)

        return 1