Commit | Line | Data |
---|---|---|
173e0e9e | 1 | #!/usr/bin/python |
c270f222 | 2 | |
14640dcc | 3 | import sys, os, getopt, threading, logging, time |
d5ee5cde FT |
4 | import ashd.proto, ashd.util, ashd.perf |
5 | try: | |
6 | import pdm.srv | |
7 | except: | |
8 | pdm = None | |
c270f222 FT |
9 | |
10 | def usage(out): | |
14640dcc | 11 | out.write("usage: ashd-wsgi [-hAL] [-m PDM-SPEC] [-p MODPATH] [-l REQLIMIT] HANDLER-MODULE [ARGS...]\n") |
c270f222 | 12 | |
3e11d7ed | 13 | reqlimit = 0 |
c270f222 | 14 | modwsgi_compat = False |
14640dcc | 15 | setlog = True |
d5ee5cde | 16 | opts, args = getopt.getopt(sys.argv[1:], "+hAp:l:m:") |
c270f222 FT |
17 | for o, a in opts: |
18 | if o == "-h": | |
19 | usage(sys.stdout) | |
20 | sys.exit(0) | |
21 | elif o == "-p": | |
22 | sys.path.insert(0, a) | |
14640dcc FT |
23 | elif o == "-L": |
24 | setlog = False | |
c270f222 FT |
25 | elif o == "-A": |
26 | modwsgi_compat = True | |
3e11d7ed FT |
27 | elif o == "-l": |
28 | reqlimit = int(a) | |
d5ee5cde FT |
29 | elif o == "-m": |
30 | if pdm is not None: | |
31 | pdm.srv.listen(a) | |
c270f222 FT |
32 | if len(args) < 1: |
33 | usage(sys.stderr) | |
34 | sys.exit(1) | |
14640dcc FT |
35 | if setlog: |
36 | logging.basicConfig(format="ashd-wsgi(%(name)s): %(levelname)s: %(message)s") | |
c270f222 FT |
37 | |
38 | try: | |
39 | handlermod = __import__(args[0], fromlist = ["dummy"]) | |
173e0e9e FT |
40 | except ImportError, exc: |
41 | sys.stderr.write("ashd-wsgi: handler %s not found: %s\n" % (args[0], exc.message)) | |
c270f222 FT |
42 | sys.exit(1) |
43 | if not modwsgi_compat: | |
44 | if not hasattr(handlermod, "wmain"): | |
45 | sys.stderr.write("ashd-wsgi: handler %s has no `wmain' function\n" % args[0]) | |
46 | sys.exit(1) | |
adb11d5f | 47 | handler = handlermod.wmain(*args[1:]) |
c270f222 FT |
48 | else: |
49 | if not hasattr(handlermod, "application"): | |
50 | sys.stderr.write("ashd-wsgi: handler %s has no `application' object\n" % args[0]) | |
51 | sys.exit(1) | |
52 | handler = handlermod.application | |
53 | ||
81a0ca30 FT |
54 | class closed(IOError): |
55 | def __init__(self): | |
173e0e9e | 56 | super(closed, self).__init__("The client has closed the connection.") |
81a0ca30 | 57 | |
70d942a7 FT |
58 | cwd = os.getcwd() |
59 | def absolutify(path): | |
60 | if path[0] != '/': | |
61 | return os.path.join(cwd, path) | |
62 | return path | |
63 | ||
09c82f9c | 64 | def unquoteurl(url): |
173e0e9e | 65 | buf = "" |
09c82f9c FT |
66 | i = 0 |
67 | while i < len(url): | |
68 | c = url[i] | |
69 | i += 1 | |
173e0e9e | 70 | if c == '%': |
370d235f | 71 | if len(url) >= i + 2: |
09c82f9c | 72 | c = 0 |
173e0e9e FT |
73 | if '0' <= url[i] <= '9': |
74 | c |= (ord(url[i]) - ord('0')) << 4 | |
75 | elif 'a' <= url[i] <= 'f': | |
76 | c |= (ord(url[i]) - ord('a') + 10) << 4 | |
77 | elif 'A' <= url[i] <= 'F': | |
78 | c |= (ord(url[i]) - ord('A') + 10) << 4 | |
09c82f9c FT |
79 | else: |
80 | raise ValueError("Illegal URL escape character") | |
173e0e9e FT |
81 | if '0' <= url[i + 1] <= '9': |
82 | c |= ord(url[i + 1]) - ord('0') | |
83 | elif 'a' <= url[i + 1] <= 'f': | |
84 | c |= ord(url[i + 1]) - ord('a') + 10 | |
85 | elif 'A' <= url[i + 1] <= 'F': | |
86 | c |= ord(url[i + 1]) - ord('A') + 10 | |
09c82f9c FT |
87 | else: |
88 | raise ValueError("Illegal URL escape character") | |
173e0e9e | 89 | buf += chr(c) |
09c82f9c FT |
90 | i += 2 |
91 | else: | |
92 | raise ValueError("Incomplete URL escape character") | |
93 | else: | |
173e0e9e | 94 | buf += c |
09c82f9c | 95 | return buf |
81a0ca30 | 96 | |
c270f222 FT |
97 | def dowsgi(req): |
98 | env = {} | |
99 | env["wsgi.version"] = 1, 0 | |
100 | for key, val in req.headers: | |
173e0e9e | 101 | env["HTTP_" + key.upper().replace("-", "_")] = val |
c270f222 FT |
102 | env["SERVER_SOFTWARE"] = "ashd-wsgi/1" |
103 | env["GATEWAY_INTERFACE"] = "CGI/1.1" | |
173e0e9e FT |
104 | env["SERVER_PROTOCOL"] = req.ver |
105 | env["REQUEST_METHOD"] = req.method | |
106 | env["REQUEST_URI"] = req.url | |
107 | name = req.url | |
c270f222 FT |
108 | p = name.find('?') |
109 | if p >= 0: | |
c270f222 | 110 | env["QUERY_STRING"] = name[p + 1:] |
8498ab28 | 111 | name = name[:p] |
c270f222 FT |
112 | else: |
113 | env["QUERY_STRING"] = "" | |
173e0e9e | 114 | if name[-len(req.rest):] == req.rest: |
53d666ca | 115 | # This is the same hack used in call*cgi. |
173e0e9e FT |
116 | name = name[:-len(req.rest)] |
117 | try: | |
118 | pi = unquoteurl(req.rest) | |
119 | except: | |
120 | pi = req.rest | |
121 | if name == '/': | |
53d666ca FT |
122 | # This seems to be normal CGI behavior, but see callcgi.c for |
123 | # details. | |
124 | pi = "/" + pi | |
125 | name = "" | |
c270f222 | 126 | env["SCRIPT_NAME"] = name |
53d666ca | 127 | env["PATH_INFO"] = pi |
173e0e9e FT |
128 | if "Host" in req: env["SERVER_NAME"] = req["Host"] |
129 | if "X-Ash-Server-Port" in req: env["SERVER_PORT"] = req["X-Ash-Server-Port"] | |
130 | if "X-Ash-Protocol" in req and req["X-Ash-Protocol"] == "https": env["HTTPS"] = "on" | |
131 | if "X-Ash-Address" in req: env["REMOTE_ADDR"] = req["X-Ash-Address"] | |
132 | if "Content-Type" in req: env["CONTENT_TYPE"] = req["Content-Type"] | |
133 | if "Content-Length" in req: env["CONTENT_LENGTH"] = req["Content-Length"] | |
134 | if "X-Ash-File" in req: env["SCRIPT_FILENAME"] = absolutify(req["X-Ash-File"]) | |
135 | if "X-Ash-Protocol" in req: env["wsgi.url_scheme"] = req["X-Ash-Protocol"] | |
c270f222 FT |
136 | env["wsgi.input"] = req.sk |
137 | env["wsgi.errors"] = sys.stderr | |
138 | env["wsgi.multithread"] = True | |
139 | env["wsgi.multiprocess"] = False | |
140 | env["wsgi.run_once"] = False | |
141 | ||
142 | resp = [] | |
143 | respsent = [] | |
144 | ||
699754de | 145 | def flushreq(): |
c270f222 FT |
146 | if not respsent: |
147 | if not resp: | |
173e0e9e | 148 | raise Exception, "Trying to write data before starting response." |
c270f222 FT |
149 | status, headers = resp |
150 | respsent[:] = [True] | |
8bb0e3c1 | 151 | try: |
173e0e9e FT |
152 | req.sk.write("HTTP/1.1 %s\n" % status) |
153 | for nm, val in headers: | |
154 | req.sk.write("%s: %s\n" % (nm, val)) | |
155 | req.sk.write("\n") | |
8bb0e3c1 FT |
156 | except IOError: |
157 | raise closed() | |
699754de FT |
158 | |
159 | def write(data): | |
160 | if not data: | |
161 | return | |
8bb0e3c1 | 162 | flushreq() |
81a0ca30 FT |
163 | try: |
164 | req.sk.write(data) | |
165 | req.sk.flush() | |
166 | except IOError: | |
167 | raise closed() | |
c270f222 FT |
168 | |
169 | def startreq(status, headers, exc_info = None): | |
170 | if resp: | |
171 | if exc_info: # Interesting, this... | |
172 | try: | |
173 | if respsent: | |
173e0e9e | 174 | raise exc_info[0], exc_info[1], exc_info[2] |
c270f222 FT |
175 | finally: |
176 | exc_info = None # CPython GC bug? | |
177 | else: | |
173e0e9e | 178 | raise Exception, "Can only start responding once." |
c270f222 FT |
179 | resp[:] = status, headers |
180 | return write | |
181 | ||
d5ee5cde FT |
182 | reqevent = ashd.perf.request(env) |
183 | exc = (None, None, None) | |
c270f222 | 184 | try: |
d5ee5cde | 185 | respiter = handler(env, startreq) |
8bb0e3c1 | 186 | try: |
d5ee5cde FT |
187 | try: |
188 | for data in respiter: | |
189 | write(data) | |
190 | if resp: | |
191 | flushreq() | |
192 | except closed: | |
193 | pass | |
194 | finally: | |
195 | if hasattr(respiter, "close"): | |
196 | respiter.close() | |
197 | if resp: | |
198 | reqevent.response(resp) | |
199 | except: | |
200 | exc = sys.exc_info() | |
f1263757 | 201 | raise |
c270f222 | 202 | finally: |
d5ee5cde | 203 | reqevent.__exit__(*exc) |
c270f222 | 204 | |
3e11d7ed FT |
205 | flightlock = threading.Condition() |
206 | inflight = 0 | |
207 | ||
c270f222 FT |
208 | class reqthread(threading.Thread): |
209 | def __init__(self, req): | |
173e0e9e | 210 | super(reqthread, self).__init__(name = "Request handler") |
c270f222 FT |
211 | self.req = req.dup() |
212 | ||
213 | def run(self): | |
3e11d7ed | 214 | global inflight |
c270f222 | 215 | try: |
173e0e9e FT |
216 | flightlock.acquire() |
217 | try: | |
3e11d7ed FT |
218 | if reqlimit != 0: |
219 | start = time.time() | |
220 | while inflight >= reqlimit: | |
221 | flightlock.wait(10) | |
222 | if time.time() - start > 10: | |
223 | os.abort() | |
224 | inflight += 1 | |
173e0e9e FT |
225 | finally: |
226 | flightlock.release() | |
3e11d7ed FT |
227 | try: |
228 | dowsgi(self.req) | |
229 | finally: | |
173e0e9e FT |
230 | flightlock.acquire() |
231 | try: | |
3e11d7ed FT |
232 | inflight -= 1 |
233 | flightlock.notify() | |
173e0e9e FT |
234 | finally: |
235 | flightlock.release() | |
c270f222 FT |
236 | finally: |
237 | self.req.close() | |
238 | ||
239 | def handle(req): | |
240 | reqthread(req).start() | |
241 | ||
4e7888f7 | 242 | ashd.util.serveloop(handle) |