1 import sys, os, threading, time, logging, select, queue, collections
4 log = logging.getLogger("ashd.serve")
6 seqlk = threading.Lock()
15 class closed(IOError):
17 super().__init__("The client has closed the connection.")
19 class reqthread(threading.Thread):
20 def __init__(self, *, name=None, **kw):
22 name = "Request handler %i" % reqseq()
23 super().__init__(name=name, **kw)
25 class wsgirequest(object):
26 def __init__(self, *, handler):
30 self.handler = handler
31 self.buffer = bytearray()
37 def writehead(self, status, headers):
43 def writedata(self, data):
44 self.buffer.extend(data)
49 raise Exception("Cannot send response body before starting response.")
51 self.writehead(self.status, self.headers)
53 def write(self, data):
58 self.handler.ckflush(self)
60 def startreq(self, status, headers, exc_info=None):
69 raise Exception("Can only start responding once.")
71 self.headers = headers
74 class handler(object):
75 def handle(self, request):
77 def ckflush(self, req):
78 while len(req.buffer) > 0:
79 rls, wls, els = select.select([], [req], [req])
85 def parseargs(cls, **args):
87 raise ValueError("unknown handler argument: " + next(iter(args)))
90 class single(handler):
93 def handle(self, req):
96 with perf.request(env) as reqevent:
97 respiter = req.handlewsgi(env, req.startreq)
101 reqevent.response([req.status, req.headers])
107 log.error("exception occurred when handling request", exc_info=True)
115 sys.stderr.write(" ")
116 sys.stderr.write(str(a))
118 sys.stderr.write("\n")
121 class freethread(handler):
124 def __init__(self, *, max=None, timeout=None, **kw):
125 super().__init__(**kw)
127 self.lk = threading.Lock()
128 self.tcond = threading.Condition(self.lk)
130 self.timeout = timeout
133 def parseargs(cls, *, max=None, abort=None, **args):
134 ret = super().parseargs(**args)
136 ret["max"] = int(max)
138 ret["timeout"] = int(abort)
141 def handle(self, req):
143 if self.max is not None:
144 if self.timeout is not None:
145 now = start = time.time()
146 while len(self.current) >= self.max:
147 self.tcond.wait(start + self.timeout - now)
149 if now - start > self.timeout:
152 while len(self.current) >= self.max:
154 th = reqthread(target=self.run, args=[req])
155 th.registered = False
157 while not th.registered:
162 th = threading.current_thread()
166 self.tcond.notify_all()
169 with perf.request(env) as reqevent:
170 respiter = req.handlewsgi(env, req.startreq)
171 for data in respiter:
174 reqevent.response([req.status, req.headers])
180 log.error("exception occurred when handling request", exc_info=True)
183 self.current.remove(th)
184 self.tcond.notify_all()
191 if len(self.current) > 0:
192 th = next(iter(self.current))
197 class threadpool(handler):
200 def __init__(self, *, max=25, qsz=100, timeout=None, **kw):
201 super().__init__(**kw)
203 self.clk = threading.Lock()
204 self.ccond = threading.Condition(self.clk)
205 self.queue = collections.deque()
209 self.qlk = threading.Lock()
210 self.qcond = threading.Condition(self.qlk)
213 self.timeout = timeout
216 def parseargs(cls, *, max=None, queue=None, abort=None, **args):
217 ret = super().parseargs(**args)
219 ret["max"] = int(max)
221 ret["qsz"] = int(queue)
223 ret["timeout"] = int(abort)
226 def handle(self, req):
229 if self.timeout is not None:
230 now = start = time.time()
231 while len(self.queue) >= self.qsz:
232 self.qcond.wait(start + self.timeout - now)
234 if now - start > self.timeout:
237 while len(self.current) >= self.qsz:
239 self.queue.append(req)
241 if len(self.waiting) < 1:
245 if len(self.current) < self.max:
246 th = reqthread(target=self.run)
247 th.registered = False
249 while not th.registered:
252 def handle1(self, req):
255 with perf.request(env) as reqevent:
256 respiter = req.handlewsgi(env, req.startreq)
257 for data in respiter:
260 reqevent.response([req.status, req.headers])
266 log.error("exception occurred when handling request", exc_info=True)
270 th = threading.current_thread()
274 self.ccond.notify_all()
277 start = now = time.time()
279 while len(self.queue) < 1:
280 if len(self.waiting) >= self.waitlimit and now - self.wlstart >= timeout:
284 if len(self.waiting) == self.waitlimit:
286 self.qcond.wait(start + timeout - now)
288 self.waiting.remove(th)
290 if now - start > timeout:
292 req = self.queue.popleft()
299 self.current.remove(th)
304 if len(self.current) > 0:
305 th = next(iter(self.current))
310 class resplex(handler):
313 def __init__(self, *, max=None, **kw):
314 super().__init__(**kw)
316 self.lk = threading.Lock()
317 self.tcond = threading.Condition(self.lk)
319 self.cqueue = queue.Queue(5)
320 self.cnpipe = os.pipe()
321 self.rthread = reqthread(name="Response thread", target=self.handle2)
325 def parseargs(cls, *, max=None, **args):
326 ret = super().parseargs(**args)
328 ret["max"] = int(max)
331 def ckflush(self, req):
332 raise Exception("resplex handler does not support the write() function")
334 def handle(self, req):
336 if self.max is not None:
337 while len(self.current) >= self.max:
339 th = reqthread(target=self.handle1, args=[req])
340 th.registered = False
342 while not th.registered:
345 def handle1(self, req):
347 th = threading.current_thread()
351 self.tcond.notify_all()
354 respobj = req.handlewsgi(env, req.startreq)
355 respiter = iter(respobj)
357 log.error("request handler returned without calling start_request")
358 if hasattr(respiter, "close"):
362 self.cqueue.put((req, respiter))
363 os.write(self.cnpipe[1], b" ")
367 self.current.remove(th)
368 self.tcond.notify_all()
372 log.error("exception occurred when handling request", exc_info=True)
383 respiter = current[req]
385 if respiter is not None and hasattr(respiter, "close"):
388 log.error("exception occurred when closing iterator", exc_info=True)
392 log.error("exception occurred when closing request", exc_info=True)
395 respiter = current[req]
396 if respiter is not None:
399 data = next(respiter)
400 except StopIteration:
405 log.error("exception occurred when handling response data", exc_info=True)
408 log.error("exception occurred when iterating response", exc_info=True)
415 log.error("exception occurred when handling response data", exc_info=True)
420 if hasattr(respiter, "close"):
423 log.error("exception occurred when closing iterator", exc_info=True)
425 if respiter is None and not req.buffer:
429 bufl = list(req for req in current.keys() if req.buffer)
430 rls, wls, els = select.select([rp], bufl, [rp] + bufl)
432 ret = os.read(rp, 1024)
438 req, respiter = self.cqueue.get(False)
439 current[req] = respiter
449 log.error("exception occurred when writing response", exc_info=True)
452 if len(req.buffer) < 65536:
455 log.critical("unexpected exception occurred in response handler thread", exc_info=True)
461 if len(self.current) > 0:
462 th = next(iter(self.current))
466 os.close(self.cnpipe[1])
469 names = {cls.cname: cls for cls in globals().values() if
470 isinstance(cls, type) and
471 issubclass(cls, handler) and
472 hasattr(cls, "cname")}
474 def parsehspec(spec):
477 nm, spec = spec.split(":", 1)
481 part, spec = spec.split(",", 1)
483 part, spec = spec, None
485 key, val = part.split("=", 1)