示例#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():
    parser = argparse.ArgumentParser(description="Launch lbrynet-daemon")
    parser.add_argument("--wallet", help="lbrycrd or lbryum, default lbryum", type=str, default="")
    parser.add_argument("--ui", help="path to custom UI folder", default=None)
    parser.add_argument("--branch", help="Branch of lbry-web-ui repo to use, defaults on master")
    parser.add_argument("--no-launch", dest="launchui", action="store_false")
    parser.add_argument("--log-to-console", dest="logtoconsole", action="store_true")
    parser.add_argument("--quiet", dest="quiet", action="store_true")
    parser.set_defaults(branch=False, launchui=True, logtoconsole=False, quiet=False)
    args = parser.parse_args()

    if args.logtoconsole:
        logging.basicConfig(level=logging.INFO)

    args = parser.parse_args()

    try:
        JSONRPCProxy.from_url(API_CONNECTION_STRING).is_running()
        log.info("lbrynet-daemon is already running")
        if not args.logtoconsole:
            print "lbrynet-daemon is already running"
        if args.launchui:
            webbrowser.open(UI_ADDRESS)
        return
    except:
        pass

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

    if not args.logtoconsole and not args.quiet:
        print "Starting lbrynet-daemon from command line"
        print "To view activity, view the log file here: " + lbrynet_log
        print "Web UI is available at http://%s:%i" % (API_INTERFACE, API_PORT)
        print "JSONRPC API is available at " + API_CONNECTION_STRING
        print "To quit press ctrl-c or call 'stop' via the API"

    if test_internet_connection():
        lbry = LBRYDaemonServer()

        d = lbry.start(
            branch=args.branch if args.branch else DEFAULT_UI_BRANCH,
            user_specified=args.ui,
            wallet=args.wallet,
            branch_specified=True if args.branch else False,
        )
        if args.launchui:
            d.addCallback(lambda _: webbrowser.open(UI_ADDRESS))

        reactor.listenTCP(API_PORT, server.Site(lbry.root), interface=API_INTERFACE)
        reactor.run()

        if not args.logtoconsole and not args.quiet:
            print "\nClosing lbrynet-daemon"
    else:
        log.info("Not connected to internet, unable to start")
        if not args.logtoconsole:
            print "Not connected to internet, unable to start"
        return
示例#3
0
def test():
    con = MySQLdb.connect(db='twit_manager', host="61.43.139.70",user='******', passwd='1rmdwjd', charset="UTF8")
    cur = con.cursor(cursorclass=MySQLdb.cursors.DictCursor)
    cur.execute("select * from tweet_data order by no desc limit 10000")

    qq2 = JSONRPCProxy("http://61.43.139.70:11001")
    for tt in cur.fetchall():
        print qq2.opn_classify(tt['tweet'])
        print tt['tweet']
示例#4
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")
示例#5
0
def start():
    utils.setup_certs_for_windows()
    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("--ui", help="path to custom UI folder", default=None)
    parser.add_argument(
        "--branch",
        help='Branch of lbry-web-ui repo to use, defaults to {}'.format(
            conf.settings['ui_branch']),
        default=conf.settings['ui_branch'])
    parser.add_argument('--launch-ui', dest='launchui', action="store_true")
    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.'))

    args = parser.parse_args()
    update_settings_from_args(args)

    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()).is_running()
        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.launchui, args.useauth, analytics_manager)
        reactor.run()
    else:
        log.info("Not connected to internet, unable to start")
示例#6
0
文件: client.py 项目: lbryio/lbry
 def config(service=None, params=None):
     if settings.use_auth_http:
         if service is None:
             return AuthAPIClient.config()
         log.error("Try auth")
         if params is not None:
             return AuthAPIClient.config(service=service)(params)
         return AuthAPIClient.config(service=service)()
     url = settings.API_CONNECTION_STRING
     if service is None:
         return JSONRPCProxy.from_url(url)
     return JSONRPCProxy.from_url(url).call(service, params)
示例#7
0
文件: client.py 项目: bitspill/lbry
 def config(service=None, params=None):
     if settings.use_auth_http:
         if service is None:
             return AuthAPIClient.config()
         log.error("Try auth")
         if params is not None:
             return AuthAPIClient.config(service=service)(params)
         return AuthAPIClient.config(service=service)()
     url = settings.API_CONNECTION_STRING
     if service is None:
         return JSONRPCProxy.from_url(url)
     return JSONRPCProxy.from_url(url).call(service, params)
示例#8
0
def start():
    utils.setup_certs_for_windows()
    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("--ui", help="path to custom UI folder", default=None)
    parser.add_argument(
        "--branch",
        help='Branch of lbry-web-ui repo to use, defaults to {}'.format(conf.settings['ui_branch']),
        default=conf.settings['ui_branch'])
    parser.add_argument('--launch-ui', dest='launchui', action="store_true")
    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.'))

    args = parser.parse_args()
    update_settings_from_args(args)

    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()).is_running()
        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.launchui, args.useauth, analytics_manager)
        reactor.run()
    else:
        log.info("Not connected to internet, unable to start")
示例#9
0
文件: keynes.py 项目: lbryio/keynes
    def __init__(self):
        print 'Starting up'
        self._api = JSONRPCProxy.from_url(API_CONNECTION_STRING)
        self._restricted_api_functions = ['stop_lbry_file', 'start_lbry_file', 'delete_lbry_file',
                                          'set_settings', 'publish', 'get', 'stop',
                                          'send_amount_to_address', 'abandon_name']

        self._api_functions = [f for f in self._api.help() if f not in self._restricted_api_functions]
        self._cb = cleverbot.Cleverbot()

        f = open('keynes.conf', 'r')
        self._slack_token = str(f.readline().replace('\n', ''))
        self._test_name = str(f.readline().replace('\n', ''))
        f.close()

        self.sc = SlackClient(self._slack_token)
        self.sc.rtm_connect()
        self._fetcher = Autofetcher()

        self.channels = {}
        self.users = {}
        self.message_queue = []

        self._slackrx = LoopingCall(self._get_messages)
        self._checker = LoopingCall(self._check_lbrynet)
