fix typo and formatting errors, stop console's shutdown from running twice on exit, give more informative message if ports can't be bound, only set upnp if there isn't already a redirect on that port/protocol, and only unset upnp if the redirect was set by the program

This commit is contained in:
Jimmy Kiselak 2015-10-19 15:05:17 -04:00
parent 76a5f2f516
commit 7df6e99e28
4 changed files with 57 additions and 32 deletions

View file

@ -95,8 +95,8 @@ class LBRYSession(object):
self.rate_limiter = rate_limiter
self.external_ip = '127.0.0.1'
self.upnp_handler = None
self.upnp_redirects_set = False
self.upnp_redirects = []
self.wallet = wallet
@ -148,7 +148,6 @@ class LBRYSession(object):
ds.append(defer.maybeDeferred(self.wallet.stop))
if self.blob_manager is not None:
ds.append(defer.maybeDeferred(self.blob_manager.stop))
if self.upnp_redirects_set is True:
ds.append(defer.maybeDeferred(self._unset_upnp))
return defer.DeferredList(ds)
@ -163,16 +162,24 @@ class LBRYSession(object):
u = miniupnpc.UPnP()
num_devices_found = u.discover()
if num_devices_found > 0:
self.upnp_handler = u
u.selectigd()
external_ip = u.externalipaddress()
if external_ip != '0.0.0.0':
self.external_ip = external_ip
if self.peer_port is not None:
if u.getspecificportmapping(self.peer_port, 'TCP') is None:
u.addportmapping(self.peer_port, 'TCP', u.lanaddr, self.peer_port, 'LBRY peer port', '')
self.upnp_redirects.append((self.peer_port, 'TCP'))
log.info("Set UPnP redirect for TCP port %d", self.peer_port)
else:
log.warning("UPnP redirect already set for TCP port %d", self.peer_port)
if self.dht_node_port is not None:
if u.getspecificportmapping(self.dht_node_port, 'UDP') is None:
u.addportmapping(self.dht_node_port, 'UDP', u.lanaddr, self.dht_node_port, 'LBRY DHT port', '')
self.upnp_redirects_set = True
self.upnp_redirects.append((self.dht_node_port, 'UDP'))
log.info("Set UPnP redirect for UPD port %d", self.dht_node_port)
else:
log.warning("UPnP redirect already set for UDP port %d", self.dht_node_port)
return True
return False
@ -247,11 +254,16 @@ class LBRYSession(object):
def _unset_upnp(self):
def threaded_unset_upnp():
u = self.upnp_handler
if self.peer_port is not None:
u.deleteportmapping(self.peer_port, 'TCP')
if self.dht_node_port is not None:
u.deleteportmapping(self.dht_node_port, 'UDP')
self.upnp_redirects_set = False
u = miniupnpc.UPnP()
num_devices_found = u.discover()
if num_devices_found > 0:
u.selectigd()
for port, protocol in self.upnp_redirects:
if u.getspecificportmapping(port, protocol) is None:
log.warning("UPnP redirect for %s %d was removed by something else.", protocol, port)
else:
u.deleteportmapping(port, protocol)
log.info("Removed UPnP redirect for %s %d.", protocol, port)
self.upnp_redirects = []
return threads.deferToThread(threaded_unset_upnp)

View file

@ -9,7 +9,7 @@
import hashlib, random, struct, time, math, binascii
import argparse
from twisted.internet import defer
from twisted.internet import defer, error
import constants
import routingtable
import datastore
@ -142,7 +142,13 @@ class Node(object):
"""
# Prepare the underlying Kademlia protocol
if self.port is not None:
self._listeningPort = twisted.internet.reactor.listenUDP(self.port, self._protocol) #IGNORE:E1101
try:
self._listeningPort = twisted.internet.reactor.listenUDP(self.port, self._protocol)
except error.CannotListenError as e:
import traceback
log.error("Couldn't bind to port %d. %s", self.port, traceback.format_exc())
raise ValueError("%s lbrynet may already be running." % str(e))
#IGNORE:E1101
# Create temporary contact information for the list of addresses of known nodes
if knownNodeAddresses != None:
bootstrapContacts = []

View file

@ -326,15 +326,15 @@ class ShutDown(CommandHandler):
# return True, self._shut_down()
def _shut_down(self):
d = self.lbry_service.shut_down()
#d = self.lbry_service.shut_down()
def stop_reactor():
#def stop_reactor():
from twisted.internet import reactor
self.console.sendLine("Shutting down.")
reactor.stop()
d.addBoth(lambda _: stop_reactor())
return d
#d.addBoth(lambda _: stop_reactor())
return defer.succeed(True)
class ShutDownFactory(CommandHandlerFactory):
@ -609,17 +609,17 @@ class AddStream(CommandHandler):
NotImplementedError()
return choice_string
def _get_value_for_choice(self, input):
def _get_value_for_choice(self, choice_input):
choice = self.current_option.option_types[self.current_choice]
if choice.value == float:
try:
return float(input)
return float(choice_input)
except ValueError:
raise InvalidValueError()
elif choice.value == bool:
if input == "0":
if choice_input == "0":
return True
elif input == "1":
elif choice_input == "1":
return False
raise InvalidValueError()
raise NotImplementedError()
@ -727,7 +727,9 @@ class AddStreamFromLBRYcrdName(AddStreamFromHash):
def start(self, name):
self.loading_metadata_deferred = self._resolve_name(name)
self.loading_metadata_deferred.addCallback(lambda stream_hash: download_sd_blob(self.session, stream_hash, self.payment_rate_manager))
self.loading_metadata_deferred.addCallback(lambda stream_hash: download_sd_blob(self.session,
stream_hash,
self.payment_rate_manager))
self.loading_metadata_deferred.addCallback(self.sd_identifier.get_metadata_for_sd_blob)
AddStream.start(self)

View file

@ -3,7 +3,7 @@ from lbrynet.core.Session import LBRYSession
import os.path
import argparse
from yapsy.PluginManager import PluginManager
from twisted.internet import defer, threads, stdio, task
from twisted.internet import defer, threads, stdio, task, error
from lbrynet.lbrynet_console.ConsoleControl import ConsoleControl
from lbrynet.lbrynet_console.LBRYSettings import LBRYSettings
from lbrynet.lbryfilemanager.LBRYFileManager import LBRYFileManager
@ -194,7 +194,7 @@ class LBRYConsole():
if not os.path.exists(lbrycrdd_path_conf_path):
return ""
lbrycrdd_path_conf = open(lbrycrdd_path_conf_path)
lines = lbrycrdd_path_conf.readline()
lines = lbrycrdd_path_conf.readlines()
return lines
d = threads.deferToThread(get_lbrycrdd_path_conf_file)
@ -407,7 +407,12 @@ class LBRYConsole():
self.query_handlers,
self.session.peer_manager)
from twisted.internet import reactor
try:
self.lbry_server_port = reactor.listenTCP(self.peer_port, server_factory)
except error.CannotListenError as e:
import traceback
log.error("Couldn't bind to port %d. %s", self.peer_port, traceback.format_exc())
raise ValueError("%s lbrynet may already be running on your computer.", str(e))
return defer.succeed(True)
def stop_server(self):