python: Try to shut ashd-wsgi down more nicely upon signal receipt.
[ashd.git] / python / ashd-wsgi
1 #!/usr/bin/python
2
3 import sys, os, getopt, socket, logging, time, signal
4 import ashd.util, ashd.serve
5 try:
6     import pdm.srv
7 except:
8     pdm = None
9
10 def usage(out):
11     out.write("usage: ashd-wsgi [-hAL] [-m PDM-SPEC] [-p MODPATH] [-t REQUEST-HANDLER[:PAR[=VAL](,PAR[=VAL])...]] HANDLER-MODULE [ARGS...]\n")
12
13 hspec = "free", {}
14 modwsgi_compat = False
15 setlog = True
16 opts, args = getopt.getopt(sys.argv[1:], "+hALp:t:l:m:")
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)
23     elif o == "-L":
24         setlog = False
25     elif o == "-A":
26         modwsgi_compat = True
27     elif o == "-l":
28         hspec = "free", {"max": a, "abort": "10"}
29     elif o == "-t":
30         hspec = ashd.serve.parsehspec(a)
31     elif o == "-m":
32         if pdm is not None:
33             pdm.srv.listen(a)
34 if len(args) < 1:
35     usage(sys.stderr)
36     sys.exit(1)
37 if setlog:
38     logging.basicConfig(format="ashd-wsgi(%(name)s): %(levelname)s: %(message)s")
39 log = logging.getLogger("ashd-wsgi")
40
41 try:
42     handlermod = __import__(args[0], fromlist = ["dummy"])
43 except ImportError, exc:
44     sys.stderr.write("ashd-wsgi: handler %s not found: %s\n" % (args[0], exc.message))
45     sys.exit(1)
46 if not modwsgi_compat:
47     if not hasattr(handlermod, "wmain"):
48         sys.stderr.write("ashd-wsgi: handler %s has no `wmain' function\n" % args[0])
49         sys.exit(1)
50     handler = handlermod.wmain(*args[1:])
51 else:
52     if not hasattr(handlermod, "application"):
53         sys.stderr.write("ashd-wsgi: handler %s has no `application' object\n" % args[0])
54         sys.exit(1)
55     handler = handlermod.application
56
57 cwd = os.getcwd()
58 def absolutify(path):
59     if path[0] != '/':
60         return os.path.join(cwd, path)
61     return path
62
63 def unquoteurl(url):
64     buf = ""
65     i = 0
66     while i < len(url):
67         c = url[i]
68         i += 1
69         if c == '%':
70             if len(url) >= i + 2:
71                 c = 0
72                 if '0' <= url[i] <= '9':
73                     c |= (ord(url[i]) - ord('0')) << 4
74                 elif 'a' <= url[i] <= 'f':
75                     c |= (ord(url[i]) - ord('a') + 10) << 4
76                 elif 'A' <= url[i] <= 'F':
77                     c |= (ord(url[i]) - ord('A') + 10) << 4
78                 else:
79                     raise ValueError("Illegal URL escape character")
80                 if '0' <= url[i + 1] <= '9':
81                     c |= ord(url[i + 1]) - ord('0')
82                 elif 'a' <= url[i + 1] <= 'f':
83                     c |= ord(url[i + 1]) - ord('a') + 10
84                 elif 'A' <= url[i + 1] <= 'F':
85                     c |= ord(url[i + 1]) - ord('A') + 10
86                 else:
87                     raise ValueError("Illegal URL escape character")
88                 buf += chr(c)
89                 i += 2
90             else:
91                 raise ValueError("Incomplete URL escape character")
92         else:
93             buf += c
94     return buf
95
96 def mkenv(req):
97     env = {}
98     env["wsgi.version"] = 1, 0
99     for key, val in req.headers:
100         env["HTTP_" + key.upper().replace("-", "_")] = val
101     env["SERVER_SOFTWARE"] = "ashd-wsgi/1"
102     env["GATEWAY_INTERFACE"] = "CGI/1.1"
103     env["SERVER_PROTOCOL"] = req.ver
104     env["REQUEST_METHOD"] = req.method
105     env["REQUEST_URI"] = req.url
106     name = req.url
107     p = name.find('?')
108     if p >= 0:
109         env["QUERY_STRING"] = name[p + 1:]
110         name = name[:p]
111     else:
112         env["QUERY_STRING"] = ""
113     if name[-len(req.rest):] == req.rest:
114         # This is the same hack used in call*cgi.
115         name = name[:-len(req.rest)]
116     try:
117         pi = unquoteurl(req.rest)
118     except:
119         pi = req.rest
120     if name == '/':
121         # This seems to be normal CGI behavior, but see callcgi.c for
122         # details.
123         pi = "/" + pi
124         name = ""
125     env["SCRIPT_NAME"] = name
126     env["PATH_INFO"] = pi
127     if "Host" in req: env["SERVER_NAME"] = req["Host"]
128     if "X-Ash-Server-Address" in req: env["SERVER_ADDR"] = req["X-Ash-Server-Address"]
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 "X-Ash-Port" in req: env["REMOTE_PORT"] = req["X-Ash-Port"]
133     if "Content-Type" in req:
134         env["CONTENT_TYPE"] = req["Content-Type"]
135         # The CGI specification does not strictly require this, but
136         # many actualy programs and libraries seem to.
137         del env["HTTP_CONTENT_TYPE"]
138     if "Content-Length" in req:
139         env["CONTENT_LENGTH"] = req["Content-Length"]
140         del env["HTTP_CONTENT_LENGTH"]
141     if "X-Ash-File" in req: env["SCRIPT_FILENAME"] = absolutify(req["X-Ash-File"])
142     if "X-Ash-Protocol" in req: env["wsgi.url_scheme"] = req["X-Ash-Protocol"]
143     env["wsgi.input"] = req.sk
144     env["wsgi.errors"] = sys.stderr
145     env["wsgi.multithread"] = True
146     env["wsgi.multiprocess"] = False
147     env["wsgi.run_once"] = False
148     return env
149
150 class request(ashd.serve.wsgirequest):
151     def __init__(self, bkreq, **kw):
152         super(request, self).__init__(**kw)
153         self.bkreq = bkreq.dup()
154
155     def mkenv(self):
156         return mkenv(self.bkreq)
157
158     def handlewsgi(self, env, startreq):
159         return handler(env, startreq)
160
161     def fileno(self):
162         return self.bkreq.bsk.fileno()
163
164     def writehead(self, status, headers):
165         w = self.buffer.extend
166         w("HTTP/1.1 %s\n" % status)
167         for nm, val in headers:
168             w("%s: %s\n" % (nm, val))
169         w("\n")
170
171     def flush(self):
172         try:
173             ret = self.bkreq.bsk.send(self.buffer, socket.MSG_DONTWAIT)
174             self.buffer[:ret] = ""
175         except IOError:
176             raise ashd.serve.closed()
177
178     def close(self):
179         self.bkreq.close()
180
181 def handle(req):
182     reqhandler.handle(request(bkreq=req, handler=reqhandler))
183
184 if hspec[0] not in ashd.serve.names:
185     sys.stderr.write("ashd-wsgi: no such request handler: %s\n" % hspec[0])
186     sys.exit(1)
187 hclass = ashd.serve.names[hspec[0]]
188 try:
189     hargs = hclass.parseargs(**hspec[1])
190 except ValueError as exc:
191     sys.stderr.write("ashd-wsgi: %s\n" % exc)
192     sys.exit(1)
193
194 def sigterm(sig, frame):
195     socket.fromfd(0, socket.AF_UNIX, socket.SOCK_SEQPACKET).shutdown(socket.SHUT_RDWR) # :P
196 for signum in [signal.SIGINT, signal.SIGTERM]:
197     signal.signal(signum, sigterm)
198
199 reqhandler = hclass(**hargs)
200 try:
201     ashd.util.serveloop(handle)
202 finally:
203     reqhandler.close()