示例#10
0
文件: client.py 项目: CAOLINAN/lbry
 def get_client():
     if not conf.settings:  # settings是Config类的实例, 在初始化时作为全局变量被赋值
         conf.initialize_settings()
         # JSONRPCProxy.from_url:实例化JSONRPCProxy,其中的一种方法
         # conf.settings.get_api_connection_string(): 组合配置中的host,port,address
     return AuthAPIClient.config() if conf.settings['use_auth_http'] else \
         JSONRPCProxy.from_url(conf.settings.get_api_connection_string())
 def __init__(self,rpc_url,db):
     generic.generic_scraper.__init__(self)
     self.db_exec = db.db_exec
     self.found_urls = []
     self.got_url = lambda url : url and self.found_urls.append(url)
     self.rpc = RPC.from_url(rpc_url)
     self.sleep = lambda: time.sleep(1)
示例#12
0
 def __init__(self):
     reactor.addSystemEventTrigger('before', 'shutdown', self.stop)
     self.api = JSONRPCProxy.from_url(API_CONNECTION_STRING)
     self.cache_dir = CACHE_DIR
     self.cache_file = os.path.join(self.cache_dir, "lighthouse.sqlite")
     self.cost_updater = LoopingCall(self._update_costs)
     self.exchange_rate_manager = ExchangeRateManager()
     self.show_status = LoopingCall(self._display_catchup_status)
     self.name_checker = LoopingCall(self._initialize_metadata)
     self.db = None
     self._is_running = False
     self._claims_to_check = []
     self.claimtrie = {}
     self._last_time = time.time()
     self.descriptors_to_download = []
     self._claims = {}
     self.metadata = {}
     self.size_cache = {}
     self.sd_attempts = {}
     self.stream_size = {}
     self.non_complying_claims = []
     self.bad_uris = []
     self._chain_height = 0
     self._blocks_to_go = False
     self.cost_and_availability = {
         n: {
             'cost': 0.0,
             'available': False
         }
         for n in self.metadata
     }
 def __init__(self, rpc_url, db):
     generic.generic_scraper.__init__(self)
     self.db_exec = db.db_exec
     self.found_urls = []
     self.got_url = lambda url: url and self.found_urls.append(url)
     self.rpc = RPC.from_url(rpc_url)
     self.sleep = lambda: time.sleep(1)
示例#14
0
def stop():
    ecu = JSONRPCProxy.from_url("http://localhost:50004")
    try:
        r = ecu.is_running()
        ecu.stop()
        print "lighthouse stopped"
    except:
        print "lighthouse wasn't running"
示例#15
0
def make_polar_train_data():
    server = JSONRPCProxy("http://office2.buzzni.com:10100")

    eng = ["animation", "baseball", "basketball", "book", "car", "childcare", "commercial", "economy", "entertainment",
           "fashion", "food", "game", "health", "infotech", "love", "movie", "pet", "science", "politics", "soccer", "travel", "volley", "world"]

    for x in eng:
        pros=[]
        cons=[]

        fp = open("/home/xorox90/tp/"+x, "r")
        fp2 = open("/home/xorox90/tp/polar/p_"+x, "a")
        fp3 = open("/home/xorox90/tp/polar/c_"+x, "a")

        for line in fp.read().split("\n"):
            idx=0
            while(True):
                try:
                    #print line
                    polarity = server.opn_classify(line)

                    if polarity==None or (polarity>2 and polarity <4):
                        break
                    elif(polarity <= 2):
                        cons.append(str(polarity) + " " +  line)
                    else:
                        pros.append(str(polarity) + " " + line)

                    break

                except Exception, err:
                    traceback.print_exc()
                    idx+=1
                    if(idx==3):
                        break



        print x
        for x in pros:
            fp2.write(x + "\n")

        for x in cons:
            fp3.writelines(x + "\n")
示例#16
0
def stop():
    def _disp_shutdown():
        log.info("Shutting down lbrynet-daemon from command line")

    def _disp_not_running():
        log.info("Attempt to shut down lbrynet-daemon from command line when daemon isn't running")

    d = defer.Deferred(None)
    d.addCallback(lambda _: JSONRPCProxy.from_url(API_CONNECTION_STRING).stop())
    d.addCallbacks(lambda _: _disp_shutdown(), lambda _: _disp_not_running())
    d.callback(None)
示例#17
0
def cli():
    ecu = JSONRPCProxy.from_url("http://localhost:50004")
    try:
        s = ecu.is_running()
    except:
        print "lighthouse isn't running"
        sys.exit(1)
    args = sys.argv[1:]
    meth = args[0]
    if args:
        print ecu.call(meth)
    else:
        print ecu.call(meth, args)
示例#18
0
def stop():
    def _disp_shutdown():
        print "Shutting down lbrynet-daemon from command line"
        log.info("Shutting down lbrynet-daemon from command line")

    def _disp_not_running():
        print "Attempt to shut down lbrynet-daemon from command line when daemon isn't running"
        log.info(
            "Attempt to shut down lbrynet-daemon from command line when daemon isn't running"
        )

    d = defer.Deferred(None)
    d.addCallback(
        lambda _: JSONRPCProxy.from_url(API_CONNECTION_STRING).stop())
    d.addCallbacks(lambda _: _disp_shutdown(), lambda _: _disp_not_running())
    d.callback(None)
