chiark / gitweb /
f26d46b8eff30e177a11c379bd81100249d6ee1e
[hippotat.git] / client
1 #!/usr/bin/python3
2
3 from hippotat import *
4
5 import twisted.web
6 import twisted.web.client
7
8 import io
9
10 class GeneralResponseConsumer(twisted.internet.protocol.Protocol):
11   def __init__(self, cl, req, desc):
12     self._cl = cl
13     self._req = req
14     self._desc = desc
15
16   def _log(self, dflag, msg, **kwargs):
17     self._cl.log(dflag, '%s: %s' % (self._desc, msg), idof=self._req, **kwargs)
18
19   def connectionMade(self):
20     self._log(DBG.HTTP_CTRL, 'connectionMade')
21
22 class ResponseConsumer(GeneralResponseConsumer):
23   def __init__(self, cl, req):
24     super().__init__(cl, req, 'RC')
25     ssddesc = '[%s] %s' % (id(req), self._desc)
26     self._ssd = SlipStreamDecoder(ssddesc, cl.queue_inbound)
27     self._log(DBG.HTTP_CTRL, '__init__')
28     self._success_reported = False
29
30   def dataReceived(self, data):
31     self._log(DBG.HTTP, 'dataReceived', d=data)
32     try:
33       self._ssd.inputdata(data)
34     except Exception as e:
35       self._handleexception()
36
37   def connectionLost(self, reason):
38     self._log(DBG.HTTP_CTRL, 'connectionLost ' + str(reason))
39     if not reason.check(twisted.web.client.ResponseDone):
40       self.latefailure()
41       return
42     try:
43       self._log(DBG.HTTP, 'ResponseDone')
44       self._ssd.flush()
45       self._cl.req_fin(self._req)
46     except Exception as e:
47       self._handleexception()
48     if not self._success_reported:
49       log.info(cl.desc + 'running OK', dflag=False)
50       self._success_reported = True
51
52   def _handleexception(self):
53     self._latefailure(traceback.format_exc())
54
55   def _latefailure(self, reason):
56     self._log(DBG.HTTP_CTRL, '_latefailure ' + str(reason))
57     self._cl.req_err(self._req, reason)
58
59 class ErrorResponseConsumer(GeneralResponseConsumer):
60   def __init__(self, cl, req, resp):
61     super().__init__(cl, req, 'ERROR-RC')
62     self._resp = resp
63     self._m = b''
64     try:
65       self._phrase = resp.phrase.decode('utf-8')
66     except Exception:
67       self._phrase = repr(resp.phrase)
68     self._log(DBG.HTTP_CTRL, '__init__ %d %s' % (resp.code, self._phrase))
69
70   def dataReceived(self, data):
71     self._log(DBG.HTTP_CTRL, 'dataReceived ' + repr(data))
72     self._m += data
73
74   def connectionLost(self, reason):
75     try:
76       mbody = self._m.decode('utf-8')
77     except Exception:
78       mbody = repr(self._m)
79     if not reason.check(twisted.web.client.ResponseDone):
80       mbody += ' || ' + str(reason)
81     self._cl.req_err(self._req,
82             "FAILED %d %s | %s"
83             % (self._resp.code, self._phrase, mbody))
84
85 class Client():
86   def __init__(cl, c,ss,cs):
87     cl.c = c
88     cl.outstanding = { }
89     cl.desc = '[%s %s] ' % (ss,cs)
90     log.info(cl.desc + 'setting up', dflag=False)
91
92   def log(cl, dflag, msg, **kwargs):
93     log_debug(dflag, cl.desc + msg, **kwargs)
94
95   def log_outstanding(cl):
96     cl.log(DBG.CTRL_DUMP, 'OS %s' % cl.outstanding)
97
98   def start(cl):
99     cl.queue = PacketQueue('up', cl.c.max_queue_time)
100     cl.agent = twisted.web.client.Agent(
101       reactor, connectTimeout = cl.c.http_timeout)
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,
110             'req_ok %d %s %s' % (resp.code, repr(resp.phrase), str(resp)),
111             idof=req)
112     if resp.code == 200:
113       rc = ResponseConsumer(cl, req)
114     else:
115       rc = ErrorResponseConsumer(cl, req, resp)
116
117     resp.deliverBody(rc)
118     # now rc is responsible for calling req_fin
119
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)
128       if not isinstance(cl.outstanding[req], int):
129         raise RuntimeError('[%#x] previously %s' %
130                            (id(req), cl.outstanding[req]))
131       cl.outstanding[req] = err
132       cl.log_outstanding()
133       reactor.callLater(cl.c.http_retry, partial(cl.req_fin, req))
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]
139     cl.log(DBG.HTTP_CTRL, 'req_fin OS=%d' % len(cl.outstanding), idof=req)
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
147       if (not cl.queue.nonempty() and
148           len(cl.outstanding) >= cl.c.target_requests_outstanding):
149         break
150
151       d = b''
152       def moredata(s): nonlocal d; d += s
153       cl.queue.process((lambda: len(d)),
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 +
166               str(cl.c.target_requests_outstanding)
167                                           .encode('ascii')  + crlf +
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
191       req = cl.agent.request(b'POST',
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
206 clients = [ ]
207
208 def 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
215       sections = cfg_process_client_common(c,ss,cs,ci)
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')
224       c.max_queue_time  = srch(cfg.getint, 'max_queue_time')
225       c.vroutes         = srch(cfg.get,    'vroutes')
226
227       try: c.url = srch(cfg.get,'url')
228       except NoOptionError:
229         cfg_process_saddrs(c, ss)
230         c.url = c.saddrs[0].url()
231
232       c.client = ci
233
234       cfg_process_vaddr(c,ss)
235
236       cfg_process_ipif(c,
237                        sections,
238                        (('local','client'),
239                         ('peer', 'vaddr'),
240                         ('rnets','vroutes')))
241
242       clients.append(Client(c,ss,cs))
243
244 common_startup(process_cfg)
245
246 for cl in clients:
247   cl.start()
248   start_ipif(cl.c.ipif_command, cl.outbound)
249   cl.check_outbound()
250
251 common_run()