From 7df6e99e285217c7141479f8396bfa46bf99140e Mon Sep 17 00:00:00 2001 From: Jimmy Kiselak Date: Mon, 19 Oct 2015 15:05:17 -0400 Subject: [PATCH] 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 --- lbrynet/core/Session.py | 40 ++++++++++++++-------- lbrynet/dht/node.py | 10 ++++-- lbrynet/lbrynet_console/ControlHandlers.py | 28 ++++++++------- lbrynet/lbrynet_console/LBRYConsole.py | 11 ++++-- 4 files changed, 57 insertions(+), 32 deletions(-) diff --git a/lbrynet/core/Session.py b/lbrynet/core/Session.py index b7c319c68..21fd4c979 100644 --- a/lbrynet/core/Session.py +++ b/lbrynet/core/Session.py @@ -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,8 +148,7 @@ 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)) + ds.append(defer.maybeDeferred(self._unset_upnp)) return defer.DeferredList(ds) def _try_upnp(self): @@ -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: - u.addportmapping(self.peer_port, 'TCP', u.lanaddr, self.peer_port, 'LBRY peer port', '') + 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: - u.addportmapping(self.dht_node_port, 'UDP', u.lanaddr, self.dht_node_port, 'LBRY DHT port', '') - self.upnp_redirects_set = True + 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.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) \ No newline at end of file diff --git a/lbrynet/dht/node.py b/lbrynet/dht/node.py index 9bd6b2848..1fae2e889 100644 --- a/lbrynet/dht/node.py +++ b/lbrynet/dht/node.py @@ -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 = [] diff --git a/lbrynet/lbrynet_console/ControlHandlers.py b/lbrynet/lbrynet_console/ControlHandlers.py index 7926ee180..94f81b793 100644 --- a/lbrynet/lbrynet_console/ControlHandlers.py +++ b/lbrynet/lbrynet_console/ControlHandlers.py @@ -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(): - from twisted.internet import reactor - self.console.sendLine("Shutting down.") - reactor.stop() + #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): @@ -538,7 +538,7 @@ class AddStream(CommandHandler): self.loading_failed = True log.error("An exception occurred attempting to load the stream descriptor: %s", err.getTraceback()) self.console.sendLine("An unexpected error occurred attempting to load the stream's metadata.\n" - "See console.log for further details.\n\n") + "See console.log for further details.\n\n") self.finished_deferred.callback(None) def _handle_metadata(self, metadata): @@ -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) diff --git a/lbrynet/lbrynet_console/LBRYConsole.py b/lbrynet/lbrynet_console/LBRYConsole.py index ed1274474..25a845346 100644 --- a/lbrynet/lbrynet_console/LBRYConsole.py +++ b/lbrynet/lbrynet_console/LBRYConsole.py @@ -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 - self.lbry_server_port = reactor.listenTCP(self.peer_port, server_factory) + 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):