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-Port" in req: env["SERVER_PORT"] = req["X-Ash-Server-Port"]
131 if "X-Ash-Protocol" in req and req["X-Ash-Protocol"] == "https": env["HTTPS"] = "on"
132 if "X-Ash-Address" in req: env["REMOTE_ADDR"] = req["X-Ash-Address"]
133 if "Content-Type" in req: env["CONTENT_TYPE"] = req["Content-Type"]
134 if "Content-Length" in req: env["CONTENT_LENGTH"] = req["Content-Length"]
135 if "X-Ash-File" in req: env["SCRIPT_FILENAME"] = absolutify(req["X-Ash-File"])
136 if "X-Ash-Protocol" in req: env["wsgi.url_scheme"] = req["X-Ash-Protocol"]
137 env["wsgi.input"] = req.sk
138 env["wsgi.errors"] = sys.stderr
139 env["wsgi.multithread"] = True
140 env["wsgi.multiprocess"] = False
141 env["wsgi.run_once"] = False
149 raise Exception, "Trying to write data before starting response."
150 status, headers = resp
153 req.sk.write("HTTP/1.1 %s\n" % status)
154 for nm, val in headers:
155 req.sk.write("%s: %s\n" % (nm, val))
170 def startreq(status, headers, exc_info = None):
172 if exc_info: # Interesting, this...
175 raise exc_info[0], exc_info[1], exc_info[2]
177 exc_info = None # CPython GC bug?
179 raise Exception, "Can only start responding once."
180 resp[:] = status, headers
183 reqevent = ashd.perf.request(env)
184 exc = (None, None, None)
187 respiter = handler(env, startreq)
189 for data in respiter:
194 if hasattr(respiter, "close"):
199 reqevent.response(resp)
204 reqevent.__exit__(*exc)
206 flightlock = threading.Condition()
209 class reqthread(threading.Thread):
210 def __init__(self, req):
211 super(reqthread, self).__init__(name = "Request handler")
221 while inflight >= reqlimit:
223 if time.time() - start > 10:
238 log.error("exception occurred in handler thread", exc_info=True)
243 reqthread(req).start()
245 ashd.util.serveloop(handle)