3 import sys, os, getopt, threading, logging, time
4 import ashd.proto, ashd.util, ashd.perf
11 out.write("usage: ashd-wsgi [-hAL] [-m PDM-SPEC] [-p MODPATH] [-l REQLIMIT] HANDLER-MODULE [ARGS...]\n")
14 modwsgi_compat = False
16 opts, args = getopt.getopt(sys.argv[1:], "+hAp:l:m:")
36 logging.basicConfig(format="ashd-wsgi(%(name)s): %(levelname)s: %(message)s")
37 log = logging.getLogger("ashd-wsgi")
40 handlermod = __import__(args[0], fromlist = ["dummy"])
41 except ImportError, exc:
42 sys.stderr.write("ashd-wsgi: handler %s not found: %s\n" % (args[0], exc.message))
44 if not modwsgi_compat:
45 if not hasattr(handlermod, "wmain"):
46 sys.stderr.write("ashd-wsgi: handler %s has no `wmain' function\n" % args[0])
48 handler = handlermod.wmain(*args[1:])
50 if not hasattr(handlermod, "application"):
51 sys.stderr.write("ashd-wsgi: handler %s has no `application' object\n" % args[0])
53 handler = handlermod.application
55 class closed(IOError):
57 super(closed, self).__init__("The client has closed the connection.")
62 return os.path.join(cwd, path)
74 if '0' <= url[i] <= '9':
75 c |= (ord(url[i]) - ord('0')) << 4
76 elif 'a' <= url[i] <= 'f':
77 c |= (ord(url[i]) - ord('a') + 10) << 4
78 elif 'A' <= url[i] <= 'F':
79 c |= (ord(url[i]) - ord('A') + 10) << 4
81 raise ValueError("Illegal URL escape character")
82 if '0' <= url[i + 1] <= '9':
83 c |= ord(url[i + 1]) - ord('0')
84 elif 'a' <= url[i + 1] <= 'f':
85 c |= ord(url[i + 1]) - ord('a') + 10
86 elif 'A' <= url[i + 1] <= 'F':
87 c |= ord(url[i + 1]) - ord('A') + 10
89 raise ValueError("Illegal URL escape character")
93 raise ValueError("Incomplete URL escape character")
100 env["wsgi.version"] = 1, 0
101 for key, val in req.headers:
102 env["HTTP_" + key.upper().replace("-", "_")] = val
103 env["SERVER_SOFTWARE"] = "ashd-wsgi/1"
104 env["GATEWAY_INTERFACE"] = "CGI/1.1"
105 env["SERVER_PROTOCOL"] = req.ver
106 env["REQUEST_METHOD"] = req.method
107 env["REQUEST_URI"] = req.url
111 env["QUERY_STRING"] = name[p + 1:]
114 env["QUERY_STRING"] = ""
115 if name[-len(req.rest):] == req.rest:
116 # This is the same hack used in call*cgi.
117 name = name[:-len(req.rest)]
119 pi = unquoteurl(req.rest)
123 # This seems to be normal CGI behavior, but see callcgi.c for
127 env["SCRIPT_NAME"] = name
128 env["PATH_INFO"] = pi
129 if "Host" in req: env["SERVER_NAME"] = req["Host"]
130 if "X-Ash-Server-Address" in req: env["SERVER_ADDR"] = req["X-Ash-Server-Address"]
131 if "X-Ash-Server-Port" in req: env["SERVER_PORT"] = req["X-Ash-Server-Port"]
132 if "X-Ash-Protocol" in req and req["X-Ash-Protocol"] == "https": env["HTTPS"] = "on"
133 if "X-Ash-Address" in req: env["REMOTE_ADDR"] = req["X-Ash-Address"]
134 if "X-Ash-Port" in req: env["REMOTE_PORT"] = req["X-Ash-Port"]
135 if "Content-Type" in req:
136 env["CONTENT_TYPE"] = req["Content-Type"]
137 # The CGI specification does not strictly require this, but
138 # many actualy programs and libraries seem to.
139 del env["HTTP_CONTENT_TYPE"]
140 if "Content-Length" in req:
141 env["CONTENT_LENGTH"] = req["Content-Length"]
142 del env["HTTP_CONTENT_LENGTH"]
143 if "X-Ash-File" in req: env["SCRIPT_FILENAME"] = absolutify(req["X-Ash-File"])
144 if "X-Ash-Protocol" in req: env["wsgi.url_scheme"] = req["X-Ash-Protocol"]
145 env["wsgi.input"] = req.sk
146 env["wsgi.errors"] = sys.stderr
147 env["wsgi.multithread"] = True
148 env["wsgi.multiprocess"] = False
149 env["wsgi.run_once"] = False
157 raise Exception, "Trying to write data before starting response."
158 status, headers = resp
161 req.sk.write("HTTP/1.1 %s\n" % status)
162 for nm, val in headers:
163 req.sk.write("%s: %s\n" % (nm, val))
178 def startreq(status, headers, exc_info = None):
180 if exc_info: # Interesting, this...
183 raise exc_info[0], exc_info[1], exc_info[2]
185 exc_info = None # CPython GC bug?
187 raise Exception, "Can only start responding once."
188 resp[:] = status, headers
191 reqevent = ashd.perf.request(env)
192 exc = (None, None, None)
195 respiter = handler(env, startreq)
197 for data in respiter:
202 if hasattr(respiter, "close"):
207 reqevent.response(resp)
212 reqevent.__exit__(*exc)
214 flightlock = threading.Condition()
217 class reqthread(threading.Thread):
218 def __init__(self, req):
219 super(reqthread, self).__init__(name = "Request handler")
229 while inflight >= reqlimit:
231 if time.time() - start > 10:
246 log.error("exception occurred in handler thread", exc_info=True)
251 reqthread(req).start()
253 ashd.util.serveloop(handle)