accesslog: Explicitly close logfile when exiting.
[ashd.git] / python3 / scgi-wsgi3
... / ...
CommitLineData
1#!/usr/bin/python3
2
3import sys, os, getopt, logging, collections
4import socket
5import ashd.scgi, ashd.perf, ashd.serve
6try:
7 import pdm.srv
8except:
9 pdm = None
10
11def usage(out):
12 out.write("usage: scgi-wsgi3 [-hAL] [-m PDM-SPEC] [-p MODPATH] [-T [HOST:]PORT] HANDLER-MODULE [ARGS...]\n")
13
14sk = None
15modwsgi_compat = False
16setlog = True
17opts, args = getopt.getopt(sys.argv[1:], "+hALp:T:m:")
18for 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)
43if len(args) < 1:
44 usage(sys.stderr)
45 sys.exit(1)
46if setlog:
47 logging.basicConfig(format="scgi-wsgi3(%(name)s): %(levelname)s: %(message)s")
48
49if 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
55try:
56 handlermod = __import__(args[0], fromlist = ["dummy"])
57except ImportError as exc:
58 sys.stderr.write("scgi-wsgi3: handler %s not found: %s\n" % (args[0], exc.args[0]))
59 sys.exit(1)
60if not modwsgi_compat:
61 if not hasattr(handlermod, "wmain"):
62 sys.stderr.write("scgi-wsgi3: handler %s has no `wmain' function\n" % args[0])
63 sys.exit(1)
64 handler = handlermod.wmain(*args[1:])
65else:
66 if not hasattr(handlermod, "application"):
67 sys.stderr.write("scgi-wsgi3: handler %s has no `application' object\n" % args[0])
68 sys.exit(1)
69 handler = handlermod.application
70
71def mkenv(head, sk):
72 try:
73 env = ashd.scgi.decodehead(head, "utf-8")
74 env["wsgi.uri_encoding"] = "utf-8"
75 except UnicodeError:
76 env = ashd.scgi.decodehead(head, "latin-1")
77 env["wsgi.uri_encoding"] = "latin-1"
78 env["wsgi.version"] = 1, 0
79 if "HTTP_X_ASH_PROTOCOL" in env:
80 env["wsgi.url_scheme"] = env["HTTP_X_ASH_PROTOCOL"]
81 elif "HTTPS" in env:
82 env["wsgi.url_scheme"] = "https"
83 else:
84 env["wsgi.url_scheme"] = "http"
85 env["wsgi.input"] = sk
86 env["wsgi.errors"] = sys.stderr
87 env["wsgi.multithread"] = True
88 env["wsgi.multiprocess"] = False
89 env["wsgi.run_once"] = False
90 return env
91
92def recode(thing):
93 if isinstance(thing, collections.ByteString):
94 return thing
95 else:
96 return str(thing).encode("latin-1")
97
98class reqthread(ashd.serve.wsgithread):
99 def __init__(self, sk):
100 super().__init__()
101 self.bsk = sk.dup()
102 self.sk = self.bsk.makefile("rwb")
103
104 def handlewsgi(self):
105 return handler(self.env, self.startreq)
106
107 def writehead(self, status, headers):
108 buf = bytearray()
109 buf += b"Status: " + recode(status) + b"\n"
110 for nm, val in headers:
111 buf += recode(nm) + b": " + recode(val) + b"\n"
112 buf += b"\n"
113 try:
114 self.sk.write(buf)
115 except IOError:
116 raise ashd.serve.closed()
117
118 def writedata(self, data):
119 try:
120 self.sk.write(data)
121 self.sk.flush()
122 except IOError:
123 raise ashd.serve.closed()
124
125 def handle(self):
126 head = ashd.scgi.readhead(self.sk)
127 self.env = mkenv(head, self.sk)
128 with ashd.perf.request(self.env) as reqevent:
129 super().handle()
130 if self.status:
131 reqevent.response([self.status, self.headers])
132
133 def run(self):
134 try:
135 super().run()
136 finally:
137 self.sk.close()
138 self.bsk.close()
139
140while True:
141 nsk, addr = sk.accept()
142 try:
143 reqthread(nsk).start()
144 finally:
145 nsk.close()