3 from hippotatlib
import *
6 import twisted
.web
.client
10 class GeneralResponseConsumer(twisted
.internet
.protocol
.Protocol
):
11 def __init__(self
, cl
, req
, desc
):
16 def _log(self
, dflag
, msg
, **kwargs
):
17 self
._cl
.log(dflag
, '%s: %s' %
(self
._desc
, msg
), idof
=self
._req
, **kwargs
)
19 def connectionMade(self
):
20 self
._log(DBG
.HTTP_CTRL
, 'connectionMade')
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__')
29 def dataReceived(self
, data
):
30 self
._log(DBG
.HTTP
, 'dataReceived', d
=data
)
32 self
._ssd
.inputdata(data
)
33 except Exception as e
:
34 self
._handleexception()
36 def connectionLost(self
, reason
):
37 self
._log(DBG
.HTTP_CTRL
, 'connectionLost ' + str(reason
))
38 if not reason
.check(twisted
.web
.client
.ResponseDone
):
42 self
._log(DBG
.HTTP
, 'ResponseDone')
44 self
._cl
.req_fin(self
._req
)
45 except Exception as e
:
46 self
._handleexception()
47 self
._cl
.report_running()
49 def _handleexception(self
):
50 self
._latefailure(traceback
.format_exc())
52 def _latefailure(self
, reason
):
53 self
._log(DBG
.HTTP_CTRL
, '_latefailure ' + str(reason
))
54 self
._cl
.req_err(self
._req
, reason
)
56 class ErrorResponseConsumer(GeneralResponseConsumer
):
57 def __init__(self
, cl
, req
, resp
):
58 super().__init__(cl
, req
, 'ERROR-RC')
62 self
._phrase
= resp
.phrase
.decode('utf-8')
64 self
._phrase
= repr(resp
.phrase
)
65 self
._log(DBG
.HTTP_CTRL
, '__init__ %d %s' %
(resp
.code
, self
._phrase
))
67 def dataReceived(self
, data
):
68 self
._log(DBG
.HTTP_CTRL
, 'dataReceived ' + repr(data
))
71 def connectionLost(self
, reason
):
73 mbody
= self
._m
.decode('utf-8')
76 if not reason
.check(twisted
.web
.client
.ResponseDone
):
77 mbody
+= ' || ' + str(reason
)
78 self
._cl
.req_err(self
._req
,
80 %
(self
._resp
.code
, self
._phrase
, mbody
))
83 def __init__(cl
, c
,ss
,cs
):
86 cl
.desc
= '[%s %s] ' %
(ss
,cs
)
87 cl
.running_reported
= False
88 cl
.log_info('setting up')
90 def log_info(cl
, msg
):
91 log
.info(cl
.desc
+ msg
, dflag
=False)
93 def report_running(cl
):
94 if not cl
.running_reported
:
95 cl
.log_info('running OK')
96 cl
.running_reported
= True
98 def log(cl
, dflag
, msg
, **kwargs
):
99 log_debug(dflag
, cl
.desc
+ msg
, **kwargs
)
101 def log_outstanding(cl
):
102 cl
.log(DBG
.CTRL_DUMP
, 'OS %s' % cl
.outstanding
)
105 cl
.queue
= PacketQueue('up', cl
.c
.max_queue_time
)
106 cl
.agent
= twisted
.web
.client
.Agent(
107 reactor
, connectTimeout
= cl
.c
.http_timeout
)
109 def outbound(cl
, packet
, saddr
, daddr
):
110 #print('OUT ', saddr, daddr, repr(packet))
111 cl
.queue
.append(packet
)
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
)),
119 rc
= ResponseConsumer(cl
, req
)
121 rc
= ErrorResponseConsumer(cl
, req
, resp
)
124 # now rc is responsible for calling req_fin
126 def req_err(cl
, req
, err
):
127 # called when the Deferred fails, or (if it completes),
128 # later, by ResponsConsumer or ErrorResponsConsumer
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
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
)
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
)
148 def check_outbound(cl
):
150 if len(cl
.outstanding
) >= cl
.c
.max_outstanding
:
153 if (not cl
.queue
.nonempty() and
154 len(cl
.outstanding
) >= cl
.c
.target_requests_outstanding
):
158 def moredata(s
): nonlocal d
; d
+= s
159 cl
.queue
.process((lambda: len(d
)),
163 d
= mime_translate(d
)
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
+
177 b
'Content-Type: application/octet-stream' + crlf
+
178 b
'Content-Disposition: form-data; name="d"' + crlf
+ crlf
+
180 ) if len(d
) else b
'') +
183 #df = open('data.dump.dbg', mode='wb')
186 # POST -use -c 'multipart/form-data; boundary="b"' http://localhost:8099/ <data.dump.dbg
188 cl
.log(DBG
.HTTP_FULL
, 'requesting: ' + str(mime
))
190 hh
= { 'User-Agent': ['hippotat'],
191 'Content-Type': ['multipart/form-data; boundary="b"'],
192 'Content-Length': [str(len(mime
))] }
194 bytesreader
= io
.BytesIO(mime
)
195 producer
= twisted
.web
.client
.FileBodyProducer(bytesreader
)
197 req
= cl
.agent
.request(b
'POST',
199 twisted
.web
.client
.Headers(hh
),
202 cl
.outstanding
[req
] = len(d
)
203 cl
.log(DBG
.HTTP_CTRL
,
204 'request OS=%d' %
len(cl
.outstanding
),
206 req
.addTimeout(cl
.c
.http_timeout
, reactor
)
207 req
.addCallback(partial(cl
.req_ok
, req
))
208 req
.addErrback(partial(cl
.req_err
, req
))
214 def process_cfg(putative_servers
, putative_clients
):
217 for ss
in putative_servers
.values():
218 for (ci
,cs
) in putative_clients
.items():
221 sections
= cfg_process_client_common(c
,ss
,cs
,ci
)
222 if not sections
: continue
224 def srch(getter
,key
): return cfg_search(getter
,key
,sections
)
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')
233 try: c
.url
= srch(cfg
.get
,'url')
234 except NoOptionError
:
235 cfg_process_saddrs(c
, ss
)
236 c
.url
= c
.saddrs
[0].url()
240 cfg_process_vaddr(c
,ss
)
246 ('rnets','vroutes')))
248 clients
.append(Client(c
,ss
,cs
))
250 common_startup(process_cfg
)
254 cl
.ipif
= start_ipif(cl
.c
.ipif_command
, cl
.outbound
)