wip fixes
[hippotat] / client
CommitLineData
c55f394e
IJ
1#!/usr/bin/python3
2
3from hippotat import *
4
c0c90673
IJ
5import twisted.web
6import twisted.web.client
7
dd6665ee
IJ
8import io
9
0accf0d3 10class GeneralResponseConsumer(twisted.internet.protocol.Protocol):
c7fb640e
IJ
11 def __init__(self, cl, req, desc):
12 self._cl = cl
8b62cd2c 13 self._req = req
0accf0d3 14 self._desc = desc
14c6d55c
IJ
15
16 def _log(self, dflag, msg, **kwargs):
74934d63 17 self._cl.log(dflag, '%s: %s' % (self._desc, msg), idof=self._req, **kwargs)
0accf0d3
IJ
18
19 def connectionMade(self):
20 self._log(DBG.HTTP_CTRL, 'connectionMade')
21
22class ResponseConsumer(GeneralResponseConsumer):
c7fb640e
IJ
23 def __init__(self, cl, req):
24 super().__init__(cl, req, 'RC')
0accf0d3 25 ssddesc = '[%s] %s' % (id(req), self._desc)
c7fb640e 26 self._ssd = SlipStreamDecoder(ssddesc, cl.queue_inbound)
0accf0d3 27 self._log(DBG.HTTP_CTRL, '__init__')
c7f134ce 28 self._success_reported = False
bd9e77fb 29
62b51bcf 30 def dataReceived(self, data):
380ed56c 31 self._log(DBG.HTTP, 'dataReceived', d=data)
9b65cdd4 32 try:
02cdcb52 33 self._ssd.inputdata(data)
9b65cdd4 34 except Exception as e:
eedc8b30 35 self._handleexception()
ccd371b3 36
62b51bcf 37 def connectionLost(self, reason):
15407d80 38 self._log(DBG.HTTP_CTRL, 'connectionLost ' + str(reason))
765aba55 39 if not reason.check(twisted.web.client.ResponseDone):
0accf0d3 40 self.latefailure()
765aba55
IJ
41 return
42 try:
380ed56c 43 self._log(DBG.HTTP, 'ResponseDone')
765aba55 44 self._ssd.flush()
74934d63 45 self._cl.req_fin(self._req)
765aba55 46 except Exception as e:
eedc8b30 47 self._handleexception()
c7f134ce
IJ
48 if not self._success_reported:
49 log.info(cl.desc + 'running OK', dflag=False)
50 self._success_reported = True
eedc8b30
IJ
51
52 def _handleexception(self):
0accf0d3 53 self._latefailure(traceback.format_exc())
33932420 54
0accf0d3 55 def _latefailure(self, reason):
380ed56c 56 self._log(DBG.HTTP_CTRL, '_latefailure ' + str(reason))
74934d63 57 self._cl.req_err(self._req, reason)
bd9e77fb 58
74934d63 59class ErrorResponseConsumer(GeneralResponseConsumer):
c7fb640e
IJ
60 def __init__(self, cl, req, resp):
61 super().__init__(cl, req, 'ERROR-RC')
6e4af0a2 62 self._resp = resp
0accf0d3 63 self._m = b''
6e4af0a2
IJ
64 try:
65 self._phrase = resp.phrase.decode('utf-8')
66 except Exception:
67 self._phrase = repr(resp.phrase)
6e4af0a2
IJ
68 self._log(DBG.HTTP_CTRL, '__init__ %d %s' % (resp.code, self._phrase))
69
765aba55
IJ
70 def dataReceived(self, data):
71 self._log(DBG.HTTP_CTRL, 'dataReceived ' + repr(data))
72 self._m += data
73
6e4af0a2
IJ
74 def connectionLost(self, reason):
75 try:
76 mbody = self._m.decode('utf-8')
77 except Exception:
78 mbody = repr(self._m)
765aba55
IJ
79 if not reason.check(twisted.web.client.ResponseDone):
80 mbody += ' || ' + str(reason)
74934d63 81 self._cl.req_err(self._req,
765aba55
IJ
82 "FAILED %d %s | %s"
83 % (self._resp.code, self._phrase, mbody))
6e4af0a2 84
c7fb640e
IJ
85class Client():
86 def __init__(cl, c,ss,cs):
87 cl.c = c
88 cl.outstanding = { }
89 cl.desc = '[%s %s] ' % (ss,cs)
c7f134ce 90 log.info(cl.desc + 'setting up', dflag=False)
c7fb640e
IJ
91
92 def log(cl, dflag, msg, **kwargs):
93 log_debug(dflag, cl.desc + msg, **kwargs)
94
95 def log_outstanding(cl):
c7f134ce 96 cl.log(DBG.CTRL_DUMP, 'OS %s' % cl.outstanding)
c7fb640e
IJ
97
98 def start(cl):
8d374606 99 cl.queue = PacketQueue('up', cl.c.max_queue_time)
c7fb640e 100 cl.agent = twisted.web.client.Agent(
8d374606 101 reactor, connectTimeout = cl.c.http_timeout)
c7fb640e
IJ
102
103 def outbound(cl, packet, saddr, daddr):
104 #print('OUT ', saddr, daddr, repr(packet))
105 cl.queue.append(packet)
106 cl.check_outbound()
107
108 def req_ok(cl, req, resp):
109 cl.log(DBG.HTTP_CTRL,
5dd3275b
IJ
110 'req_ok %d %s %s' % (resp.code, repr(resp.phrase), str(resp)),
111 idof=req)
8d374606
IJ
112 if resp.code == 200:
113 rc = ResponseConsumer(cl, req)
114 else:
115 rc = ErrorResponseConsumer(cl, req, resp)
5dd3275b 116
8d374606
IJ
117 resp.deliverBody(rc)
118 # now rc is responsible for calling req_fin
7b07f0b5 119
c7fb640e
IJ
120 def req_err(cl, req, err):
121 # called when the Deferred fails, or (if it completes),
122 # later, by ResponsConsumer or ErrorResponsConsumer
123 try:
124 cl.log(DBG.HTTP_CTRL, 'req_err ' + str(err), idof=req)
125 if isinstance(err, twisted.python.failure.Failure):
126 err = err.getTraceback()
127 print('[%#x] %s' % (id(req), err), file=sys.stderr)
c7f134ce
IJ
128 if not isinstance(cl.outstanding[req], int):
129 raise RuntimeError('[%#x] previously %s' %
130 (id(req), cl.outstanding[req]))
c7fb640e
IJ
131 cl.outstanding[req] = err
132 cl.log_outstanding()
8d374606 133 reactor.callLater(cl.c.http_retry, partial(cl.req_fin, req))
c7fb640e
IJ
134 except Exception as e:
135 crash(traceback.format_exc() + '\n----- handling -----\n' + err)
136
137 def req_fin(cl, req):
138 del cl.outstanding[req]
c7f134ce 139 cl.log(DBG.HTTP_CTRL, 'req_fin OS=%d' % len(cl.outstanding), idof=req)
c7fb640e
IJ
140 cl.check_outbound()
141
142 def check_outbound(cl):
143 while True:
144 if len(cl.outstanding) >= cl.c.max_outstanding:
145 break
146
c7f134ce
IJ
147 if (not cl.queue.nonempty() and
148 len(cl.outstanding) >= cl.c.target_requests_outstanding):
c7fb640e
IJ
149 break
150
151 d = b''
152 def moredata(s): nonlocal d; d += s
c7f134ce 153 cl.queue.process((lambda: len(d)),
c7fb640e
IJ
154 moredata,
155 cl.c.max_batch_up)
156
157 d = mime_translate(d)
158
159 crlf = b'\r\n'
160 lf = b'\n'
161 mime = (b'--b' + crlf +
162 b'Content-Type: text/plain; charset="utf-8"' + crlf +
163 b'Content-Disposition: form-data; name="m"' + crlf + crlf +
164 str(cl.c.client) .encode('ascii') + crlf +
165 cl.c.password + crlf +
c7f134ce
IJ
166 str(cl.c.target_requests_outstanding)
167 .encode('ascii') + crlf +
c7fb640e
IJ
168 str(cl.c.http_timeout) .encode('ascii') + crlf +
169 ((
170 b'--b' + crlf +
171 b'Content-Type: application/octet-stream' + crlf +
172 b'Content-Disposition: form-data; name="d"' + crlf + crlf +
173 d + crlf
174 ) if len(d) else b'') +
175 b'--b--' + crlf)
176
177 #df = open('data.dump.dbg', mode='wb')
178 #df.write(mime)
179 #df.close()
180 # POST -use -c 'multipart/form-data; boundary="b"' http://localhost:8099/ <data.dump.dbg
181
182 cl.log(DBG.HTTP_FULL, 'requesting: ' + str(mime))
183
184 hh = { 'User-Agent': ['hippotat'],
185 'Content-Type': ['multipart/form-data; boundary="b"'],
186 'Content-Length': [str(len(mime))] }
187
188 bytesreader = io.BytesIO(mime)
189 producer = twisted.web.client.FileBodyProducer(bytesreader)
190
c7f134ce 191 req = cl.agent.request(b'POST',
c7fb640e
IJ
192 cl.c.url,
193 twisted.web.client.Headers(hh),
194 producer)
195
196 cl.outstanding[req] = len(d)
197 cl.log(DBG.HTTP_CTRL,
198 'request OS=%d' % len(cl.outstanding),
199 idof=req, d=d)
200 req.addTimeout(cl.c.http_timeout, reactor)
201 req.addCallback(partial(cl.req_ok, req))
202 req.addErrback(partial(cl.req_err, req))
203
204 cl.log_outstanding()
205
206clients = [ ]
207
208def process_cfg(putative_servers, putative_clients):
209 global clients
210
211 for ss in putative_servers.values():
212 for (ci,cs) in putative_clients.items():
213 c = ConfigResults()
214
8d374606 215 sections = cfg_process_client_common(c,ss,cs,ci)
c7fb640e
IJ
216 if not sections: continue
217
218 def srch(getter,key): return cfg_search(getter,key,sections)
219
220 c.http_timeout += srch(cfg.getint, 'http_timeout_grace')
221 c.max_outstanding = srch(cfg.getint, 'max_requests_outstanding')
222 c.max_batch_up = srch(cfg.getint, 'max_batch_up')
223 c.http_retry = srch(cfg.getint, 'http_retry')
f754eec4 224 c.max_queue_time = srch(cfg.getint, 'max_queue_time')
c7fb640e
IJ
225 c.vroutes = srch(cfg.get, 'vroutes')
226
c7fb640e
IJ
227 try: c.url = srch(cfg.get,'url')
228 except NoOptionError:
8d374606 229 cfg_process_saddrs(c, ss)
c7fb640e
IJ
230 c.url = c.saddrs[0].url()
231
8d374606
IJ
232 c.client = ci
233
234 cfg_process_vaddr(c,ss)
235
236 cfg_process_ipif(c,
c7fb640e
IJ
237 sections,
238 (('local','client'),
239 ('peer', 'vaddr'),
240 ('rnets','vroutes')))
241
242 clients.append(Client(c,ss,cs))
0accf0d3 243
5510890e 244common_startup(process_cfg)
c7fb640e
IJ
245
246for cl in clients:
247 cl.start()
248 start_ipif(cl.c.ipif_command, cl.outbound)
249 cl.check_outbound()
250
034284c3 251common_run()