6 import twisted.web.client
12 def set_client(ci,cs,pw):
15 assert(client_cs is None)
18 c.max_outstanding = cfg.getint(cs, 'max_requests_outstanding')
19 c.target_outstanding = cfg.getint(cs, 'target_requests_outstanding')
24 global max_requests_outstanding
26 process_cfg_common_always()
30 c.url = cfg.get('server','url')
33 c.url = c.saddrs[0].url()
35 process_cfg_clients(set_client)
37 c.routes = cfg.get('virtual','routes')
38 c.max_queue_time = cfg.getint(client_cs, 'max_queue_time')
39 c.max_batch_up = cfg.getint(client_cs, 'max_batch_up')
40 c.http_timeout = cfg.getint(client_cs, 'http_timeout')
41 c.http_retry = cfg.getint(client_cs, 'http_retry')
43 process_cfg_ipif(client_cs,
50 def log_outstanding():
51 log_debug(DBG.CTRL_DUMP, 'OS %s' % outstanding)
56 queue = PacketQueue('up', c.max_queue_time)
57 agent = twisted.web.client.Agent(reactor, connectTimeout = c.http_timeout)
59 def outbound(packet, saddr, daddr):
60 #print('OUT ', saddr, daddr, repr(packet))
64 class GeneralResponseConsumer(twisted.internet.protocol.Protocol):
65 def __init__(self, req, desc):
69 def _log(self, dflag, msg, **kwargs):
70 log_debug(dflag, '%s: %s' % (self._desc, msg), idof=self._req, **kwargs)
72 def connectionMade(self):
73 self._log(DBG.HTTP_CTRL, 'connectionMade')
75 class ResponseConsumer(GeneralResponseConsumer):
76 def __init__(self, req):
77 super().__init__(req, 'RC')
78 ssddesc = '[%s] %s' % (id(req), self._desc)
79 self._ssd = SlipStreamDecoder(ssddesc, queue_inbound)
80 self._log(DBG.HTTP_CTRL, '__init__')
82 def dataReceived(self, data):
83 self._log(DBG.HTTP_CTRL, 'dataReceived', d=data)
85 self._ssd.inputdata(data)
86 except Exception as e:
87 self._handleexception()
89 def connectionLost(self, reason):
90 self._log(DBG.HTTP_CTRL, 'connectionLost ' + str(reason))
91 if not reason.check(twisted.web.client.ResponseDone):
97 except Exception as e:
98 self._handleexception()
100 def _handleexception(self):
101 self._latefailure(traceback.format_exc())
103 def _latefailure(self, reason):
104 self._log(DBG.HTTP_CTRL, '_asyncFailure ' + str(reason))
105 req_err(self._req, reason)
107 class ErrorResponseConsumer(twisted.internet.protocol.Protocol):
108 def __init__(self, req, resp):
109 super().__init__(req, 'ERROR-RC')
113 self._phrase = resp.phrase.decode('utf-8')
115 self._phrase = repr(resp.phrase)
116 self._log(DBG.HTTP_CTRL, '__init__ %d %s' % (resp.code, self._phrase))
118 def dataReceived(self, data):
119 self._log(DBG.HTTP_CTRL, 'dataReceived ' + repr(data))
122 def connectionLost(self, reason):
124 mbody = self._m.decode('utf-8')
126 mbody = repr(self._m)
127 if not reason.check(twisted.web.client.ResponseDone):
128 mbody += ' || ' + str(reason)
131 % (self._resp.code, self._phrase, mbody))
133 def req_ok(req, resp):
134 log_debug(DBG.HTTP_CTRL,
135 'req_ok %d %s %s' % (resp.code, repr(resp.phrase), str(resp)),
138 rc = ResponseConsumer(req)
140 rc = ErrorResponseConsumer(req, resp)
143 # now rc is responsible for calling req_fin
145 def req_err(req, err):
146 # called when the Deferred fails, or (if it completes),
147 # later, by ResponsConsumer or ErrorResponsConsumer
149 log_debug(DBG.HTTP_CTRL, 'req_err ' + str(err), idof=req)
150 if isinstance(err, twisted.python.failure.Failure):
151 err = err.getTraceback()
152 print('[%#x] %s' % (id(req), err), file=sys.stderr)
153 if not isinstance(outstanding[req], int):
154 raise RuntimeError('[%#x] previously %s' % (id(req), outstanding[req]))
155 outstanding[req] = err
157 reactor.callLater(c.http_retry, partial(req_fin, req))
158 except Exception as e:
159 crash(traceback.format_exc() + '\n----- handling -----\n' + err)
163 log_debug(DBG.HTTP_CTRL, 'req_fin OS=%d' % len(outstanding), idof=req)
167 def __init__(self, req):
170 req_err(self._req, err)
172 def check_outbound():
176 if len(outstanding) >= c.max_outstanding : break
177 if not queue.nonempty() and len(outstanding) >= c.target_outstanding: break
180 def moredata(s): nonlocal d; d += s
181 queue.process((lambda: len(d)),
185 d = mime_translate(d)
189 mime = (b'--b' + crlf +
190 b'Content-Type: text/plain; charset="utf-8"' + crlf +
191 b'Content-Disposition: form-data; name="m"' + crlf + crlf +
192 str(c.client) .encode('ascii') + crlf +
194 str(c.target_outstanding) .encode('ascii') + crlf +
197 b'Content-Type: application/octet-stream' + crlf +
198 b'Content-Disposition: form-data; name="d"' + crlf + crlf +
200 ) if len(d) else b'') +
203 #df = open('data.dump.dbg', mode='wb')
206 # POST -use -c 'multipart/form-data; boundary="b"' http://localhost:8099/ <data.dump.dbg
208 log_debug(DBG.HTTP_FULL, 'requesting: ' + str(mime))
210 hh = { 'User-Agent': ['hippotat'],
211 'Content-Type': ['multipart/form-data; boundary="b"'],
212 'Content-Length': [str(len(mime))] }
214 bytesreader = io.BytesIO(mime)
215 producer = twisted.web.client.FileBodyProducer(bytesreader)
217 req = agent.request(b'POST',
219 twisted.web.client.Headers(hh),
222 outstanding[req] = len(d)
223 log_debug(DBG.HTTP_CTRL, 'request OS=%d' % len(outstanding), idof=req, d=d)
224 req.addTimeout(c.http_timeout, reactor)
225 req.addCallback(partial(req_ok, req))
226 req.addErrback(partial(req_err, req))
233 start_ipif(c.ipif_command, outbound)