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