1 import sys, os, threading, time, logging, select, Queue
4 log = logging.getLogger("ashd.serve")
6 seqlk = threading.Lock()
15 class closed(IOError):
17 super(closed, self).__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(reqthread, self).__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: " + iter(args).next())
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)
111 class freethread(handler):
114 def __init__(self, max=None, timeout=None, **kw):
115 super(freethread, self).__init__(**kw)
117 self.lk = threading.Lock()
118 self.tcond = threading.Condition(self.lk)
120 self.timeout = timeout
123 def parseargs(cls, max=None, abort=None, **args):
124 ret = super(freethread, cls).parseargs(**args)
126 ret["max"] = int(max)
128 ret["timeout"] = int(abort)
131 def handle(self, req):
133 if self.max is not None:
134 if self.timeout is not None:
135 now = start = time.time()
136 while len(self.current) >= self.max:
137 self.tcond.wait(start + self.timeout - now)
139 if now - start > self.timeout:
142 while len(self.current) >= self.max:
144 th = reqthread(target=self.run, args=[req])
145 th.registered = False
147 while not th.registered:
152 th = threading.current_thread()
156 self.tcond.notify_all()
159 with perf.request(env) as reqevent:
160 respiter = req.handlewsgi(env, req.startreq)
161 for data in respiter:
164 reqevent.response([req.status, req.headers])
170 log.error("exception occurred when handling request", exc_info=True)
173 self.current.remove(th)
174 self.tcond.notify_all()
181 if len(self.current) > 0:
182 th = iter(self.current).next()
187 class resplex(handler):
190 def __init__(self, max=None, **kw):
191 super(resplex, self).__init__(**kw)
193 self.lk = threading.Lock()
194 self.tcond = threading.Condition(self.lk)
196 self.cqueue = Queue.Queue(5)
197 self.cnpipe = os.pipe()
198 self.rthread = reqthread(name="Response thread", target=self.handle2)
202 def parseargs(cls, max=None, **args):
203 ret = super(resplex, cls).parseargs(**args)
205 ret["max"] = int(max)
208 def ckflush(self, req):
209 raise Exception("resplex handler does not support the write() function")
211 def handle(self, req):
213 if self.max is not None:
214 while len(self.current) >= self.max:
216 th = reqthread(target=self.handle1, args=[req])
217 th.registered = False
219 while not th.registered:
222 def handle1(self, req):
224 th = threading.current_thread()
228 self.tcond.notify_all()
231 respobj = req.handlewsgi(env, req.startreq)
232 respiter = iter(respobj)
234 log.error("request handler returned without calling start_request")
235 if hasattr(respiter, "close"):
239 self.cqueue.put((req, respiter))
240 os.write(self.cnpipe[1], " ")
244 self.current.remove(th)
245 self.tcond.notify_all()
249 log.error("exception occurred when handling request", exc_info=True)
260 respiter = current[req]
262 if respiter is not None and hasattr(respiter, "close"):
265 log.error("exception occurred when closing iterator", exc_info=True)
269 log.error("exception occurred when closing request", exc_info=True)
272 respiter = current[req]
273 if respiter is not None:
276 data = respiter.next()
277 except StopIteration:
282 log.error("exception occurred when handling response data", exc_info=True)
285 log.error("exception occurred when iterating response", exc_info=True)
292 log.error("exception occurred when handling response data", exc_info=True)
297 if hasattr(respiter, "close"):
300 log.error("exception occurred when closing iterator", exc_info=True)
302 if respiter is None and not req.buffer:
306 bufl = list(req for req in current.iterkeys() if req.buffer)
307 rls, wls, els = select.select([rp], bufl, [rp] + bufl)
309 ret = os.read(rp, 1024)
315 req, respiter = self.cqueue.get(False)
316 current[req] = respiter
326 log.error("exception occurred when writing response", exc_info=True)
329 if len(req.buffer) < 65536:
332 log.critical("unexpected exception occurred in response handler thread", exc_info=True)
338 if len(self.current) > 0:
339 th = iter(self.current).next()
343 os.close(self.cnpipe[1])
346 names = dict((cls.cname, cls) for cls in globals().itervalues() if
347 isinstance(cls, type) and
348 issubclass(cls, handler) and
349 hasattr(cls, "cname"))
351 def parsehspec(spec):
354 nm, spec = spec.split(":", 1)
358 part, spec = spec.split(",", 1)
360 part, spec = spec, None
362 key, val = part.split("=", 1)