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