ownsource does dpkg stuff
[hippotat] / hippotat
CommitLineData
c55f394e
IJ
1#!/usr/bin/python3
2
5a37bac8 3from hippotatlib import *
c55f394e 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)
909e0ff3 26 self._ssd = SlipStreamDecoder(ssddesc, partial(queue_inbound, cl.ipif))
0accf0d3 27 self._log(DBG.HTTP_CTRL, '__init__')
bd9e77fb 28
62b51bcf 29 def dataReceived(self, data):
380ed56c 30 self._log(DBG.HTTP, 'dataReceived', d=data)
9b65cdd4 31 try:
02cdcb52 32 self._ssd.inputdata(data)
9b65cdd4 33 except Exception as e:
eedc8b30 34 self._handleexception()
ccd371b3 35
62b51bcf 36 def connectionLost(self, reason):
15407d80 37 self._log(DBG.HTTP_CTRL, 'connectionLost ' + str(reason))
765aba55 38 if not reason.check(twisted.web.client.ResponseDone):
0accf0d3 39 self.latefailure()
765aba55
IJ
40 return
41 try:
380ed56c 42 self._log(DBG.HTTP, 'ResponseDone')
765aba55 43 self._ssd.flush()
74934d63 44 self._cl.req_fin(self._req)
765aba55 45 except Exception as e:
eedc8b30 46 self._handleexception()
909e0ff3 47 self._cl.report_running()
eedc8b30
IJ
48
49 def _handleexception(self):
0accf0d3 50 self._latefailure(traceback.format_exc())
33932420 51
0accf0d3 52 def _latefailure(self, reason):
380ed56c 53 self._log(DBG.HTTP_CTRL, '_latefailure ' + str(reason))
74934d63 54 self._cl.req_err(self._req, reason)
bd9e77fb 55
74934d63 56class ErrorResponseConsumer(GeneralResponseConsumer):
c7fb640e
IJ
57 def __init__(self, cl, req, resp):
58 super().__init__(cl, req, 'ERROR-RC')
6e4af0a2 59 self._resp = resp
0accf0d3 60 self._m = b''
6e4af0a2
IJ
61 try:
62 self._phrase = resp.phrase.decode('utf-8')
63 except Exception:
64 self._phrase = repr(resp.phrase)
6e4af0a2
IJ
65 self._log(DBG.HTTP_CTRL, '__init__ %d %s' % (resp.code, self._phrase))
66
765aba55
IJ
67 def dataReceived(self, data):
68 self._log(DBG.HTTP_CTRL, 'dataReceived ' + repr(data))
69 self._m += data
70
6e4af0a2
IJ
71 def connectionLost(self, reason):
72 try:
73 mbody = self._m.decode('utf-8')
74 except Exception:
75 mbody = repr(self._m)
765aba55
IJ
76 if not reason.check(twisted.web.client.ResponseDone):
77 mbody += ' || ' + str(reason)
74934d63 78 self._cl.req_err(self._req,
765aba55
IJ
79 "FAILED %d %s | %s"
80 % (self._resp.code, self._phrase, mbody))
6e4af0a2 81
c7fb640e
IJ
82class Client():
83 def __init__(cl, c,ss,cs):
84 cl.c = c
85 cl.outstanding = { }
86 cl.desc = '[%s %s] ' % (ss,cs)
909e0ff3
IJ
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
c7fb640e
IJ
97
98 def log(cl, dflag, msg, **kwargs):
99 log_debug(dflag, cl.desc + msg, **kwargs)
100
101 def log_outstanding(cl):
c7f134ce 102 cl.log(DBG.CTRL_DUMP, 'OS %s' % cl.outstanding)
c7fb640e
IJ
103
104 def start(cl):
8d374606 105 cl.queue = PacketQueue('up', cl.c.max_queue_time)
c7fb640e 106 cl.agent = twisted.web.client.Agent(
8d374606 107 reactor, connectTimeout = cl.c.http_timeout)
c7fb640e
IJ
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,
5dd3275b
IJ
116 'req_ok %d %s %s' % (resp.code, repr(resp.phrase), str(resp)),
117 idof=req)
8d374606
IJ
118 if resp.code == 200:
119 rc = ResponseConsumer(cl, req)
120 else:
121 rc = ErrorResponseConsumer(cl, req, resp)
5dd3275b 122
8d374606
IJ
123 resp.deliverBody(rc)
124 # now rc is responsible for calling req_fin
7b07f0b5 125
c7fb640e
IJ
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)
c7f134ce
IJ
134 if not isinstance(cl.outstanding[req], int):
135 raise RuntimeError('[%#x] previously %s' %
136 (id(req), cl.outstanding[req]))
c7fb640e
IJ
137 cl.outstanding[req] = err
138 cl.log_outstanding()
8d374606 139 reactor.callLater(cl.c.http_retry, partial(cl.req_fin, req))
c7fb640e
IJ
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]
c7f134ce 145 cl.log(DBG.HTTP_CTRL, 'req_fin OS=%d' % len(cl.outstanding), idof=req)
c7fb640e
IJ
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
c7f134ce
IJ
153 if (not cl.queue.nonempty() and
154 len(cl.outstanding) >= cl.c.target_requests_outstanding):
c7fb640e
IJ
155 break
156
157 d = b''
158 def moredata(s): nonlocal d; d += s
c7f134ce 159 cl.queue.process((lambda: len(d)),
c7fb640e
IJ
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 +
c7f134ce
IJ
172 str(cl.c.target_requests_outstanding)
173 .encode('ascii') + crlf +
c7fb640e
IJ
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
c7f134ce 197 req = cl.agent.request(b'POST',
c7fb640e
IJ
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
212clients = [ ]
213
214def 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
8d374606 221 sections = cfg_process_client_common(c,ss,cs,ci)
c7fb640e
IJ
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')
f754eec4 230 c.max_queue_time = srch(cfg.getint, 'max_queue_time')
c7fb640e
IJ
231 c.vroutes = srch(cfg.get, 'vroutes')
232
c7fb640e
IJ
233 try: c.url = srch(cfg.get,'url')
234 except NoOptionError:
8d374606 235 cfg_process_saddrs(c, ss)
c7fb640e
IJ
236 c.url = c.saddrs[0].url()
237
8d374606
IJ
238 c.client = ci
239
240 cfg_process_vaddr(c,ss)
241
242 cfg_process_ipif(c,
c7fb640e
IJ
243 sections,
244 (('local','client'),
245 ('peer', 'vaddr'),
246 ('rnets','vroutes')))
247
248 clients.append(Client(c,ss,cs))
0accf0d3 249
5510890e 250common_startup(process_cfg)
c7fb640e
IJ
251
252for cl in clients:
253 cl.start()
909e0ff3 254 cl.ipif = start_ipif(cl.c.ipif_command, cl.outbound)
c7fb640e
IJ
255 cl.check_outbound()
256
034284c3 257common_run()