ae08137a1a80fb460dce85d47adbacad526e9e18
[ashd.git] / python / ashd-wsgi
1 #!/usr/bin/python
2
3 import sys, os, getopt, threading
4 import ashd.proto, ashd.util
5
6 def usage(out):
7     out.write("usage: ashd-wsgi [-hA] [-p MODPATH] HANDLER-MODULE [ARGS...]\n")
8
9 modwsgi_compat = False
10 opts, args = getopt.getopt(sys.argv[1:], "+hAp:")
11 for o, a in opts:
12     if o == "-h":
13         usage(sys.stdout)
14         sys.exit(0)
15     elif o == "-p":
16         sys.path.insert(0, a)
17     elif o == "-A":
18         modwsgi_compat = True
19 if len(args) < 1:
20     usage(sys.stderr)
21     sys.exit(1)
22
23 try:
24     handlermod = __import__(args[0], fromlist = ["dummy"])
25 except ImportError, exc:
26     sys.stderr.write("ashd-wsgi: handler %s not found: %s\n" % (args[0], exc.message))
27     sys.exit(1)
28 if not modwsgi_compat:
29     if not hasattr(handlermod, "wmain"):
30         sys.stderr.write("ashd-wsgi: handler %s has no `wmain' function\n" % args[0])
31         sys.exit(1)
32     handler = handlermod.wmain(*args[1:])
33 else:
34     if not hasattr(handlermod, "application"):
35         sys.stderr.write("ashd-wsgi: handler %s has no `application' object\n" % args[0])
36         sys.exit(1)
37     handler = handlermod.application
38
39 cwd = os.getcwd()
40 def absolutify(path):
41     if path[0] != '/':
42         return os.path.join(cwd, path)
43     return path
44
45 def dowsgi(req):
46     env = {}
47     env["wsgi.version"] = 1, 0
48     for key, val in req.headers:
49         env["HTTP_" + key.upper().replace("-", "_")] = val
50     env["SERVER_SOFTWARE"] = "ashd-wsgi/1"
51     env["GATEWAY_INTERFACE"] = "CGI/1.1"
52     env["SERVER_PROTOCOL"] = req.ver
53     env["REQUEST_METHOD"] = req.method
54     env["REQUEST_URI"] = req.url
55     env["PATH_INFO"] = req.rest
56     name = req.url
57     p = name.find('?')
58     if p >= 0:
59         env["QUERY_STRING"] = name[p + 1:]
60         name = name[:p]
61     else:
62         env["QUERY_STRING"] = ""
63     if name[-len(req.rest):] == req.rest:
64         name = name[:-len(req.rest)]
65     env["SCRIPT_NAME"] = name
66     if "Host" in req: env["SERVER_NAME"] = req["Host"]
67     if "X-Ash-Server-Port" in req: env["SERVER_PORT"] = req["X-Ash-Server-Port"]
68     if "X-Ash-Protocol" in req and req["X-Ash-Protocol"] == "https": env["HTTPS"] = "on"
69     if "X-Ash-Address" in req: env["REMOTE_ADDR"] = req["X-Ash-Address"]
70     if "Content-Type" in req: env["CONTENT_TYPE"] = req["Content-Type"]
71     if "Content-Length" in req: env["CONTENT_LENGTH"] = req["Content-Length"]
72     if "X-Ash-File" in req: env["SCRIPT_FILENAME"] = absolutify(req["X-Ash-File"])
73     if "X-Ash-Protocol" in req: env["wsgi.url_scheme"] = req["X-Ash-Protocol"]
74     env["wsgi.input"] = req.sk
75     env["wsgi.errors"] = sys.stderr
76     env["wsgi.multithread"] = True
77     env["wsgi.multiprocess"] = False
78     env["wsgi.run_once"] = False
79
80     resp = []
81     respsent = []
82
83     def flushreq():
84         if not respsent:
85             if not resp:
86                 raise Exception, "Trying to write data before starting response."
87             status, headers = resp
88             respsent[:] = [True]
89             req.sk.write("HTTP/1.1 %s\n" % status)
90             for nm, val in headers:
91                 req.sk.write("%s: %s\n" % (nm, val))
92             req.sk.write("\n")
93
94     def write(data):
95         if not data:
96             return
97         flushreq()
98         req.sk.write(data)
99         req.sk.flush()
100
101     def startreq(status, headers, exc_info = None):
102         if resp:
103             if exc_info:                # Interesting, this...
104                 try:
105                     if respsent:
106                         raise exc_info[0], exc_info[1], exc_info[2]
107                 finally:
108                     exc_info = None     # CPython GC bug?
109             else:
110                 raise Exception, "Can only start responding once."
111         resp[:] = status, headers
112         return write
113
114     respiter = handler(env, startreq)
115     try:
116         for data in respiter:
117             write(data)
118         if resp:
119             flushreq()
120     finally:
121         if hasattr(respiter, "close"):
122             respiter.close()
123
124 class reqthread(threading.Thread):
125     def __init__(self, req):
126         super(reqthread, self).__init__(name = "Request handler")
127         self.req = req.dup()
128     
129     def run(self):
130         try:
131             dowsgi(self.req)
132         finally:
133             self.req.close()
134     
135 def handle(req):
136     reqthread(req).start()
137
138 ashd.util.serveloop(handle)