python: Start rewriting WSGI handlers with modular handling models.
[ashd.git] / python / scgi-wsgi
1 #!/usr/bin/python
2
3 import sys, os, getopt, logging
4 import socket
5 import ashd.scgi, ashd.perf, ashd.serve
6 try:
7     import pdm.srv
8 except:
9     pdm = None
10
11 def usage(out):
12     out.write("usage: scgi-wsgi [-hAL] [-m PDM-SPEC] [-p MODPATH] [-T [HOST:]PORT] HANDLER-MODULE [ARGS...]\n")
13
14 sk = None
15 modwsgi_compat = False
16 setlog = True
17 opts, args = getopt.getopt(sys.argv[1:], "+hALp:T:m:")
18 for o, a in opts:
19     if o == "-h":
20         usage(sys.stdout)
21         sys.exit(0)
22     elif o == "-p":
23         sys.path.insert(0, a)
24     elif o == "-L":
25         setlog = False
26     elif o == "-T":
27         sk = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
28         sk.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
29         p = a.rfind(":")
30         if p < 0:
31             bindhost = "localhost"
32             bindport = int(a)
33         else:
34             bindhost = a[:p]
35             bindport = int(a[p + 1:])
36         sk.bind((bindhost, bindport))
37         sk.listen(32)
38     elif o == "-A":
39         modwsgi_compat = True
40     elif o == "-m":
41         if pdm is not None:
42             pdm.srv.listen(a)
43 if len(args) < 1:
44     usage(sys.stderr)
45     sys.exit(1)
46 if setlog:
47     logging.basicConfig(format="scgi-wsgi(%(name)s): %(levelname)s: %(message)s")
48
49 if sk is None:
50     # This is suboptimal, since the socket on stdin is not necessarily
51     # AF_UNIX, but Python does not seem to offer any way around it,
52     # that I can find.
53     sk = socket.fromfd(0, socket.AF_UNIX, socket.SOCK_STREAM)
54
55 try:
56     handlermod = __import__(args[0], fromlist = ["dummy"])
57 except ImportError, exc:
58     sys.stderr.write("scgi-wsgi: handler %s not found: %s\n" % (args[0], exc.message))
59     sys.exit(1)
60 if not modwsgi_compat:
61     if not hasattr(handlermod, "wmain"):
62         sys.stderr.write("scgi-wsgi: handler %s has no `wmain' function\n" % args[0])
63         sys.exit(1)
64     handler = handlermod.wmain(*args[1:])
65 else:
66     if not hasattr(handlermod, "application"):
67         sys.stderr.write("scgi-wsgi: handler %s has no `application' object\n" % args[0])
68         sys.exit(1)
69     handler = handlermod.application
70
71 def mkenv(head, sk):
72     env = dict(head)
73     env["wsgi.version"] = 1, 0
74     if "HTTP_X_ASH_PROTOCOL" in env:
75         env["wsgi.url_scheme"] = env["HTTP_X_ASH_PROTOCOL"]
76     elif "HTTPS" in env:
77         env["wsgi.url_scheme"] = "https"
78     else:
79         env["wsgi.url_scheme"] = "http"
80     env["wsgi.input"] = sk
81     env["wsgi.errors"] = sys.stderr
82     env["wsgi.multithread"] = True
83     env["wsgi.multiprocess"] = False
84     env["wsgi.run_once"] = False
85     return env
86
87 class reqthread(ashd.serve.wsgithread):
88     def __init__(self, sk):
89         super(reqthread, self).__init__()
90         self.bsk = sk.dup()
91         self.sk = self.bsk.makefile("r+")
92
93     def handlewsgi(self):
94         return handler(self.env, self.startreq)
95
96     def writehead(self, status, headers):
97         try:
98             self.sk.write("Status: %s\n" % status)
99             for nm, val in headers:
100                 self.sk.write("%s: %s\n" % (nm, val))
101             self.sk.write("\n")
102         except IOError:
103             raise ashd.serve.closed()
104
105     def writedata(self, data):
106         try:
107             self.sk.write(data)
108             self.sk.flush()
109         except IOError:
110             raise ashd.serve.closed()
111
112     def handle(self):
113         head = ashd.scgi.readhead(self.sk)
114         self.env = mkenv(head, self.sk)
115         reqevent = ashd.perf.request(self.env)
116         exc = (None, None, None)
117         try:
118             super(reqthread, self).handle()
119             if self.status:
120                 reqevent.response([self.status, self.headers])
121         except:
122             exc = sys.exc_info()
123             raise
124         finally:
125             reqevent.__exit__(*exc)
126
127     def run(self):
128         try:
129             super(reqthread, self).run()
130         finally:
131             self.sk.close()
132             self.bsk.close()
133
134 while True:
135     nsk, addr = sk.accept()
136     try:
137         reqthread(nsk).start()
138     finally:
139         nsk.close()