示例#19
0
文件: DaemonCLI.py 项目: DaveA50/lbry
def main():
    api = JSONRPCProxy.from_url(API_CONNECTION_STRING)

    try:
        s = api.is_running()
    except:
        print "lbrynet-daemon isn't running"
        sys.exit(1)

    parser = argparse.ArgumentParser()
    parser.add_argument('method', nargs=1)
    parser.add_argument('params', nargs=argparse.REMAINDER, default=None)
    args = parser.parse_args()

    meth = args.method[0]
    params = {}

    if args.params:
        if len(args.params) > 1:
            params = get_params_from_kwargs(args.params)
        elif len(args.params) == 1:
            try:
                params = json.loads(args.params[0])
            except ValueError:
                params = get_params_from_kwargs(args.params)

    msg = help_msg
    for f in api.help():
        msg += f + "\n"

    if meth in ['--help', '-h', 'help']:
        print msg
        sys.exit(1)

    if meth in api.help():
        try:
            if params:
                r = api.call(meth, params)
            else:
                r = api.call(meth)
            print json.dumps(r, sort_keys=True)
        except:
            print "Something went wrong, here's the usage for %s:" % meth
            print api.help({'function': meth})
    else:
        print "Unknown function"
        print msg
示例#20
0
def main():
    api = JSONRPCProxy.from_url(API_CONNECTION_STRING)

    try:
        s = api.is_running()
    except:
        print "lbrynet-daemon isn't running"
        sys.exit(1)

    parser = argparse.ArgumentParser()
    parser.add_argument('method', nargs=1)
    parser.add_argument('params', nargs=argparse.REMAINDER, default=None)
    args = parser.parse_args()

    meth = args.method[0]
    params = {}

    if args.params:
        if len(args.params) > 1:
            params = get_params_from_kwargs(args.params)
        elif len(args.params) == 1:
            try:
                params = json.loads(args.params[0])
            except ValueError:
                params = get_params_from_kwargs(args.params)

    msg = help_msg
    for f in api.help():
        msg += f + "\n"

    if meth in ['--help', '-h', 'help']:
        print msg
        sys.exit(1)

    if meth in api.help():
        try:
            if params:
                r = api.call(meth, params)
            else:
                r = api.call(meth)
            print json.dumps(r, sort_keys=True)
        except:
            print "Something went wrong, here's the usage for %s:" % meth
            print api.help({'function': meth})
    else:
        print "Unknown function"
        print msg
示例#21
0
    def __init__(self):
        reactor.addSystemEventTrigger('before', 'shutdown', self.stop)
        self.api = JSONRPCProxy.from_url(API_CONNECTION_STRING)
        self.cache_file = os.path.join(os.path.expanduser("~/"), ".lighthouse_cache")
        self.claimtrie_updater = LoopingCall(self._update_claimtrie)

        if os.path.isfile(self.cache_file):
            log.info("Loading cache")
            f = open(self.cache_file, "r")
            r = json.loads(f.read())
            f.close()
            self.claimtrie, self.metadata, self.bad_uris= r['claimtrie'], r['metadata'], r['bad_uris']
        else:
            log.info("Rebuilding metadata cache")
            self.claimtrie = []
            self.metadata = {}
            self.bad_uris = []
示例#22
0
def main():
    api = JSONRPCProxy.from_url(API_CONNECTION_STRING)

    try:
        s = api.is_running()
    except:
        print "lbrynet-daemon isn't running"
        sys.exit(1)

    args = sys.argv[1:]
    meth = args[0]

    msg = help_msg
    for f in api.help():
        msg += f + "\n"

    if meth in ['--help', '-h', 'help']:
        print msg
        sys.exit(1)

    if len(args) > 1:
        if isinstance(args[1], dict):
            params = args[1]
        elif isinstance(args[1], basestring):
            params = json.loads(args[1])
    else:
        params = None

    if meth in api.help():
        try:
            if params:
                r = api.call(meth, params)
            else:
                r = api.call(meth)
            print r
        except:
            print "Something went wrong, here's the usage for %s:" % meth
            print api.help({'function': meth})
    else:
        print "Unknown function"
        print msg
示例#23
0
def main():
    api = JSONRPCProxy.from_url(API_CONNECTION_STRING)

    try:
        s = api.is_running()
    except:
        print "lbrynet-daemon isn't running"
        sys.exit(1)

    args = sys.argv[1:]
    meth = args[0]

    msg = help_msg
    for f in api.help():
        msg += f + "\n"

    if meth in ['--help', '-h', 'help']:
        print msg
        sys.exit(1)

    if len(args) > 1:
        if isinstance(args[1], dict):
            params = args[1]
        elif isinstance(args[1], basestring):
            params = json.loads(args[1])
    else:
        params = None

    if meth in api.help():
        try:
            if params:
                r = api.call(meth, params)
            else:
                r = api.call(meth)
            print json.dumps(r, sort_keys=True)
        except:
            print "Something went wrong, here's the usage for %s:" % meth
            print api.help({'function': meth})
    else:
        print "Unknown function"
        print msg
示例#24
0
def shell_command(command):
    FNULL = open(os.devnull, 'w')
    p = subprocess.Popen(command,shell=False,stdout=FNULL,stderr=subprocess.STDOUT)


