chiark / gitweb /
wip
[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 client_cs = None
11
12 def set_client(ci,cs,pw):
13   global client_cs
14   global password
15   assert(client_cs is None)
16   client_cs = cs
17   c.client = ci
18   c.max_outstanding = cfg.getint(cs, 'max_requests_outstanding')
19   c.target_outstanding = cfg.getint(cs, 'target_requests_outstanding')
20   password = pw
21
22 def process_cfg():
23   global url
24   global max_requests_outstanding
25
26   process_cfg_common_always()
27   process_cfg_server()
28
29   try:
30     c.url = cfg.get('server','url')
31   except NoOptionError:
32     process_cfg_saddrs()
33     c.url = c.saddrs[0].url()
34
35   process_cfg_clients(set_client)
36
37   c.routes = cfg.get('virtual','routes')
38   c.max_queue_time = cfg.getint(client_cs, 'max_queue_time')
39   c.max_batch_up   = cfg.getint(client_cs, 'max_batch_up')
40   c.http_timeout   = cfg.getint(client_cs, 'http_timeout')
41   c.http_retry     = cfg.getint(client_cs, 'http_retry')
42
43   process_cfg_ipif(client_cs,
44                    (('local', 'client'),
45                     ('peer',  'server'),
46                     ('rnets', 'routes')))
47
48 outstanding = 0
49
50 def start_client():
51   global queue
52   global agent
53   queue = PacketQueue('up', c.max_queue_time)
54   agent = twisted.web.client.Agent(reactor, connectTimeout = c.http_timeout)
55
56 def outbound(packet, saddr, daddr):
57   #print('OUT ', saddr, daddr, repr(packet))
58   queue.append(packet)
59   check_outbound()
60
61 class ResponseConsumer(twisted.internet.protocol.Protocol):
62   def __init__(self, req):
63     self._req = req
64     self._ssd = SlipStreamDecoder(queue_inbound)
65     self._log(DBG.HTTP_CTRL, '__init__')
66
67   def _log(self, dflag, msg, **kwargs):
68     log_debug(dflag, 'RC ' + msg, idof=self._req, **kwargs)
69
70   def dataReceived(self, data):
71     self._log(DBG.HTTP_CTRL, 'dataReceived', d=data)
72     try:
73       self._ssd.inputdata(mime_translate(data))
74     except Exception as e:
75       self._asyncfailure(e)
76
77   def connectionMade(self):
78     self._log(DBG.HTTP_CTRL, 'connectionMade')
79
80   def connectionLost(self, reason):
81     self._log(DBG.HTTP_CTRL, 'connectionLost ' + str(reason))
82     if reason.check(twisted.web.client.ResponseDone):
83       try: self._ssd.flush()
84       except Exception as e:
85         self._asyncfailure(e)
86     else:
87       self._asyncfailure(reason)
88
89   def _asyncfailure(self, reason):
90     self._log(DBG.HTTP_CTRL, '_asyncFailure ' + str(reason))
91     req_err(self._req, reason)
92
93 class ErrorResponseConsumer(twisted.internet.protocol.Protocol):
94   def __init__(self, req, resp):
95     self._req = req
96     self._resp = resp
97
98     try:
99       self._phrase = resp.phrase.decode('utf-8')
100     except Exception:
101       self._phrase = repr(resp.phrase)
102
103     self._log(DBG.HTTP_CTRL, '__init__ %d %s' % (resp.code, self._phrase))
104
105   def _log(self, dflag, msg, **kwargs):
106     log_debug(dflag,'ERROR-RC '+msg, idof=self._req, **kwargs)
107
108   def connectionMade(self): self._m = ''
109   def dataReceived(self, data): self._m += data
110   def connectionLost(self, reason):
111     try:
112       mbody = self._m.decode('utf-8')
113     except Exception:
114       mbody = repr(self._m)
115     req_err(req,
116             "FAILED %d %s | %s | %s"
117             % (self._resp.code, self.phrase, mbody, str(reason)))
118
119 def req_ok(req, resp):
120   log_debug(DBG.HTTP_CTRL,
121             'req_ok %d %s %s' % (resp.code, repr(resp.phrase), str(resp)),
122             idof=req)
123   if resp.code == 200:
124     rc = ResponseConsumer(req)
125   else:
126     rc = ErrorResponseConsumer(req, resp)
127
128   resp.deliverBody(rc)
129
130 def req_err(req, err):
131   log_debug(DBG.HTTP_CTRL, 'req_err ' + str(err), idof=req)
132   print(err, file=sys.stderr)
133   reactor.callLater(c.http_retry, (lambda: req_fin(req)))
134
135 def req_fin(req):
136   global outstanding
137   outstanding -= 1
138   log_debug(DBG.HTTP_CTRL, 'req_fin OS=%d' % outstanding, idof=req)
139   check_outbound()
140
141 def check_outbound():
142   global outstanding
143
144   while True:
145     if                          outstanding >= c.max_outstanding   : break
146     if not queue.nonempty() and outstanding >= c.target_outstanding: break
147
148     d = b''
149     def moredata(s): nonlocal d; d += s
150     queue.process((lambda: len(d)),
151                   moredata,
152                   c.max_batch_up)
153     
154     d = mime_translate(d)
155
156     crlf = b'\r\n'
157     lf   =   b'\n'
158     mime = (b'--b'                                        + crlf +
159             b'Content-Type: text/plain; charset="utf-8"'  + crlf +
160             b'Content-Disposition: form-data; name="m"'   + crlf + crlf +
161             str(c.client)             .encode('ascii')    + crlf +
162             password                                      + crlf +
163             str(c.target_outstanding) .encode('ascii')    + crlf +
164           ((
165             b'--b'                                        + crlf +
166             b'Content-Type: application/octet-stream'     + crlf +
167             b'Content-Disposition: form-data; name="d"'   + crlf + crlf +
168             d                                             + crlf
169            ) if len(d) else b'')                               +
170             b'--b--'                                      + crlf)
171
172     #df = open('data.dump.dbg', mode='wb')
173     #df.write(mime)
174     #df.close()
175     # POST -use -c 'multipart/form-data; boundary="b"' http://localhost:8099/ <data.dump.dbg
176
177     log_debug(DBG.HTTP_FULL, 'requesting: ' + str(mime))
178
179     hh = { 'User-Agent': ['hippotat'],
180            'Content-Type': ['multipart/form-data; boundary="b"'],
181            'Content-Length': [str(len(mime))] }
182
183     bytesreader = io.BytesIO(mime)
184     producer = twisted.web.client.FileBodyProducer(bytesreader)
185
186     req = agent.request(b'POST',
187                         c.url,
188                         twisted.web.client.Headers(hh),
189                         producer)
190
191     outstanding += 1
192     log_debug(DBG.HTTP_CTRL, 'request OS=%d' % outstanding, idof=req, d=d)
193     req.addTimeout(c.http_timeout, reactor)
194     req.addCallback((lambda resp: req_ok(req, resp)))
195     req.addErrback((lambda err: req_err(req, err)))
196
197 common_startup()
198 process_cfg()
199 start_client()
200 start_ipif(c.ipif_command, outbound)
201 check_outbound()
202 common_run()