improve get_external_ip

This commit is contained in:
Jack Robison 2018-11-07 18:35:32 -05:00
parent 7b32e2ff7c
commit e9efd9f68a
No known key found for this signature in database
GPG key ID: DF25C68FE0239BB2
5 changed files with 22 additions and 24 deletions

View file

@ -140,7 +140,7 @@ def main(argv=None):
elif method in ['version', '--version', '-v']: elif method in ['version', '--version', '-v']:
print("{lbrynet_name} {lbrynet_version}".format( print("{lbrynet_name} {lbrynet_version}".format(
lbrynet_name=lbrynet_name, **get_platform(get_ip=False) lbrynet_name=lbrynet_name, **get_platform()
)) ))
return 0 return 0

View file

@ -2,6 +2,7 @@ import os
import asyncio import asyncio
import logging import logging
import treq import treq
import json
import math import math
import binascii import binascii
from hashlib import sha256 from hashlib import sha256
@ -11,7 +12,7 @@ import lbrynet.schema
from aioupnp import __version__ as aioupnp_version from aioupnp import __version__ as aioupnp_version
from aioupnp.upnp import UPnP from aioupnp.upnp import UPnP
from aioupnp.fault import UPnPError from aioupnp.fault import UPnPError
from lbrynet import conf, system_info from lbrynet import conf
from lbrynet.utils import DeferredDict, generate_id from lbrynet.utils import DeferredDict, generate_id
from lbrynet.p2p.PaymentRateManager import OnlyFreePaymentsManager from lbrynet.p2p.PaymentRateManager import OnlyFreePaymentsManager
from lbrynet.p2p.RateLimiter import RateLimiter from lbrynet.p2p.RateLimiter import RateLimiter
@ -93,9 +94,19 @@ class ConfigSettings:
return conf.settings.node_id return conf.settings.node_id
@staticmethod @staticmethod
def get_external_ip(): @defer.inlineCallbacks
platform = system_info.get_platform(get_ip=True) def get_external_ip(): # used if upnp is disabled or non-functioning
return platform['ip'] try:
buf = []
response = yield treq.get("https://api.lbry.io/ip")
yield treq.collect(response, buf.append)
parsed = json.loads(b"".join(buf).decode())
if parsed['success']:
return parsed['data']['ip']
return
except Exception as err:
return
# Shorthand for common ConfigSettings methods # Shorthand for common ConfigSettings methods
@ -429,7 +440,7 @@ class DHTComponent(Component):
external_ip = self.upnp_component.external_ip external_ip = self.upnp_component.external_ip
if not external_ip: if not external_ip:
log.warning("UPnP component failed to get external ip") log.warning("UPnP component failed to get external ip")
external_ip = CS.get_external_ip() external_ip = yield CS.get_external_ip()
if not external_ip: if not external_ip:
log.warning("failed to get external ip") log.warning("failed to get external ip")
@ -705,7 +716,7 @@ class UPnPComponent(Component):
if external_ip == "0.0.0.0" or not external_ip: if external_ip == "0.0.0.0" or not external_ip:
log.warning("unable to get external ip from UPnP, checking lbry.io fallback") log.warning("unable to get external ip from UPnP, checking lbry.io fallback")
external_ip = CS.get_external_ip() external_ip = yield CS.get_external_ip()
if self.external_ip and self.external_ip != external_ip: if self.external_ip and self.external_ip != external_ip:
log.info("external ip changed from %s to %s", self.external_ip, external_ip) log.info("external ip changed from %s to %s", self.external_ip, external_ip)
self.external_ip = external_ip self.external_ip = external_ip
@ -761,7 +772,7 @@ class UPnPComponent(Component):
def start(self): def start(self):
log.info("detecting external ip") log.info("detecting external ip")
if not self.use_upnp: if not self.use_upnp:
self.external_ip = CS.get_external_ip() self.external_ip = yield CS.get_external_ip()
return return
success = False success = False
yield self._maintain_redirects() yield self._maintain_redirects()

View file

@ -53,7 +53,7 @@ def start(argv=None, conf_path=None):
conf.settings.update({'use_auth_http': args.useauth}, data_types=(conf.TYPE_CLI,)) conf.settings.update({'use_auth_http': args.useauth}, data_types=(conf.TYPE_CLI,))
if args.version: if args.version:
version = system_info.get_platform(get_ip=False) version = system_info.get_platform()
version['installation_id'] = conf.settings.installation_id version['installation_id'] = conf.settings.installation_id
print(utils.json_dumps_pretty(version)) print(utils.json_dumps_pretty(version))
return return

View file

@ -1,9 +1,6 @@
import platform import platform
import json
import os import os
from six.moves.urllib import request
from six.moves.urllib.error import URLError
from lbrynet.schema import __version__ as schema_version from lbrynet.schema import __version__ as schema_version
from lbrynet import build_type, __version__ as lbrynet_version from lbrynet import build_type, __version__ as lbrynet_version
import logging.handlers import logging.handlers
@ -15,7 +12,7 @@ def get_lbrynet_version() -> str:
return lbrynet_version return lbrynet_version
def get_platform(get_ip: bool = True) -> dict: def get_platform() -> dict:
p = { p = {
"processor": platform.processor(), "processor": platform.processor(),
"python_version": platform.python_version(), "python_version": platform.python_version(),
@ -34,14 +31,4 @@ def get_platform(get_ip: bool = True) -> dict:
except ModuleNotFoundError: except ModuleNotFoundError:
pass pass
# TODO: remove this from get_platform and add a get_external_ip function using treq
if get_ip:
try:
response = json.loads(request.urlopen("https://api.lbry.io/ip").read())
if not response['success']:
raise URLError("failed to get external ip")
p['ip'] = response['data']['ip']
except (URLError, AssertionError):
p['ip'] = "Could not determine IP"
return p return p

View file

@ -67,7 +67,7 @@ class CLITest(unittest.TestCase):
main(['version']) main(['version'])
self.assertEqual( self.assertEqual(
actual_output.getvalue().strip(), actual_output.getvalue().strip(),
"lbrynet {lbrynet_version}".format(**get_platform(get_ip=False)) "lbrynet {lbrynet_version}".format(**get_platform())
) )
def test_invalid_command(self): def test_invalid_command(self):