def lbrynet_cli(commands):
    cli_cmd=['lbrynet-cli']
    for cmd in commands:
        cli_cmd.append(cmd)
    p = subprocess.Popen(cli_cmd,shell=False,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
    out,err = p.communicate()
    return out,err

lbrynet_rpc_port = '5279'
lbrynet = JSONRPCProxy.from_url("http://localhost:{}/lbryapi".format(lbrynet_rpc_port))


class TestIntegration(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        shell_command(['lbrynet-daemon'])
        start_time = time.time()
        STARTUP_TIMEOUT = 180
        while time.time() - start_time < STARTUP_TIMEOUT:
            try:
                status = lbrynet.status()
            except (URLError,error,BadStatusLine) as e:
                pass
            else:
                if status['is_running'] == True:
示例#25
0
#!/usr/bin/env python2
# utility program for calling lbryum commands from command line
import json
import sys
from jsonrpc.proxy import JSONRPCProxy
jsonrpc  = JSONRPCProxy.from_url('http://localhost:7777','')

def json_decode(s):
    try:
        out = json.loads(s)
    except ValueError:
        out = s
    return out

if __name__ == '__main__':
    cmdname = sys.argv[1]
    cmds = sys.argv[2:]
    cmds = [json_decode(cmd) for cmd in cmds]
    out = getattr(jsonrpc,cmdname)(*cmds)
    print json.dumps(out)
示例#26
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")
示例#27
0
 def __init__(self):
     self.started_daemon = False
     self.daemon = JSONRPCProxy.from_url(API_CONNECTION_STRING)
示例#28
0
# ImportError for jsonrpc [python]
from jsonrpc.proxy import JSONRPCProxy
givex = JSONRPCProxy.from_url("http://localhost/url/of/your/service.py")
示例#29
0
文件: keynes.py 项目: lbryio/keynes
 def __init__(self):
     self._api = JSONRPCProxy.from_url(API_CONNECTION_STRING)
     self._checker = LoopingCall(self._check_for_new_claims)
     self.best_block = None
示例#30
0
def start():
    parser = argparse.ArgumentParser(description="Launch lbrynet-daemon")
    parser.add_argument("--wallet",
                        help="lbryum or ptc for testing, default lbryum",
                        type=str,
                        default=conf.LBRYUM_WALLET)
    parser.add_argument("--ui", help="path to custom UI folder", default=None)
    parser.add_argument(
        "--branch",
        help='Branch of lbry-web-ui repo to use, defaults to {}'.format(settings.ui_branch),
        default=settings.ui_branch)
    parser.add_argument('--no-launch', dest='launchui', action="store_false")
    parser.add_argument("--http-auth", dest="useauth", action="store_true")
    parser.add_argument(
        '--log-to-console', dest='logtoconsole', action='store_true',
        help=('Set to enable console logging. Set the --verbose flag '
              ' to enable more detailed console logging'))
    parser.add_argument(
        '--quiet', dest='quiet', action="store_true",
        help=('If log-to-console is not set, setting this disables all console output. '
              'If log-to-console is set, this argument is ignored'))
    parser.add_argument(
        '--verbose', nargs="*",
        help=('Enable debug output. Optionally specify loggers for which debug output '
              'should selectively be applied.'))
    args = parser.parse_args()

    utils.setup_certs_for_windows()

    conf.update_settings_from_file()
    update_settings_from_args(args)

    lbrynet_log = settings.get_log_filename()
    log_support.configure_logging(lbrynet_log, args.logtoconsole, args.verbose)
    log.debug('Final Settings: %s', settings.get_dict())

    try:
        log.debug('Checking for an existing lbrynet daemon instance')
        JSONRPCProxy.from_url(settings.API_CONNECTION_STRING).is_running()
        log.info("lbrynet-daemon is already running")
        if not args.logtoconsole:
            print "lbrynet-daemon is already running"
        return
    except Exception:
        log.debug('No lbrynet instance found, continuing to start')
        pass

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

    if not args.logtoconsole and not args.quiet:
        print "Starting lbrynet-daemon from command line"
        print "To view activity, view the log file here: " + lbrynet_log
        print "Web UI is available at http://%s:%i" % (settings.API_INTERFACE, settings.api_port)
        print "JSONRPC API is available at " + settings.API_CONNECTION_STRING
        print "To quit press ctrl-c or call 'stop' via the API"

    if test_internet_connection():
        analytics_manager = analytics.Manager.new_instance()
        analytics_manager.send_server_startup()
        start_server_and_listen(args.launchui, args.useauth, analytics_manager)
        reactor.run()

        if not args.logtoconsole and not args.quiet:
            print "\nClosing lbrynet-daemon"
    else:
        log.info("Not connected to internet, unable to start")
        if not args.logtoconsole:
            print "Not connected to internet, unable to start"
        return
示例#31
0
from jsonrpc.proxy import JSONRPCProxy
import sys
import string

# ===== BEGIN USER SETTINGS =====
# if you do not set these you will be prompted for a password for every command
rpcuser = ""
rpcpass = ""
# ====== END USER SETTINGS ======

if rpcpass == "":
    access = JSONRPCProxy.from_url("http://127.0.0.1:8332")
else:
    access = JSONRPCProxy.from_url("http://" + rpcuser + ":" + rpcpass +
                                   "@127.0.0.1:8332")
cmd = sys.argv[1].lower()

if cmd == "backupwallet":
    try:
        path = input("Enter destination path/filename: ")
        print(access.backupwallet(path))
    except:
        print("\n---An error occurred---\n")

elif cmd == "getaccount":
    try:
        addr = input("Enter a Honey address: ")
        print(access.getaccount(addr))
    except:
        print("\n---An error occurred---\n")
示例#32
0
文件: Console.py 项目: DaveA50/lbry
def launch_lbry_console():
    from twisted.internet import reactor

    parser = argparse.ArgumentParser(description="Launch a lbrynet console")
    parser.add_argument("--no_listen_peer",
                        help="Don't listen for incoming data connections.",
                        action="store_true")
    parser.add_argument("--peer_port",
                        help="The port on which the console will listen for incoming data connections.",
                        type=int, default=3333)
    parser.add_argument("--no_listen_dht",
                        help="Don't listen for incoming DHT connections.",
                        action="store_true")
    parser.add_argument("--dht_node_port",
                        help="The port on which the console will listen for DHT connections.",
                        type=int, default=4444)
    parser.add_argument("--fake_wallet",
                        help="Testing purposes only. Use a non-blockchain wallet.",
                        action="store_true")
    parser.add_argument("--no_dht_bootstrap",
                        help="Don't try to connect to the DHT",
                        action="store_true")
    parser.add_argument("--dht_bootstrap_host",
                        help="The hostname of a known DHT node, to be used to bootstrap into the DHT. "
                             "Must be used with --dht_bootstrap_port",
                        type=str, default='104.236.42.182')
    parser.add_argument("--dht_bootstrap_port",
                        help="The port of a known DHT node, to be used to bootstrap into the DHT. Must "
                             "be used with --dht_bootstrap_host",
                        type=int, default=4000)
    parser.add_argument("--disable_upnp",
                        help="Don't try to use UPnP to enable incoming connections through the firewall",
                        action="store_true")
    parser.add_argument("--data_dir",
                        help=("The full path to the directory in which lbrynet data and metadata will be stored. "
                              "Default: ~/.lbrynet on linux, ~/Library/Application Support/lbrynet on OS X"),
                        type=str)
    parser.add_argument("--lbrycrdd_path",
                        help="The path to lbrycrdd, which will be launched if it isn't running. If"
                             "this option is chosen, lbrycrdd will be used as the interface to the"
                             "blockchain. By default, a lightweight interface is used.")
    parser.add_argument("--lbrycrd_wallet_dir",
                        help="The directory in which lbrycrd data will stored. Used if lbrycrdd is "
                             "launched by this application.")
    parser.add_argument("--lbrycrd_wallet_conf",
                        help="The configuration file for the LBRYcrd wallet. Default: ~/.lbrycrd/lbrycrd.conf",
                        type=str)

    args = parser.parse_args()

    if args.no_dht_bootstrap:
        bootstrap_nodes = []
    else:
        bootstrap_nodes = [(args.dht_bootstrap_host, args.dht_bootstrap_port)]

    if args.no_listen_peer:
        peer_port = None
    else:
        peer_port = args.peer_port

    if args.no_listen_dht:
        dht_node_port = None
    else:
        dht_node_port = args.dht_node_port

    created_data_dir = False
    if not args.data_dir:
        if sys.platform == "darwin":
            data_dir = user_data_dir("LBRY")
        else:
            data_dir = os.path.join(os.path.expanduser("~"), ".lbrynet")
    else:
        data_dir = args.data_dir
    if not os.path.exists(data_dir):
        os.mkdir(data_dir)
        created_data_dir = True

    daemon = JSONRPCProxy.from_url(API_CONNECTION_STRING)
    try:
        daemon.is_running()
        log.info("Attempt to start lbrynet-console while lbrynet-daemon is running")
        print "lbrynet-daemon is running, you must turn it off before using lbrynet-console"
        print "If you're running the app, quit before starting lbrynet-console"
        print "If you're running lbrynet-daemon in a terminal, run 'stop-lbrynet-daemon' to turn it off"

        webbrowser.open("http://localhost:5279")

    except:
        log_format = "(%(asctime)s)[%(filename)s:%(lineno)s] %(funcName)s(): %(message)s"
        formatter = logging.Formatter(log_format)

        logger = logging.getLogger()
        logger.setLevel(logging.DEBUG)
        file_handler = logging.FileHandler(os.path.join(data_dir, "console.log"))
        file_handler.setFormatter(formatter)
        file_handler.addFilter(logging.Filter("lbrynet"))
        logger.addHandler(file_handler)


        console = Console(peer_port, dht_node_port, bootstrap_nodes, fake_wallet=args.fake_wallet,
                                lbrycrd_conf=args.lbrycrd_wallet_conf, lbrycrd_dir=args.lbrycrd_wallet_dir,
                                use_upnp=not args.disable_upnp, data_dir=data_dir,
                                created_data_dir=created_data_dir, lbrycrdd_path=args.lbrycrdd_path)

        d = task.deferLater(reactor, 0, console.start)
        d.addErrback(lambda _: reactor.stop())
        reactor.addSystemEventTrigger('before', 'shutdown', console.shut_down)
        reactor.run()
示例#33
0
import curses
import time
from jsonrpc.proxy import JSONRPCProxy
import logging

log = logging.getLogger(__name__)
log.addHandler(logging.FileHandler("dht contacts.log"))
# log.addHandler(logging.StreamHandler())
log.setLevel(logging.INFO)
stdscr = curses.initscr()

api = JSONRPCProxy.from_url("http://localhost:5279")


def init_curses():
    curses.noecho()
    curses.cbreak()
    stdscr.nodelay(1)
    stdscr.keypad(1)


def teardown_curses():
    curses.nocbreak()
    stdscr.keypad(0)
    curses.echo()
    curses.endwin()


def refresh(last_contacts, last_blobs):
    height, width = stdscr.getmaxyx()
示例#34
0
        print qq2.opn_classify(tt['tweet'])
        print tt['tweet']


#classify_init()
test()
exit(0)

svm = SVMLight("/home/xorox90/svm", model="polar_model", cleanup=True)
ans = []
gold = []
x = []
index =1

qq = JSONRPCProxy("http://61.43.139.70:8000")
qq2 = JSONRPCProxy("http://office2.buzzni.com:10100")

con = MySQLdb.connect(db='twit_manager', host="61.43.139.70",user='******', passwd='1rmdwjd', charset="UTF8")
cur = con.cursor(cursorclass=MySQLdb.cursors.DictCursor)
cur.execute("select * from tweet_data order by no desc limit 10000")

arr = []
for tt in cur.fetchall():
    arr.append(tt['tweet'])

print len(arr)

dic = load_dic()
for line in arr:
    x.append(apply_dic(dic, line))
    polarity = qq2.opn_classify(line)
示例#35
0
 def get_client():
     return AuthAPIClient.config() if conf.settings['use_auth_http'] else \
         JSONRPCProxy.from_url(conf.settings.get_api_connection_string())
示例#36
0
import curses
import time
from jsonrpc.proxy import JSONRPCProxy
import logging

log = logging.getLogger(__name__)
log.addHandler(logging.FileHandler("dht contacts.log"))
# log.addHandler(logging.StreamHandler())
log.setLevel(logging.INFO)
stdscr = curses.initscr()

api = JSONRPCProxy.from_url("http://localhost:5279")


def init_curses():
    curses.noecho()
    curses.cbreak()
    stdscr.nodelay(1)
    stdscr.keypad(1)


def teardown_curses():
    curses.nocbreak()
    stdscr.keypad(0)
    curses.echo()
    curses.endwin()


def refresh(last_contacts, last_blobs):
    height, width = stdscr.getmaxyx()
示例#37
0
 def __init__(self, settings):
     JSONRPCProxy.__init__(self, 
示例#38
0

def lbrynet_cli(commands):
    cli_cmd = ['lbrynet-cli']
    for cmd in commands:
        cli_cmd.append(cmd)
    p = subprocess.Popen(cli_cmd,
                         shell=False,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE)
    out, err = p.communicate()
    return out, err


lbrynet_rpc_port = '5279'
lbrynet = JSONRPCProxy.from_url("http://localhost:{}".format(lbrynet_rpc_port))


class TestIntegration(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        shell_command(['lbrynet-daemon'])
        start_time = time.time()
        STARTUP_TIMEOUT = 180
        while time.time() - start_time < STARTUP_TIMEOUT:
            try:
                status = lbrynet.status()
            except (URLError, error, BadStatusLine) as e:
                pass
            else:
                if status['is_running'] == True:
示例#39
0
def launch_lbry_console():
    from twisted.internet import reactor

    parser = argparse.ArgumentParser(description="Launch a lbrynet console")
    parser.add_argument("--no_listen_peer",
                        help="Don't listen for incoming data connections.",
                        action="store_true")
    parser.add_argument("--peer_port",
                        help="The port on which the console will listen for incoming data connections.",
                        type=int, default=3333)
    parser.add_argument("--no_listen_dht",
                        help="Don't listen for incoming DHT connections.",
                        action="store_true")
    parser.add_argument("--dht_node_port",
                        help="The port on which the console will listen for DHT connections.",
                        type=int, default=4444)
    parser.add_argument("--fake_wallet",
                        help="Testing purposes only. Use a non-blockchain wallet.",
                        action="store_true")
    parser.add_argument("--no_dht_bootstrap",
                        help="Don't try to connect to the DHT",
                        action="store_true")
    parser.add_argument("--dht_bootstrap_host",
                        help="The hostname of a known DHT node, to be used to bootstrap into the DHT. "
                             "Must be used with --dht_bootstrap_port",
                        type=str, default='104.236.42.182')
    parser.add_argument("--dht_bootstrap_port",
                        help="The port of a known DHT node, to be used to bootstrap into the DHT. Must "
                             "be used with --dht_bootstrap_host",
                        type=int, default=4000)
    parser.add_argument("--disable_upnp",
                        help="Don't try to use UPnP to enable incoming connections through the firewall",
                        action="store_true")
    parser.add_argument("--data_dir",
                        help=("The full path to the directory in which lbrynet data and metadata will be stored. "
                              "Default: ~/.lbrynet on linux, ~/Library/Application Support/lbrynet on OS X"),
                        type=str)
    parser.add_argument("--lbrycrdd_path",
                        help="The path to lbrycrdd, which will be launched if it isn't running. If"
                             "this option is chosen, lbrycrdd will be used as the interface to the"
                             "blockchain. By default, a lightweight interface is used.")
    parser.add_argument("--lbrycrd_wallet_dir",
                        help="The directory in which lbrycrd data will stored. Used if lbrycrdd is "
                             "launched by this application.")
    parser.add_argument("--lbrycrd_wallet_conf",
                        help="The configuration file for the LBRYcrd wallet. Default: ~/.lbrycrd/lbrycrd.conf",
                        type=str)

    args = parser.parse_args()

    if args.no_dht_bootstrap:
        bootstrap_nodes = []
    else:
        bootstrap_nodes = [(args.dht_bootstrap_host, args.dht_bootstrap_port)]

    if args.no_listen_peer:
        peer_port = None
    else:
        peer_port = args.peer_port

    if args.no_listen_dht:
        dht_node_port = None
    else:
        dht_node_port = args.dht_node_port

    created_data_dir = False
    if not args.data_dir:
        if sys.platform == "darwin":
            data_dir = user_data_dir("LBRY")
        else:
            data_dir = os.path.join(os.path.expanduser("~"), ".lbrynet")
    else:
        data_dir = args.data_dir
    if not os.path.exists(data_dir):
        os.mkdir(data_dir)
        created_data_dir = True

    daemon = JSONRPCProxy.from_url(API_CONNECTION_STRING)
    try:
        daemon.is_running()
        log.info("Attempt to start lbrynet-console while lbrynet-daemon is running")
        print "lbrynet-daemon is running, you must turn it off before using lbrynet-console"
        print "If you're running the app, quit before starting lbrynet-console"
        print "If you're running lbrynet-daemon in a terminal, run 'stop-lbrynet-daemon' to turn it off"

        webbrowser.open("http://localhost:5279")

    except:
        log_format = "(%(asctime)s)[%(filename)s:%(lineno)s] %(funcName)s(): %(message)s"
        formatter = logging.Formatter(log_format)

        logger = logging.getLogger()
        logger.setLevel(logging.DEBUG)
        file_handler = logging.FileHandler(os.path.join(data_dir, "console.log"))
        file_handler.setFormatter(formatter)
        file_handler.addFilter(logging.Filter("lbrynet"))
        logger.addHandler(file_handler)


        console = LBRYConsole(peer_port, dht_node_port, bootstrap_nodes, fake_wallet=args.fake_wallet,
                                lbrycrd_conf=args.lbrycrd_wallet_conf, lbrycrd_dir=args.lbrycrd_wallet_dir,
                                use_upnp=not args.disable_upnp, data_dir=data_dir,
                                created_data_dir=created_data_dir, lbrycrdd_path=args.lbrycrdd_path)

        d = task.deferLater(reactor, 0, console.start)
        d.addErrback(lambda _: reactor.stop())
        reactor.addSystemEventTrigger('before', 'shutdown', console.shut_down)
        reactor.run()
示例#40
0
def start():
    parser = argparse.ArgumentParser(description="Launch lbrynet-daemon")
    parser.add_argument("--wallet",
                        help="lbrycrd or lbryum, default lbryum",
                        type=str,
                        default='')
    parser.add_argument("--ui", help="path to custom UI folder", default=None)
    parser.add_argument(
        "--branch",
        help="Branch of lbry-web-ui repo to use, defaults on master")
    parser.add_argument('--no-launch', dest='launchui', action="store_false")
    parser.add_argument('--log-to-console',
                        dest='logtoconsole',
                        action="store_true")
    parser.add_argument('--quiet', dest='quiet', action="store_true")
    parser.add_argument('--verbose',
                        action='store_true',
                        help='enable more debug output for the console')
    parser.set_defaults(branch=False,
                        launchui=True,
                        logtoconsole=False,
                        quiet=False)
    args = parser.parse_args()

    log_support.configure_file_handler(lbrynet_log)
    log_support.configure_loggly_handler()
    if args.logtoconsole:
        log_support.configure_console(level='DEBUG')
    log_support.disable_third_party_loggers()
    if not args.verbose:
        log_support.disable_noisy_loggers()

    try:
        JSONRPCProxy.from_url(API_CONNECTION_STRING).is_running()
        log.info("lbrynet-daemon is already running")
        if not args.logtoconsole:
            print "lbrynet-daemon is already running"
        if args.launchui:
            webbrowser.open(UI_ADDRESS)
        return
    except:
        pass

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

    if not args.logtoconsole and not args.quiet:
        print "Starting lbrynet-daemon from command line"
        print "To view activity, view the log file here: " + lbrynet_log
        print "Web UI is available at http://%s:%i" % (API_INTERFACE, API_PORT)
        print "JSONRPC API is available at " + API_CONNECTION_STRING
        print "To quit press ctrl-c or call 'stop' via the API"

    if test_internet_connection():
        lbry = DaemonServer()

        d = lbry.start(
            branch=args.branch if args.branch else DEFAULT_UI_BRANCH,
            user_specified=args.ui,
            wallet=args.wallet,
            branch_specified=True if args.branch else False)
        if args.launchui:
            d.addCallback(lambda _: webbrowser.open(UI_ADDRESS))

        lbrynet_server = server.Site(lbry.root)
        lbrynet_server.requestFactory = DaemonRequest
        reactor.listenTCP(API_PORT, lbrynet_server, interface=API_INTERFACE)
        reactor.run()

        if not args.logtoconsole and not args.quiet:
            print "\nClosing lbrynet-daemon"
    else:
        log.info("Not connected to internet, unable to start")
        if not args.logtoconsole:
            print "Not connected to internet, unable to start"
        return
示例#41
0
    systray_thread.start()

    lbry = DaemonServer()
    d = lbry.start()
    d.addCallback(lambda _: LBRYURIHandler.open_address(lbry_name))
    lbrynet_server = server.Site(lbry.root)
    lbrynet_server.requestFactory = DaemonRequest
    try:
        reactor.listenTCP(API_PORT, lbrynet_server, interface=API_INTERFACE)
    except error.CannotListenError:
        log.info('Daemon already running, exiting app')
        sys.exit(1)
    reactor.run()

if __name__ == '__main__':
    lbry_daemon = JSONRPCProxy.from_url(API_CONNECTION_STRING)

    try:
        daemon_running = lbry_daemon.is_running()
        start_daemon = False
    except:
        start_daemon = True

    try:
        lbry_name = LBRYURIHandler.parse_name(sys.argv[1])
    except IndexError:
        lbry_name = None
    start_daemon = True
    if start_daemon:
        main(lbry_name)
    else:
示例#42
0
#import logging
##logger = logging.getLogger("lovely.jsonrpc.dispatcher")
#logger.addHandler(logging.StreamHandler(sys.stderr))
#logger.setLevel(logging.DEBUG)

#for item in sorted(sys.path):
#    print item
#from ZODB.FileStorage import FileStorage
#from ZODB.DB import DB
#import jsonrpclib
from operator import attrgetter
import json
import os
from jsonrpc.proxy import JSONRPCProxy
client = JSONRPCProxy.from_url('http://localhost:8080/rpc/login')
#client = JSONRPCProxy.from_url('https://gae_project.appspot.com/rpc/login')
#client = JSONRPCProxy.from_url('http://localhost:8080/xadmin')
#f = client.reverse('hello world!')
#print f
authenticated = client.login('username', 'password')

if authenticated:
    print("authentication OK")
else:
    print("authentication NOT OK")

client._path = 'xadmin'
event_key = client.create_fbla_event(title='Example exam', organization='', proctoring=False, registering=False)

for item in client.list_all_events():
示例#43
0
    DaemonControl.start_server_and_listen(
        launchui=True, use_auth=False,
        analytics_manager=analytics.Manager.new_instance()
    )
    reactor.run()


if __name__ == '__main__':
    utils.setup_certs_for_windows()
    conf.initialize_settings()

    log_file = conf.settings.get_log_filename()
    log_support.configure_logging(log_file, console=True)

    lbry_daemon = JSONRPCProxy.from_url(conf.settings.get_api_connection_string())

    try:
        daemon_running = lbry_daemon.is_running()
        start_daemon = False
    except:
        start_daemon = True

    try:
        lbry_name = LBRYURIHandler.parse_name(sys.argv[1])
    except IndexError:
        lbry_name = None
    start_daemon = True
    if start_daemon:
        main(lbry_name)
    else:
示例#44
0
    DaemonControl.start_server_and_listen(
        launchui=True,
        use_auth=False,
        analytics_manager=analytics.Manager.new_instance())
    reactor.run()


if __name__ == '__main__':
    utils.setup_certs_for_windows()
    conf.update_settings_from_file()

    log_file = settings.get_log_filename()
    log_support.configure_logging(log_file, console=True)

    lbry_daemon = JSONRPCProxy.from_url(settings.API_CONNECTION_STRING)

    try:
        daemon_running = lbry_daemon.is_running()
        start_daemon = False
    except:
        start_daemon = True

    try:
        lbry_name = LBRYURIHandler.parse_name(sys.argv[1])
    except IndexError:
        lbry_name = None
    start_daemon = True
    if start_daemon:
        main(lbry_name)
    else:
示例#45
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")
示例#46
0
 def __init__(self):
     self.started_daemon = False
     self.daemon = JSONRPCProxy.from_url(API_CONNECTION_STRING)
示例#47
0
def start():
    parser = argparse.ArgumentParser(description="Launch lbrynet-daemon")
    parser.add_argument("--wallet",
                        help="lbrycrd or lbryum, default lbryum",
                        type=str,
                        default=conf.LBRYUM_WALLET)
    parser.add_argument("--ui", help="path to custom UI folder", default=None)
    parser.add_argument(
        "--branch",
        help='Branch of lbry-web-ui repo to use, defaults to {}'.format(
            settings.ui_branch),
        default=settings.ui_branch)
    parser.add_argument('--no-launch', dest='launchui', action="store_false")
    parser.add_argument("--http-auth", dest="useauth", action="store_true")
    parser.add_argument(
        '--log-to-console',
        dest='logtoconsole',
        action='store_true',
        help=('Set to enable console logging. Set the --verbose flag '
              ' to enable more detailed console logging'))
    parser.add_argument(
        '--quiet',
        dest='quiet',
        action="store_true",
        help=
        ('If log-to-console is not set, setting this disables all console output. '
         'If log-to-console is set, this argument is ignored'))
    parser.add_argument(
        '--verbose',
        nargs="*",
        help=
        ('Enable debug output. Optionally specify loggers for which debug output '
         'should selectively be applied.'))
    args = parser.parse_args()

    utils.setup_certs_for_windows()

    conf.update_settings_from_file()
    update_settings_from_args(args)

    lbrynet_log = settings.get_log_filename()
    log_support.configure_logging(lbrynet_log, args.logtoconsole, args.verbose)
    log.debug('Final Settings: %s', settings.get_dict())

    try:
        log.debug('Checking for an existing lbrynet daemon instance')
        JSONRPCProxy.from_url(settings.API_CONNECTION_STRING).is_running()
        log.info("lbrynet-daemon is already running")
        if not args.logtoconsole:
            print "lbrynet-daemon is already running"
        return
    except Exception:
        log.debug('No lbrynet instance found, continuing to start')
        pass

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

    if not args.logtoconsole and not args.quiet:
        print "Starting lbrynet-daemon from command line"
        print "To view activity, view the log file here: " + lbrynet_log
        print "Web UI is available at http://%s:%i" % (settings.API_INTERFACE,
                                                       settings.api_port)
        print "JSONRPC API is available at " + settings.API_CONNECTION_STRING
        print "To quit press ctrl-c or call 'stop' via the API"

    if test_internet_connection():
        analytics_manager = analytics.Manager.new_instance()
        analytics_manager.send_server_startup()
        start_server_and_listen(args.launchui, args.useauth, analytics_manager)
        reactor.run()

        if not args.logtoconsole and not args.quiet:
            print "\nClosing lbrynet-daemon"
    else:
        log.info("Not connected to internet, unable to start")
        if not args.logtoconsole:
            print "Not connected to internet, unable to start"
        return
示例#48
0
import subprocess
import json
import time
import string

lbrycrd_rpc_user = '******'
lbrycrd_rpc_pw = 'jhopfpusrx'
lbrycrd_rpc_ip = '127.0.0.1'
lbrycrd_rpc_port = '19001'
lbryum_lbrycrd_rpc_port = '19011'
lbrynet_rpc_port = '5279'
dht_rpc_port = '5278'
reflector_rpc_port = '5277'

lbrynets = {}
lbrynets['lbrynet'] = JSONRPCProxy.from_url("http://localhost:{}/lbryapi".format(lbrynet_rpc_port))
lbrynets['dht'] = JSONRPCProxy.from_url("http://localhost:{}/lbryapi".format(dht_rpc_port))
lbrynets['reflector'] = JSONRPCProxy.from_url(
    "http://localhost:{}/lbryapi".format(reflector_rpc_port))

DOCKER_LOG_FILE = 'tmp.log'
NUM_INITIAL_BLOCKS_GENERATED = 150


def get_lbrycrd_authproxy(instance):
    if instance == 'lbryum-server':
        port = lbryum_lbrycrd_rpc_port
    elif instance == 'lbrycrd':
        port = lbrycrd_rpc_port
    else:
        raise Exception('unhandled type')
示例#49
0
    DaemonControl.start_server_and_listen(
        launchui=True,
        use_auth=False,
        analytics_manager=analytics.Manager.new_instance())
    reactor.run()


if __name__ == '__main__':
    utils.setup_certs_for_windows()
    conf.initialize_settings()

    log_file = conf.settings.get_log_filename()
    log_support.configure_logging(log_file, console=True)

    lbry_daemon = JSONRPCProxy.from_url(
        conf.settings.get_api_connection_string())

    try:
        daemon_running = lbry_daemon.is_running()
        start_daemon = False
    except:
        start_daemon = True

    try:
        lbry_name = LBRYURIHandler.parse_name(sys.argv[1])
    except IndexError:
        lbry_name = None
    start_daemon = True
    if start_daemon:
        main(lbry_name)
    else:
示例#50
0
文件: client.py 项目: Fillerix99/lbry
 def get_client():
     return AuthAPIClient.config() if conf.settings['use_auth_http'] else \
         JSONRPCProxy.from_url(conf.settings.get_api_connection_string())