it pings!
[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
034284c3 10client_cs = None
88487243
IJ
11
12def set_client(ci,cs,pw):
034284c3 13 global client_cs
88487243 14 global password
034284c3
IJ
15 assert(client_cs is None)
16 client_cs = cs
17 c.client = ci
88487243 18 c.max_outstanding = cfg.getint(cs, 'max_requests_outstanding')
7b07f0b5 19 c.target_outstanding = cfg.getint(cs, 'target_requests_outstanding')
88487243
IJ
20 password = pw
21
87a7c0c7
IJ
22def process_cfg():
23 global url
24 global max_requests_outstanding
c55f394e 25
87a7c0c7 26 process_cfg_common_always()
88487243
IJ
27 process_cfg_server()
28
29 try:
30 c.url = cfg.get('server','url')
31 except NoOptionError:
32 process_cfg_saddrs()
84e763c7 33 c.url = c.saddrs[0].url()
88487243
IJ
34
35 process_cfg_clients(set_client)
87a7c0c7 36
ca732796 37 c.routes = cfg.get('virtual','routes')
7b07f0b5
IJ
38 c.max_queue_time = cfg.getint(client_cs, 'max_queue_time')
39 c.max_batch_up = cfg.getint(client_cs, 'max_batch_up')
ff613365 40 c.http_timeout = cfg.getint(client_cs, 'http_timeout')
4edf77a3 41 c.http_retry = cfg.getint(client_cs, 'http_retry')
034284c3
IJ
42
43 process_cfg_ipif(client_cs,
44 (('local', 'client'),
45 ('peer', 'server'),
46 ('rnets', 'routes')))
47
0accf0d3
IJ
48outstanding = { }
49
50def log_outstanding():
51 log_debug(DBG.CTRL_DUMP, 'OS %s' % outstanding)
ca732796
IJ
52
53def start_client():
54 global queue
7b07f0b5 55 global agent
297b3ebf 56 queue = PacketQueue('up', c.max_queue_time)
7b07f0b5 57 agent = twisted.web.client.Agent(reactor, connectTimeout = c.http_timeout)
ca732796 58
034284c3 59def outbound(packet, saddr, daddr):
ca732796
IJ
60 #print('OUT ', saddr, daddr, repr(packet))
61 queue.append(packet)
62 check_outbound()
63
0accf0d3
IJ
64class GeneralResponseConsumer(twisted.internet.protocol.Protocol):
65 def __init__(self, req, desc):
8b62cd2c 66 self._req = req
0accf0d3 67 self._desc = desc
14c6d55c
IJ
68
69 def _log(self, dflag, msg, **kwargs):
0accf0d3
IJ
70 log_debug(dflag, '%s: %s' % (self._desc, msg), idof=self._req, **kwargs)
71
72 def connectionMade(self):
73 self._log(DBG.HTTP_CTRL, 'connectionMade')
74
75class 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__')
bd9e77fb 81
62b51bcf 82 def dataReceived(self, data):
9b65cdd4
IJ
83 self._log(DBG.HTTP_CTRL, 'dataReceived', d=data)
84 try:
02cdcb52 85 self._ssd.inputdata(data)
9b65cdd4 86 except Exception as e:
eedc8b30 87 self._handleexception()
ccd371b3 88
62b51bcf 89 def connectionLost(self, reason):
15407d80 90 self._log(DBG.HTTP_CTRL, 'connectionLost ' + str(reason))
765aba55 91 if not reason.check(twisted.web.client.ResponseDone):
0accf0d3 92 self.latefailure()
765aba55
IJ
93 return
94 try:
95 self._ssd.flush()
c13ee6e6 96 req_fin(self._req)
765aba55 97 except Exception as e:
eedc8b30
IJ
98 self._handleexception()
99
100 def _handleexception(self):
0accf0d3 101 self._latefailure(traceback.format_exc())
33932420 102
0accf0d3 103 def _latefailure(self, reason):
15407d80 104 self._log(DBG.HTTP_CTRL, '_asyncFailure ' + str(reason))
fd87d3f3 105 req_err(self._req, reason)
bd9e77fb 106
6e4af0a2
IJ
107class ErrorResponseConsumer(twisted.internet.protocol.Protocol):
108 def __init__(self, req, resp):
0accf0d3 109 super().__init__(req, 'ERROR-RC')
6e4af0a2 110 self._resp = resp
0accf0d3 111 self._m = b''
6e4af0a2
IJ
112 try:
113 self._phrase = resp.phrase.decode('utf-8')
114 except Exception:
115 self._phrase = repr(resp.phrase)
6e4af0a2
IJ
116 self._log(DBG.HTTP_CTRL, '__init__ %d %s' % (resp.code, self._phrase))
117
765aba55
IJ
118 def dataReceived(self, data):
119 self._log(DBG.HTTP_CTRL, 'dataReceived ' + repr(data))
120 self._m += data
121
6e4af0a2
IJ
122 def connectionLost(self, reason):
123 try:
124 mbody = self._m.decode('utf-8')
125 except Exception:
126 mbody = repr(self._m)
765aba55
IJ
127 if not reason.check(twisted.web.client.ResponseDone):
128 mbody += ' || ' + str(reason)
129 req_err(self._req,
130 "FAILED %d %s | %s"
131 % (self._resp.code, self._phrase, mbody))
6e4af0a2 132
8b62cd2c 133def req_ok(req, resp):
5dd3275b
IJ
134 log_debug(DBG.HTTP_CTRL,
135 'req_ok %d %s %s' % (resp.code, repr(resp.phrase), str(resp)),
136 idof=req)
6e4af0a2
IJ
137 if resp.code == 200:
138 rc = ResponseConsumer(req)
139 else:
140 rc = ErrorResponseConsumer(req, resp)
5dd3275b 141
8b62cd2c 142 resp.deliverBody(rc)
0accf0d3 143 # now rc is responsible for calling req_fin
7b07f0b5 144
fd87d3f3 145def req_err(req, err):
0accf0d3
IJ
146 # called when the Deferred fails, or (if it completes),
147 # later, by ResponsConsumer or ErrorResponsConsumer
e8ed0029
IJ
148 try:
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
156 log_outstanding()
c13ee6e6 157 reactor.callLater(c.http_retry, partial(req_fin, req))
e8ed0029
IJ
158 except Exception as e:
159 crash(traceback.format_exc() + '\n----- handling -----\n' + err)
7b07f0b5 160
60b58030 161def req_fin(req):
0accf0d3
IJ
162 del outstanding[req]
163 log_debug(DBG.HTTP_CTRL, 'req_fin OS=%d' % len(outstanding), idof=req)
4edf77a3
IJ
164 check_outbound()
165
c13ee6e6
IJ
166class Errb:
167 def __init__(self, req):
168 self._req = req
169 def call(self, err):
170 req_err(self._req, err)
171
ca732796 172def check_outbound():
84e763c7 173 global outstanding
4edf77a3 174
ca732796 175 while True:
0accf0d3
IJ
176 if len(outstanding) >= c.max_outstanding : break
177 if not queue.nonempty() and len(outstanding) >= c.target_outstanding: break
7b07f0b5
IJ
178
179 d = b''
84e763c7 180 def moredata(s): nonlocal d; d += s
7b07f0b5 181 queue.process((lambda: len(d)),
c0c90673 182 moredata,
7b07f0b5 183 c.max_batch_up)
7b07f0b5 184
fc0ba433
IJ
185 d = mime_translate(d)
186
7b07f0b5 187 crlf = b'\r\n'
60dc70f9 188 lf = b'\n'
5e234983
IJ
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 +
193 password + crlf +
194 str(c.target_outstanding) .encode('ascii') + crlf +
60dc70f9 195 ((
5e234983
IJ
196 b'--b' + crlf +
197 b'Content-Type: application/octet-stream' + crlf +
198 b'Content-Disposition: form-data; name="d"' + crlf + crlf +
fc0ba433 199 d + crlf
60dc70f9 200 ) if len(d) else b'') +
5e234983 201 b'--b--' + crlf)
ca732796 202
a518aa4b
IJ
203 #df = open('data.dump.dbg', mode='wb')
204 #df.write(mime)
205 #df.close()
534f07df 206 # POST -use -c 'multipart/form-data; boundary="b"' http://localhost:8099/ <data.dump.dbg
60dc70f9 207
297b3ebf 208 log_debug(DBG.HTTP_FULL, 'requesting: ' + str(mime))
4edf77a3 209
7b07f0b5 210 hh = { 'User-Agent': ['hippotat'],
b37c6b53
IJ
211 'Content-Type': ['multipart/form-data; boundary="b"'],
212 'Content-Length': [str(len(mime))] }
dd6665ee
IJ
213
214 bytesreader = io.BytesIO(mime)
215 producer = twisted.web.client.FileBodyProducer(bytesreader)
216
3dbadade 217 req = agent.request(b'POST',
7b07f0b5 218 c.url,
b37c6b53
IJ
219 twisted.web.client.Headers(hh),
220 producer)
47191df1 221
0accf0d3
IJ
222 outstanding[req] = len(d)
223 log_debug(DBG.HTTP_CTRL, 'request OS=%d' % len(outstanding), idof=req, d=d)
84e763c7 224 req.addTimeout(c.http_timeout, reactor)
c13ee6e6
IJ
225 req.addCallback(partial(req_ok, req))
226 req.addErrback(partial(req_err, req))
034284c3 227
0accf0d3
IJ
228 log_outstanding()
229
1321ad5f 230common_startup()
87a7c0c7 231process_cfg()
7b07f0b5 232start_client()
034284c3 233start_ipif(c.ipif_command, outbound)
4edf77a3 234check_outbound()
034284c3 235common_run()