Permalink
Browse files

Use httplib in merged-mine-proxy for keepalive

  • Loading branch information...
1 parent 7a1bd45 commit ffcbfdc1bc3444bdf653f0b5ca7b92c53e24425a @vinced vinced committed Oct 2, 2011
Showing with 39 additions and 23 deletions.
  1. +39 −23 contrib/merged-mine-proxy
View
@@ -12,15 +12,19 @@ import sys
import traceback
import json
import base64
+import socket
+
from datetime import datetime
-from twisted.internet import defer, reactor
-from twisted.web import server, resource, client
+from twisted.internet import defer, reactor, threads
+from twisted.web import server, resource
from twisted.internet.error import ConnectionRefusedError
import twisted.internet.error
from urlparse import urlsplit
+import httplib
+import thread
-__version__ = '0.2.1'
+__version__ = '0.2.2'
'''
merge-mine-proxy
@@ -50,6 +54,10 @@ logger.setLevel(logging.DEBUG)
def reverse_chunks(s, l):
return ''.join(reversed([s[x:x+l] for x in xrange(0, len(s), l)]))
+def getresponse(http, path, postdata, headers):
+ http.request(path, 'POST', postdata, headers)
+ return http.getresponse().read()
+
class Error(Exception):
def __init__(self, code, message, data=''):
if not isinstance(code, int):
@@ -72,12 +80,24 @@ class Proxy(object):
auth = None
if netloc.find('@') >= 0:
(auth, netloc) = netloc.split("@")
- self._url = "%s://%s/%s" % (schema, netloc, path)
+ if path == "":
+ path = "/"
+ self._url = "%s://%s%s" % (schema, netloc, path)
+ self._path = path
self._auth = auth
+ self._netloc = netloc
+ self._http = None
- @defer.inlineCallbacks
def callRemote(self, method, *params):
try:
+ if self._http is None:
+ (host, port) = self._netloc.split(":")
+ self._http = httplib.HTTPConnection(host, port)
+ try:
+ self._http.connect()
+ except socket.error:
+ raise httplib.HTTPException()
+
id_ = 0
headers = {
@@ -86,29 +106,25 @@ class Proxy(object):
if self._auth is not None:
headers['Authorization'] = 'Basic ' + base64.b64encode(self._auth)
resp = None
- try:
- resp = (yield client.getPage(
- url=self._url,
- method='POST',
- headers=headers,
- postdata=json.dumps({
- 'jsonrpc': '2.0',
- 'method': method,
- 'params': params,
- 'id': id_,
- }),
- ))
- except twisted.web.error.Error, e:
- resp = e.response
-
- resp = json.loads(resp)
+
+ postdata=json.dumps({
+ 'jsonrpc': '2.0',
+ 'method': method,
+ 'params': params,
+ 'id': id_,
+ })
+
+ content = getresponse(self._http, self._path, postdata, headers)
+
+ resp = json.loads(content)
if resp['id'] != id_:
raise ValueError('invalid id')
if 'error' in resp and resp['error'] is not None:
raise Error(resp['error']['code'], resp['error']['message'])
- defer.returnValue(resp['result'])
- except ConnectionRefusedError:
+ return resp['result']
+ except httplib.HTTPException:
+ self._http = None
logger.error("Could not connect to %s", self._url)
raise Error(-32099, u'Could not connect to backend', self._url)

0 comments on commit ffcbfdc

Please sign in to comment.