python: Include `chain' in __all__ of ashd.wsgidir.
[ashd.git] / python3 / ashd / wsgidir.py
1 """WSGI handler for serving chained WSGI modules from physical files
2
3 The WSGI handler in this module ensures that the SCRIPT_FILENAME
4 variable is properly set in every request and points out a file that
5 exists and is readable. It then dispatches the request in one of two
6 ways: If the header X-Ash-Python-Handler is set in the request, its
7 value is used as the name of a handler object to dispatch the request
8 to; otherwise, the file extension of the SCRIPT_FILENAME is used to
9 determine the handler object.
10
11 The name of a handler object is specified as a string, which is split
12 along its last constituent dot. The part left of the dot is the name
13 of a module, which is imported; and the part right of the dot is the
14 name of an object in that module, which should be a callable adhering
15 to the WSGI specification. Alternatively, the module part may be
16 omitted (such that the name is a string with no dots), in which case
17 the handler object is looked up from this module.
18
19 By default, this module will handle files with the extensions `.wsgi'
20 or `.wsgi3' using the `chain' handler, which chainloads such files and
21 runs them as independent WSGI applications. See its documentation for
22 details.
23
24 This module itself contains both an `application' and a `wmain'
25 object. If this module is used by ashd-wsgi(1) or scgi-wsgi(1) so that
26 its wmain function is called, arguments can be specified to it to
27 install handlers for other file extensions. Such arguments take the
28 form `.EXT=HANDLER', where EXT is the file extension to be handled,
29 and HANDLER is a handler name, as described above. For example, the
30 argument `.fpy=my.module.foohandler' can be given to pass requests for
31 `.fpy' files to the function `foohandler' in the module `my.module'
32 (which must, of course, be importable). When writing such handler
33 functions, you may want to use the getmod() function in this module.
34 """
35
36 import os, threading, types, importlib
37 from . import wsgiutil
38
39 __all__ = ["application", "wmain", "getmod", "cachedmod", "chain"]
40
41 class cachedmod(object):
42     """Cache entry for modules loaded by getmod()
43
44     Instances of this class are returned by the getmod()
45     function. They contain three data attributes:
46      * mod - The loaded module
47      * lock - A threading.Lock object, which can be used for
48        manipulating this instance in a thread-safe manner
49      * mtime - The time the file was last modified
50
51     Additional data attributes can be arbitrarily added for recording
52     any meta-data about the module.
53     """
54     def __init__(self, mod = None, mtime = -1):
55         self.lock = threading.Lock()
56         self.mod = mod
57         self.mtime = mtime
58
59 modcache = {}
60 cachelock = threading.Lock()
61
62 def mangle(path):
63     ret = ""
64     for c in path:
65         if c.isalnum():
66             ret += c
67         else:
68             ret += "_"
69     return ret
70
71 def getmod(path):
72     """Load the given file as a module, caching it appropriately
73
74     The given file is loaded and compiled into a Python module. The
75     compiled module is cached and returned upon subsequent requests
76     for the same file, unless the file has changed (as determined by
77     its mtime), in which case the cached module is discarded and the
78     new file contents are reloaded in its place.
79
80     The return value is an instance of the cachedmod class, which can
81     be used for locking purposes and for storing arbitrary meta-data
82     about the module. See its documentation for details.
83     """
84     sb = os.stat(path)
85     with cachelock:
86         if path in modcache:
87             entry = modcache[path]
88         else:
89             entry = cachedmod()
90             modcache[path] = entry
91     with entry.lock:
92         if entry.mod is None or sb.st_mtime > entry.mtime:
93             with open(path, "rb") as f:
94                 text = f.read()
95             code = compile(text, path, "exec")
96             mod = types.ModuleType(mangle(path))
97             mod.__file__ = path
98             exec(code, mod.__dict__)
99             entry.mod = mod
100             entry.mtime = sb.st_mtime
101         return entry
102
103 class handler(object):
104     def __init__(self):
105         self.lock = threading.Lock()
106         self.handlers = {}
107         self.exts = {}
108         self.addext("wsgi", "chain")
109         self.addext("wsgi3", "chain")
110
111     def resolve(self, name):
112         with self.lock:
113             if name in self.handlers:
114                 return self.handlers[name]
115             p = name.rfind('.')
116             if p < 0:
117                 return globals()[name]
118             mname = name[:p]
119             hname = name[p + 1:]
120             mod = importlib.import_module(mname)
121             ret = getattr(mod, hname)
122             self.handlers[name] = ret
123             return ret
124         
125     def addext(self, ext, handler):
126         self.exts[ext] = self.resolve(handler)
127
128     def handle(self, env, startreq):
129         if not "SCRIPT_FILENAME" in env:
130             return wsgiutil.simpleerror(env, startreq, 500, "Internal Error", "The server is erroneously configured.")
131         path = env["SCRIPT_FILENAME"]
132         if not os.access(path, os.R_OK):
133             return wsgiutil.simpleerror(env, startreq, 500, "Internal Error", "The server is erroneously configured.")
134         if "HTTP_X_ASH_PYTHON_HANDLER" in env:
135             handler = self.resolve(env["HTTP_X_ASH_PYTHON_HANDLER"])
136         else:
137             base = os.path.basename(path)
138             p = base.rfind('.')
139             if p < 0:
140                 return wsgiutil.simpleerror(env, startreq, 500, "Internal Error", "The server is erroneously configured.")
141             ext = base[p + 1:]
142             if not ext in self.exts:
143                 return wsgiutil.simpleerror(env, startreq, 500, "Internal Error", "The server is erroneously configured.")
144             handler = self.exts[ext]
145         return handler(env, startreq)
146
147 def wmain(*argv):
148     """Main function for ashd(7)-compatible WSGI handlers
149
150     Returns the `application' function. If any arguments are given,
151     they are parsed according to the module documentation.
152     """
153     ret = handler()
154     for arg in argv:
155         if arg[0] == '.':
156             p = arg.index('=')
157             ret.addext(arg[1:p], arg[p + 1:])
158     return ret.handle
159
160 def chain(env, startreq):
161     """Chain-loading WSGI handler
162     
163     This handler loads requested files, compiles them and loads them
164     into their own modules. The compiled modules are cached and reused
165     until the file is modified, in which case the previous module is
166     discarded and the new file contents are loaded into a new module
167     in its place. When chaining such modules, an object named `wmain'
168     is first looked for and called with no arguments if found. The
169     object it returns is then used as the WSGI application object for
170     that module, which is reused until the module is reloaded. If
171     `wmain' is not found, an object named `application' is looked for
172     instead. If found, it is used directly as the WSGI application
173     object.
174     """
175     path = env["SCRIPT_FILENAME"]
176     mod = getmod(path)
177     entry = None
178     if mod is not None:
179         with mod.lock:
180             if hasattr(mod, "entry"):
181                 entry = mod.entry
182             else:
183                 if hasattr(mod.mod, "wmain"):
184                     entry = mod.mod.wmain()
185                 elif hasattr(mod.mod, "application"):
186                     entry = mod.mod.application
187                 mod.entry = entry
188     if entry is not None:
189         return entry(env, startreq)
190     return wsgiutil.simpleerror(env, startreq, 500, "Internal Error", "Invalid WSGI handler.")
191
192 application = handler().handle