From 740ef15cbf40d8a0031ad8774a10b3711f4fcd54 Mon Sep 17 00:00:00 2001 From: Tony Garnock-Jones Date: Fri, 1 Jun 2012 11:26:06 +0100 Subject: [PATCH] Better error ignoring; logging --- experiments/python/hop/relay.py | 33 +++++++++++++++++++++++---------- 1 file changed, 23 insertions(+), 10 deletions(-) diff --git a/experiments/python/hop/relay.py b/experiments/python/hop/relay.py index 6108afa..722fe56 100644 --- a/experiments/python/hop/relay.py +++ b/experiments/python/hop/relay.py @@ -15,6 +15,9 @@ ## You should have received a copy of the GNU General Public License ## along with Hop. If not, see . +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']))