chiark / gitweb /
wip new config
[hippotat.git] / client
diff --git a/client b/client
index 3e3890f9b4cfe34e918ec9816d91f47a7cc34eca..e5d4e0005092b3e7ebf842788c17d44145bfa7c4 100755 (executable)
--- a/client
+++ b/client
@@ -5,6 +5,8 @@ from hippotat import *
 import twisted.web
 import twisted.web.client
 
+import io
+
 client_cs = None
 
 def set_client(ci,cs,pw):
@@ -35,15 +37,19 @@ def process_cfg():
   c.routes = cfg.get('virtual','routes')
   c.max_queue_time = cfg.getint(client_cs, 'max_queue_time')
   c.max_batch_up   = cfg.getint(client_cs, 'max_batch_up')
-  c.http_timeout   = cfg.getint(client_cs, 'http_timeout')
   c.http_retry     = cfg.getint(client_cs, 'http_retry')
+  c.http_timeout = (cfg.getint(client_cs, 'http_timeout') +
+                    cfg.getint(client_cs, 'http_timeout_grace'))
 
   process_cfg_ipif(client_cs,
                    (('local', 'client'),
                     ('peer',  'server'),
                     ('rnets', 'routes')))
 
-outstanding = 0
+outstanding = { }
+
+def log_outstanding():
+  log_debug(DBG.CTRL_DUMP, 'OS %s' % outstanding)
 
 def start_client():
   global queue
@@ -56,44 +62,121 @@ def outbound(packet, saddr, daddr):
   queue.append(packet)
   check_outbound()
 
-class ResponseConsumer(twisted.internet.protocol.Protocol):
-  def __init__(self):
-    self._ssd = SlipStreamDecoder(queue_inbound)
+class GeneralResponseConsumer(twisted.internet.protocol.Protocol):
+  def __init__(self, req, desc):
+    self._req = req
+    self._desc = desc
+
+  def _log(self, dflag, msg, **kwargs):
+    log_debug(dflag, '%s: %s' % (self._desc, msg), idof=self._req, **kwargs)
+
+  def connectionMade(self):
+    self._log(DBG.HTTP_CTRL, 'connectionMade')
+
+class ResponseConsumer(GeneralResponseConsumer):
+  def __init__(self, req):
+    super().__init__(req, 'RC')
+    ssddesc = '[%s] %s' % (id(req), self._desc)
+    self._ssd = SlipStreamDecoder(ssddesc, queue_inbound)
+    self._log(DBG.HTTP_CTRL, '__init__')
+
   def dataReceived(self, data):
-    try: self._ssd.inputdata(mime_translate(data))
-    except Exception as e: asyncfailure(e)
-  def connectionMade(self): pass
-  def connectionLost(self, reason):
-    if isinstance(reason, twisted.internet.error.ConnectionDone):
-      try: self._ssd.flush()
-      except Exception as e: asyncfailure(e)
-    else:
-      asyncfailure(reason)
+    self._log(DBG.HTTP, 'dataReceived', d=data)
+    try:
+      self._ssd.inputdata(data)
+    except Exception as e:
+      self._handleexception()
 
-def req_ok(resp):
-  resp.deliverBody(ResponseConsumer())
-  req_fin()
+  def connectionLost(self, reason):
+    self._log(DBG.HTTP_CTRL, 'connectionLost ' + str(reason))
+    if not reason.check(twisted.web.client.ResponseDone):
+      self.latefailure()
+      return
+    try:
+      self._log(DBG.HTTP, 'ResponseDone')
+      self._ssd.flush()
+      req_fin(self._req)
+    except Exception as e:
+      self._handleexception()
+
+  def _handleexception(self):
+    self._latefailure(traceback.format_exc())
+
+  def _latefailure(self, reason):
+    self._log(DBG.HTTP_CTRL, '_latefailure ' + str(reason))
+    req_err(self._req, reason)
+
+class ErrorResponseConsumer(twisted.internet.protocol.Protocol):
+  def __init__(self, req, resp):
+    super().__init__(req, 'ERROR-RC')
+    self._resp = resp
+    self._m = b''
+    try:
+      self._phrase = resp.phrase.decode('utf-8')
+    except Exception:
+      self._phrase = repr(resp.phrase)
+    self._log(DBG.HTTP_CTRL, '__init__ %d %s' % (resp.code, self._phrase))
 
-def req_err(err):
-  print(err, file=sys.stderr)
-  reactor.callLater(c.http_retry, req_fin)
+  def dataReceived(self, data):
+    self._log(DBG.HTTP_CTRL, 'dataReceived ' + repr(data))
+    self._m += data
 
