chiark / gitweb /
270901506c4caec692694c1fc70494033bb6b1aa
[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
66   def _log(self, dflag, msg, **kwargs):
67     log_debug(dflag, 'RC ' + msg, idof=self._req, **kwargs)
68
69   def dataReceived(self, data):
70     self._log(DBG.HTTP_CTRL, 'dataReceived', d=data)
71     try:
72       self._ssd.inputdata(mime_translate(data))
73     except Exception as e:
74       self._asyncfailure(e)
75
76   def connectionMade(self):
77     self._log(DBG.HTTP_CTRL, 'connectionMade', d=data)
78
79   def connectionLost(self, reason):
80     self._log(DBG.HTTP_CTRL, 'connectionLost', d=data)
81     if isinstance(reason, twisted.internet.error.ConnectionDone):
82       try: self._ssd.flush()
83       except Exception as e:
84         self._asyncfailure(e)
85     else:
86       self._asyncfailure(reason)
87
88   def _asyncfailure(self, reason):
89     global outstanding
90     outstanding += 1
91     req_err(self._req, reason)
92
93 def req_ok(req, resp):
94   resp.deliverBody(ResponseConsumer(req))
95   req_fin()
96
97 def req_err(req, err):
98   print(err, file=sys.stderr)
99   reactor.callLater(c.http_retry, req_fin)
100
101 def req_fin(*args):
102   global outstanding
103   outstanding -= 1
104   check_outbound()
105
106 def check_outbound():
107   global outstanding
108
109   while True:
110     if                          outstanding >= c.max_outstanding   : break
111     if not queue.nonempty() and outstanding >= c.target_outstanding: break
112
113     d = b''
114     def moredata(s): nonlocal d; d += s
115     queue.process((lambda: len(d)),
116                   moredata,
117                   c.max_batch_up)
118     
119     crlf = b'\r\n'
120     lf   =   b'\n'
121     mime = (b'--b'                                        + crlf +
122             b'Content-Type: text/plain; charset="utf-8"'  + crlf +
123             b'Content-Disposition: form-data; name="m"'   + crlf + crlf +
124             str(c.client)             .encode('ascii')    + crlf +
125             password                                      + crlf +
126             str(c.target_outstanding) .encode('ascii')    + crlf +
127           ((
128             b'--b'                                        + crlf +
129             b'Content-Type: application/octet-stream'     + crlf +
130             b'Content-Disposition: form-data; name="d"'   + crlf + crlf +
131             mime_translate(d)                             + crlf
132            ) if len(d) else b'')                               +
133             b'--b--'                                      + crlf)
134
135     #df = open('data.dump.dbg', mode='wb')
136     #df.write(mime)
137     #df.close()
138     # POST -use -c 'multipart/form-data; boundary="b"' http://localhost:8099/ <data.dump.dbg
139
140     log_debug(DBG.HTTP_FULL, 'requesting: ' + str(mime))
141
142     hh = { 'User-Agent': ['hippotat'],
143            'Content-Type': ['multipart/form-data; boundary="b"'],
144            'Content-Length': [str(len(mime))] }
145
146     bytesreader = io.BytesIO(mime)
147     producer = twisted.web.client.FileBodyProducer(bytesreader)
148
149     req = agent.request(b'POST',
150                         c.url,
151                         twisted.web.client.Headers(hh),
152                         producer)
153
154     log_debug(DBG.HTTP_CTRL, 'request', idof=req, d=d)
155     req.addTimeout(c.http_timeout, reactor)
156     req.addCallbacks((lambda resp: req_ok(req,resp)),
157                      (lambda resp: req_err(req,resp)))
158     outstanding += 1
159
160 common_startup()
161 process_cfg()
162 start_client()
163 start_ipif(c.ipif_command, outbound)
164 check_outbound()
165 common_run()