From 0a55558d9ec54e36dbd85d20ec5a54dcf1d23ff9 Mon Sep 17 00:00:00 2001 From: James Hilliard Date: Fri, 24 Nov 2017 23:08:58 -0600 Subject: [PATCH] Reconnect automatically when bitcoind connection times out --- jmclient/jmclient/jsonrpc.py | 56 ++++++++++++++++++++---------------- 1 file changed, 31 insertions(+), 25 deletions(-) diff --git a/jmclient/jmclient/jsonrpc.py b/jmclient/jmclient/jsonrpc.py index 39024d0..9575a4e 100644 --- a/jmclient/jmclient/jsonrpc.py +++ b/jmclient/jmclient/jsonrpc.py @@ -74,31 +74,37 @@ class JsonRpc(object): body = json.dumps(obj) - try: - self.conn.request("POST", "", body, headers) - response = self.conn.getresponse() - - if response.status == 401: - self.conn.close() - raise JsonRpcConnectionError( - "authentication for JSON-RPC failed") - - # All of the codes below are 'fine' from a JSON-RPC point of view. - if response.status not in [200, 404, 500]: - self.conn.close() - raise JsonRpcConnectionError("unknown error in JSON-RPC") - - data = response.read() - - return json.loads(data) - - except JsonRpcConnectionError as exc: - raise exc - except httplib.BadStatusLine: - return "CONNFAILURE" - except Exception as exc: - raise JsonRpcConnectionError("JSON-RPC connection failed. Err:" + - repr(exc)) + while True: + try: + self.conn.request("POST", "", body, headers) + response = self.conn.getresponse() + + if response.status == 401: + self.conn.close() + raise JsonRpcConnectionError( + "authentication for JSON-RPC failed") + + # All of the codes below are 'fine' from a JSON-RPC point of view. + if response.status not in [200, 404, 500]: + self.conn.close() + raise JsonRpcConnectionError("unknown error in JSON-RPC") + + data = response.read() + + return json.loads(data) + + except JsonRpcConnectionError as exc: + raise exc + except httplib.BadStatusLine: + return "CONNFAILURE" + except Exception as exc: + if str(exc) == "Connection reset by peer": + self.conn.connect() + continue + else: + raise JsonRpcConnectionError("JSON-RPC connection failed. Err:" + + repr(exc)) + break def call(self, method, params): """