Better error ignoring; logging

This commit is contained in:
Tony Garnock-Jones 2012-06-01 11:26:06 +01:00
parent 03a8d91ed8
commit 740ef15cbf
1 changed files with 23 additions and 10 deletions

View File

@ -15,6 +15,9 @@
## You should have received a copy of the GNU General Public License
## along with Hop. If not, see <http://www.gnu.org/licenses/>.
from __future__ import with_statement
import logging
import threading
import socket
@ -24,21 +27,25 @@ from dispatch import HopRelayMixin
class HopRelay(HopRelayMixin):
def __init__(self, in_ch, out_ch, ns = None, peer_address = None):
self.lock = threading.Lock()
self.in_ch = in_ch
self.out_ch = out_ch
self.peer_address = peer_address
self.thread = threading.Thread(target = self.relay_main)
self.namespace = ns if ns else namespace.default_namespace
self.lock = threading.Lock()
self.thread.start()
def write(self, x):
try:
self.lock.acquire()
sexp.write_sexp(self.out_ch, x)
self.out_ch.flush()
finally:
self.lock.release()
if self.out_ch:
with self.lock:
try:
sexp.write_sexp(self.out_ch, x)
self.out_ch.flush()
except Exception:
## Don't care, here - we assume that any write
## error will be reflected in the socket closing
## in a little while in any case.
pass
def error(self, message, details):
self.write(['error', message, details])
@ -69,19 +76,25 @@ class HopRelay(HopRelayMixin):
except EOFError:
pass
finally:
self.in_ch.close()
self.out_ch.close()
o = self.out_ch
i = self.in_ch
self.out_ch = None
self.in_ch = None
i.close()
o.close()
class TcpRelayServer:
def __init__(self, host = '0.0.0.0', port = 5671):
self.listen_address = (host, port)
self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.server_socket.bind((host, port))
self.server_socket.bind(self.listen_address)
self.server_socket.listen(4)
self.thread = threading.Thread(target = self.listen_main)
self.thread.start()
def listen_main(self):
logging.info("Accepting connections on %r" % (self.listen_address,))
while True:
conn, addr = self.server_socket.accept()
conn.send(sexp.format(['hop']))