示例#1
0
 def test_version_command(self):
     actual_output = StringIO()
     with contextlib.redirect_stdout(actual_output):
         main(['version'])
     self.assertEqual(
         actual_output.getvalue().strip(),
         json.dumps(get_platform(get_ip=False), sort_keys=True, indent=2))
示例#2
0
 def test_version_command(self):
     actual_output = StringIO()
     with contextlib.redirect_stdout(actual_output):
         main(['version'])
     self.assertEqual(
         actual_output.getvalue().strip(),
         "lbrynet {lbrynet_version}".format(**get_platform(get_ip=False)))
示例#3
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")
示例#4
0
def main(argv=None):
    argv = argv or sys.argv[1:]
    if not argv:
        print_help()
        return 1

    conf_path = None
    if len(argv) and argv[0] == "--conf":
        if len(argv) < 2:
            print("No config file specified for --conf option")
            print_help()
            return 1

        conf_path = argv[1]
        argv = argv[2:]

    method, args = argv[0], argv[1:]

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

    elif method in ['version', '--version', '-v']:
        print("{lbrynet_name} {lbrynet_version}".format(
            lbrynet_name=lbrynet_name, **get_platform(get_ip=False)))
        return 0

    elif method == 'start':
        sys.exit(daemon_main(args, conf_path))

    elif method == 'console':
        sys.exit(daemon_console())

    elif method not in Daemon.callable_methods:
        if method not in Daemon.deprecated_methods:
            print('{} is not a valid command.'.format(method))
            return 1

        new_method = Daemon.deprecated_methods[method].new_command
        if new_method is None:
            print(
                "{} is permanently deprecated and does not have a replacement command."
                .format(method))
            return 0

        print("{} is deprecated, using {}.".format(method, new_method))
        method = new_method

    fn = Daemon.callable_methods[method]
    parsed = docopt(fn.__doc__, args)
    params = set_kwargs(parsed)
    loop = asyncio.get_event_loop()
    loop.run_until_complete(execute_command(method, params, conf_path))

    return 0
示例#5
0
文件: manager.py 项目: lbryio/lbry
 def new_instance(cls, api=None, events=None):
     if api is None:
         api = Api.new_instance()
     if events is None:
         events = Events(
             make_context(get_platform(), settings.wallet),
             'not loaded', 'not loaded'
         )
     return cls(api, events, Track())
示例#6
0
 def __init__(self, analytics_api, context=None, installation_id=None, session_id=None):
     self.analytics_api = analytics_api
     self._tracked_data = collections.defaultdict(list)
     self.looping_call_manager = self._setup_looping_calls()
     self.context = context or self._make_context(
         system_info.get_platform(), conf.settings['wallet'])
     self.installation_id = installation_id or conf.settings.installation_id
     self.session_id = session_id or conf.settings.get_session_id()
     self.is_started = False
示例#7
0
 def __init__(self, analytics_api, context=None, installation_id=None, session_id=None):
     self.analytics_api = analytics_api  # 本模块Api类实例: 用于用户数据分析(segment.io)和共享统计信息和诊断信息
     self._tracked_data = collections.defaultdict(list)  # 默认值为list的字典
     self.looping_call_manager = self._setup_looping_calls()  # 循环调用管理类(属性calls(字典),保存了 调用名称:调用方法)
     self.context = context or self._make_context(  # 版本信息上下文(系统版本, lbryum版本等等)
         system_info.get_platform(), conf.settings['wallet'])
     self.installation_id = installation_id or conf.settings.installation_id
     self.session_id = session_id or conf.settings.get_session_id()
     self.is_started = False
示例#8
0
 def __init__(self, analytics_api, context=None, installation_id=None, session_id=None):
     self.analytics_api = analytics_api
     self._tracked_data = collections.defaultdict(list)
     self.looping_call_manager = self._setup_looping_calls()
     self.context = context or self._make_context(
         system_info.get_platform(), conf.settings['wallet'])
     self.installation_id = installation_id or conf.settings.installation_id
     self.session_id = session_id or conf.settings.get_session_id()
     self.is_started = False
示例#9
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")
示例#10
0
 def new_instance(cls, api=None, events=None):
     if api is None:
         api = Api.new_instance()
     if events is None:
         events = Events(
             make_context(get_platform(), conf.settings['wallet']),
             base58.b58encode(conf.settings.get_lbry_id()),
             conf.settings.get_session_id(),
         )
     return cls(api, events, Track())
示例#11
0
 def new_instance(cls, api=None, events=None):
     if api is None:
         api = Api.new_instance()
     if events is None:
         events = Events(
             make_context(get_platform(), conf.settings['wallet']),
             conf.settings.installation_id,
             conf.settings.get_session_id(),
         )
     return cls(api, events, Track())
示例#12
0
def main(argv=None):
    argv = argv or sys.argv[1:]
    if not argv:
        print_help()
        return 1

    conf_path = None
    if len(argv) and argv[0] == "--conf":
        if len(argv) < 2:
            print("No config file specified for --conf option")
            print_help()
            return 1

        conf_path = argv[1]
        argv = argv[2:]

    method, args = argv[0], argv[1:]

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

    elif method in ['version', '--version', '-v']:
        print(
            json.dumps(get_platform(get_ip=False),
                       sort_keys=True,
                       indent=2,
                       separators=(',', ': ')))
        return 0

    elif method == 'start':
        sys.exit(daemon_main(args, conf_path))

    elif method == 'console':
        sys.exit(daemon_console())

    elif method not in Daemon.callable_methods:
        if method not in Daemon.deprecated_methods:
            print('{} is not a valid command.'.format(method))
            return 1
        new_method = Daemon.deprecated_methods[method].new_command
        print("{} is deprecated, using {}.".format(method, new_method))
        method = new_method

    fn = Daemon.callable_methods[method]
    parsed = docopt(fn.__doc__, args)
    params = set_kwargs(parsed)
    loop = asyncio.get_event_loop()
    loop.run_until_complete(execute_command(method, params, conf_path))

    return 0
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")
示例#14
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")
示例#15
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
示例#16
0
 def get_external_ip():
     from lbrynet.core.system_info import get_platform
     platform = get_platform(get_ip=True)
     return platform['ip']
示例#17
0
文件: DaemonCLI.py 项目: nasht12/lbry
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
示例#18
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
示例#19
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")