python: Fixed doc typo.
[ashd.git] / python / ashd-wsgi
1 #!/usr/bin/python
2
3 import sys, os, getopt, threading, time
4 import ashd.proto, ashd.util
5
6 def usage(out):
7     out.write("usage: ashd-wsgi [-hA] [-p MODPATH] [-l REQLIMIT] HANDLER-MODULE [ARGS...]\n")
8
9 reqlimit = 0
10 modwsgi_compat = False
11 opts, args = getopt.getopt(sys.argv[1:], "+hAp:l:")
12 for 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
20     elif o == "-l":
21         reqlimit = int(a)
22 if len(args) < 1:
23     usage(sys.stderr)
24     sys.exit(1)
25
26 try:
27     handlermod = __import__(args[0], fromlist = ["dummy"])
28 except ImportError, exc:
29     sys.stderr.write("ashd-wsgi: handler %s not found: %s\n" % (args[0], exc.message))
30     sys.exit(1)
31 if 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)
35     handler = handlermod.wmain(*args[1:])
36 else:
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
42 class closed(IOError):
43     def __init__(self):
44         super(closed, self).__init__("The client has closed the connection.")
45
46 cwd = os.getcwd()
47 def absolutify(path):
48     if path[0] != '/':
49         return os.path.join(cwd, path)
50     return path
51
52 def unquoteurl(url):
53     buf = ""
54     i = 0
55     while i < len(url):
56         c = url[i]
57         i += 1
58         if c == '%':
59             if len(url) >= i + 2:
60                 c = 0
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
67                 else:
68                     raise ValueError("Illegal URL escape character")
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
75                 else:
76                     raise ValueError("Illegal URL escape character")
77                 buf += chr(c)
78                 i += 2
79             else:
80                 raise ValueError("Incomplete URL escape character")
81         else:
82             buf += c
83     return buf
84
85 def dowsgi(req):
86     env = {}
87     env["wsgi.version"] = 1, 0
88     for key, val in req.headers:
89         env["HTTP_" + key.upper().replace("-", "_")] = val
90     env["SERVER_SOFTWARE"] = "ashd-wsgi/1"
91     env["GATEWAY_INTERFACE"] = "CGI/1.1"
92     env["SERVER_PROTOCOL"] = req.ver
93     env["REQUEST_METHOD"] = req.method
94     env["REQUEST_URI"] = req.url
95     name = req.url
96     p = name.find('?')
97     if p >= 0:
98         env["QUERY_STRING"] = name[p + 1:]
99         name = name[:p]
100     else:
101         env["QUERY_STRING"] = ""
102     if name[-len(req.rest):] == req.rest:
103         # This is the same hack used in call*cgi.
104         name = name[:-len(req.rest)]
105     try:
106         pi = unquoteurl(req.rest)
107     except:
108         pi = req.rest
109     if name == '/':
110         # This seems to be normal CGI behavior, but see callcgi.c for
111         # details.
112         pi = "/" + pi
113         name = ""
114     env["SCRIPT_NAME"] = name
115     env["PATH_INFO"] = pi
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"]
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
133     def flushreq():
134         if not respsent:
135             if not resp:
136                 raise Exception, "Trying to write data before starting response."
137             status, headers = resp
138             respsent[:] = [True]
139             try:
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")
144             except IOError:
145                 raise closed()
146
147     def write(data):
148         if not data:
149             return
150         flushreq()
151         try:
152             req.sk.write(data)
153             req.sk.flush()
154         except IOError:
155             raise closed()
156
157     def startreq(status, headers, exc_info = None):
158         if resp:
159             if exc_info:                # Interesting, this...
160                 try:
161                     if respsent:
162                         raise exc_info[0], exc_info[1], exc_info[2]
163                 finally:
164                     exc_info = None     # CPython GC bug?
165             else:
166                 raise Exception, "Can only start responding once."
167         resp[:] = status, headers
168         return write
169
170     respiter = handler(env, startreq)
171     try:
172         try:
173             for data in respiter:
174                 write(data)
175             if resp:
176                 flushreq()
177         except closed:
178             pass
179     finally:
180         if hasattr(respiter, "close"):
181             respiter.close()
182
183 flightlock = threading.Condition()
184 inflight = 0
185
186 class reqthread(threading.Thread):
187     def __init__(self, req):
188         super(reqthread, self).__init__(name = "Request handler")
189         self.req = req.dup()
190     
191     def run(self):
192         global inflight
193         try:
194             flightlock.acquire()
195             try:
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
203             finally:
204                 flightlock.release()
205             try:
206                 dowsgi(self.req)
207             finally:
208                 flightlock.acquire()
209                 try:
210                     inflight -= 1
211                     flightlock.notify()
212                 finally:
213                     flightlock.release()
214         finally:
215             self.req.close()
216     
217 def handle(req):
218     reqthread(req).start()
219
220 ashd.util.serveloop(handle)