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