-def req_fin(*args):
-  global outstanding
-  outstanding -= 1
+  def connectionLost(self, reason):
+    try:
+      mbody = self._m.decode('utf-8')
+    except Exception:
+      mbody = repr(self._m)
+    if not reason.check(twisted.web.client.ResponseDone):
+      mbody += ' || ' + str(reason)
+    req_err(self._req,
+            "FAILED %d %s | %s"
+            % (self._resp.code, self._phrase, mbody))
+
+def req_ok(req, resp):
+  log_debug(DBG.HTTP_CTRL,
+            'req_ok %d %s %s' % (resp.code, repr(resp.phrase), str(resp)),
+            idof=req)
+  if resp.code == 200:
+    rc = ResponseConsumer(req)
+  else:
+    rc = ErrorResponseConsumer(req, resp)
+
+  resp.deliverBody(rc)
+  # now rc is responsible for calling req_fin
+
+def req_err(req, err):
+  # called when the Deferred fails, or (if it completes),
+  # later, by ResponsConsumer or ErrorResponsConsumer
+  try:
+    log_debug(DBG.HTTP_CTRL, 'req_err ' + str(err), idof=req)
+    if isinstance(err, twisted.python.failure.Failure):
+      err = err.getTraceback()
+    print('[%#x] %s' % (id(req), err), file=sys.stderr)
+    if not isinstance(outstanding[req], int):
+      raise RuntimeError('[%#x] previously %s' % (id(req), outstanding[req]))
+    outstanding[req] = err
+    log_outstanding()
+    reactor.callLater(c.http_retry, partial(req_fin, req))
+  except Exception as e:
+    crash(traceback.format_exc() + '\n----- handling -----\n' + err)
+
+def req_fin(req):
+  del outstanding[req]
+  log_debug(DBG.HTTP_CTRL, 'req_fin OS=%d' % len(outstanding), idof=req)
   check_outbound()
 
-def asyncfailure(reason):
-  global outstanding
-  outstanding += 1
-  req_err(reason)
+class Errb:
+  def __init__(self, req):
+    self._req = req
+  def call(self, err):
+    req_err(self._req, err)
 
 def check_outbound():
   global outstanding
 
   while True:
-    if                          outstanding >= c.max_outstanding   : break
-    if not queue.nonempty() and outstanding >= c.target_outstanding: break
+    if                          len(outstanding) >= c.max_outstanding   : break
+    if not queue.nonempty() and len(outstanding) >= c.target_outstanding: break
 
     d = b''
     def moredata(s): nonlocal d; d += s
@@ -101,6 +184,8 @@ def check_outbound():
                   moredata,
                   c.max_batch_up)
     
+    d = mime_translate(d)
+
     crlf = b'\r\n'
     lf   =   b'\n'
     mime = (b'--b'                                        + crlf +
@@ -109,11 +194,12 @@ def check_outbound():
             str(c.client)             .encode('ascii')    + crlf +
             password                                      + crlf +
             str(c.target_outstanding) .encode('ascii')    + crlf +
+            str(c.http_timeout)       .encode('ascii')    + crlf +
           ((
             b'--b'                                        + crlf +
             b'Content-Type: application/octet-stream'     + crlf +
             b'Content-Disposition: form-data; name="d"'   + crlf + crlf +
-            mime_translate(d)                             + crlf
+            d                                             + crlf
            ) if len(d) else b'')                               +
             b'--b--'                                      + crlf)
 
@@ -127,15 +213,24 @@ def check_outbound():
     hh = { 'User-Agent': ['hippotat'],
            'Content-Type': ['multipart/form-data; boundary="b"'],
            'Content-Length': [str(len(mime))] }
+
+    bytesreader = io.BytesIO(mime)
+    producer = twisted.web.client.FileBodyProducer(bytesreader)
+
     req = agent.request(b'POST',
                         c.url,
-                        twisted.web.client.Headers(hh))
+                        twisted.web.client.Headers(hh),
+                        producer)
+
+    outstanding[req] = len(d)
+    log_debug(DBG.HTTP_CTRL, 'request OS=%d' % len(outstanding), idof=req, d=d)
     req.addTimeout(c.http_timeout, reactor)
-    req.addCallbacks(req_ok, req_err)
-    outstanding += 1
+    req.addCallback(partial(req_ok, req))
+    req.addErrback(partial(req_err, req))
+
+  log_outstanding()
 
-common_startup()
-process_cfg()
+common_startup(process_cfg)
 start_client()
 start_ipif(c.ipif_command, outbound)
 check_outbound()