chiark / gitweb /
48c4f3f8768aa988483939bcbf04fd0253664feb
[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 = { }
49
50 def log_outstanding():
51   log_debug(DBG.CTRL_DUMP, 'OS %s' % outstanding)
52
53 def start_client():
54   global queue
55   global agent
56   queue = PacketQueue('up', c.max_queue_time)
57   agent = twisted.web.client.Agent(reactor, connectTimeout = c.http_timeout)
58
59 def outbound(packet, saddr, daddr):
60   #print('OUT ', saddr, daddr, repr(packet))
61   queue.append(packet)
62   check_outbound()
63
64 class GeneralResponseConsumer(twisted.internet.protocol.Protocol):
65   def __init__(self, req, desc):
66     self._req = req
67     self._desc = desc
68
69   def _log(self, dflag, msg, **kwargs):
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
75 class 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__')
81
82   def dataReceived(self, data):
83     self._log(DBG.HTTP_CTRL, 'dataReceived', d=data)
84     try:
85       self._ssd.inputdata(data)
86     except Exception as e:
87       self._handleexception()
88
89   def connectionLost(self, reason):
90     self._log(DBG.HTTP_CTRL, 'connectionLost ' + str(reason))
91     if not reason.check(twisted.web.client.ResponseDone):
92       self.latefailure()
93       return
94     try:
95       self._ssd.flush()
96       req_fin(req)
97     except Exception as e:
98       self._handleexception()
99
100   def _handleexception(self):
101     self._latefailure(traceback.format_exc())
102
103   def _latefailure(self, reason):
104     self._log(DBG.HTTP_CTRL, '_asyncFailure ' + str(reason))
105     req_err(self._req, reason)
106
107 class ErrorResponseConsumer(twisted.internet.protocol.Protocol):
108   def __init__(self, req, resp):
109     super().__init__(req, 'ERROR-RC')
110     self._resp = resp
111     self._m = b''
112     try:
113       self._phrase = resp.phrase.decode('utf-8')
114     except Exception:
115       self._phrase = repr(resp.phrase)
116     self._log(DBG.HTTP_CTRL, '__init__ %d %s' % (resp.code, self._phrase))
117
118   def dataReceived(self, data):
119     self._log(DBG.HTTP_CTRL, 'dataReceived ' + repr(data))
120     self._m += data
121
122   def connectionLost(self, reason):
123     try:
124       mbody = self._m.decode('utf-8')
125     except Exception:
126       mbody = repr(self._m)
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))
132
133 def req_ok(req, resp):
134   log_debug(DBG.HTTP_CTRL,
135             'req_ok %d %s %s' % (resp.code, repr(resp.phrase), str(resp)),
136             idof=req)
137   if resp.code == 200:
138     rc = ResponseConsumer(req)
139   else:
140     rc = ErrorResponseConsumer(req, resp)
141
142   resp.deliverBody(rc)
143   # now rc is responsible for calling req_fin
144
145 def req_err(req, err):
146   # called when the Deferred fails, or (if it completes),
147   # later, by ResponsConsumer or ErrorResponsConsumer
148   log_debug(DBG.HTTP_CTRL, 'req_err ' + str(err), idof=req)
149   if isinstance(err, twisted.python.failure.Failure):
150     err = err.getTraceback()
151   print(err, file=sys.stderr)
152   outstanding[req] = 'ERR'
153   log_outstanding()
154   reactor.callLater(c.http_retry, (lambda: req_fin(req)))
155
156 def req_fin(req):
157   del outstanding[req]
158   log_debug(DBG.HTTP_CTRL, 'req_fin OS=%d' % len(outstanding), idof=req)
159   check_outbound()
160
161 def check_outbound():
162   global outstanding
163
164   while True:
165     if                          len(outstanding) >= c.max_outstanding   : break
166     if not queue.nonempty() and len(outstanding) >= c.target_outstanding: break
167
168     d = b''
169     def moredata(s): nonlocal d; d += s
170     queue.process((lambda: len(d)),
171                   moredata,
172                   c.max_batch_up)
173     
174     d = mime_translate(d)
175
176     crlf = b'\r\n'
177     lf   =   b'\n'
178     mime = (b'--b'                                        + crlf +
179             b'Content-Type: text/plain; charset="utf-8"'  + crlf +
180             b'Content-Disposition: form-data; name="m"'   + crlf + crlf +
181             str(c.client)             .encode('ascii')    + crlf +
182             password                                      + crlf +
183             str(c.target_outstanding) .encode('ascii')    + crlf +
184           ((
185             b'--b'                                        + crlf +
186             b'Content-Type: application/octet-stream'     + crlf +
187             b'Content-Disposition: form-data; name="d"'   + crlf + crlf +
188             d                                             + crlf
189            ) if len(d) else b'')                               +
190             b'--b--'                                      + crlf)
191
192     #df = open('data.dump.dbg', mode='wb')
193     #df.write(mime)
194     #df.close()
195     # POST -use -c 'multipart/form-data; boundary="b"' http://localhost:8099/ <data.dump.dbg
196
197     log_debug(DBG.HTTP_FULL, 'requesting: ' + str(mime))
198
199     hh = { 'User-Agent': ['hippotat'],
200            'Content-Type': ['multipart/form-data; boundary="b"'],
201            'Content-Length': [str(len(mime))] }
202
203     bytesreader = io.BytesIO(mime)
204     producer = twisted.web.client.FileBodyProducer(bytesreader)
205
206     req = agent.request(b'POST',
207                         c.url,
208                         twisted.web.client.Headers(hh),
209                         producer)
210
211     outstanding[req] = len(d)
212     log_debug(DBG.HTTP_CTRL, 'request OS=%d' % len(outstanding), idof=req, d=d)
213     req.addTimeout(c.http_timeout, reactor)
214     req.addCallback((lambda resp: req_ok(req, resp)))
215     req.addErrback((lambda err: req_err(req, err)))
216
217   log_outstanding()
218
219 common_startup()
220 process_cfg()
221 start_client()
222 start_ipif(c.ipif_command, outbound)
223 check_outbound()
224 common_run()