X-Git-Url: http://www.dolda2000.com/gitweb/?p=ashd.git;a=blobdiff_plain;f=python%2Fashd%2Fwsgidir.py;h=77f41fb3971a1ca5c6fe6ca743593f484eab2cde;hp=037544d959c5fabf50e9c4895dd83fd5504776b6;hb=e9817feefe4f2ed35ded74f0ec2323ed3d0c09e4;hpb=c06db49a3a4bfbf14b1661b667e1ed1cbab2bcd0 diff --git a/python/ashd/wsgidir.py b/python/ashd/wsgidir.py index 037544d..77f41fb 100644 --- a/python/ashd/wsgidir.py +++ b/python/ashd/wsgidir.py @@ -1,7 +1,65 @@ +"""WSGI handler for serving chained WSGI modules from physical files + +The WSGI handler in this module examines the SCRIPT_FILENAME variable +of the requests it handles -- that is, the physical file corresponding +to the request, as determined by the webserver -- determining what to +do with the request based on the extension of that file. + +By default, it handles files named `.wsgi' by compiling them into +Python modules and using them, in turn, as chained WSGI handlers, but +handlers for other extensions can be installed as well. + +When handling `.wsgi' files, the compiled modules are cached and +reused until the file is modified, in which case the previous module +is discarded and the new file contents are loaded into a new module in +its place. When chaining such modules, an object named `wmain' is +first looked for and called with no arguments if found. The object it +returns is then used as the WSGI application object for that module, +which is reused until the module is reloaded. If `wmain' is not found, +an object named `application' is looked for instead. If found, it is +used directly as the WSGI application object. + +This module itself contains both an `application' and a `wmain' +object. If this module is used by ashd-wsgi(1) or scgi-wsgi(1) so that +its wmain function is called, arguments can be specified to it to +install handlers for other file extensions. Such arguments take the +form `.EXT=MODULE.HANDLER', where EXT is the file extension to be +handled, and the MODULE.HANDLER string is treated by splitting it +along its last constituent dot. The part left of the dot is the name +of a module which is imported, and the part right of the dot is the +name of an object in that module, which should be a callable adhering +to the WSGI specification. When called, this module will have made +sure that the WSGI environment contains the SCRIPT_FILENAME parameter +and that it is properly working. For example, the argument +`.fpy=my.module.foohandler' can be given to pass requests for `.fpy' +files to the function `foohandler' in the module `my.module' (which +must, of course, be importable). When writing such handler functions, +you will probably want to use the getmod() function in this module. +""" + import os, threading, types import wsgiutil -exts = {} +__all__ = ["application", "wmain", "getmod", "cachedmod"] + +class cachedmod(object): + """Cache entry for modules loaded by getmod() + + Instances of this class are returned by the getmod() + function. They contain three data attributes: + * mod - The loaded module + * lock - A threading.Lock object, which can be used for + manipulating this instance in a thread-safe manner + * mtime - The time the file was last modified + + Additional data attributes can be arbitrarily added for recording + any meta-data about the module. + """ + def __init__(self, mod = None, mtime = -1): + self.lock = threading.Lock() + self.mod = mod + self.mtime = mtime + modcache = {} cachelock = threading.Lock() @@ -15,48 +73,119 @@ def mangle(path): return ret def getmod(path): + """Load the given file as a module, caching it appropriately + + The given file is loaded and compiled into a Python module. The + compiled module is cached and returned upon subsequent requests + for the same file, unless the file has changed (as determined by + its mtime), in which case the cached module is discarded and the + new file contents are reloaded in its place. + + The return value is an instance of the cachedmod class, which can + be used for locking purposes and for storing arbitrary meta-data + about the module. See its documentation for details. + """ sb = os.stat(path) cachelock.acquire() try: if path in modcache: - mod, mtime = modcache[path] - if sb.st_mtime <= mtime: - return mod - f = open(path) - try: - text = f.read() - finally: - f.close() - code = compile(text, path, "exec") - mod = types.ModuleType(mangle(path)) - mod.__file__ = path - exec code in mod.__dict__ - modcache[path] = mod, sb.st_mtime - return mod + entry = modcache[path] + else: + entry = cachedmod() + modcache[path] = entry finally: cachelock.release() + entry.lock.acquire() + try: + if entry.mod is None or sb.st_mtime > entry.mtime: + f = open(path, "r") + try: + text = f.read() + finally: + f.close() + code = compile(text, path, "exec") + mod = types.ModuleType(mangle(path)) + mod.__file__ = path + exec code in mod.__dict__ + entry.mod = mod + entry.mtime = sb.st_mtime + return entry + finally: + entry.lock.release() -def chain(path, env, startreq): - mod = getmod(path) - if hasattr(mod, "wmain"): - return (mod.wmain())(env, startreq) - elif hasattr(mod, "application"): - return mod.application(env, startreq) - return wsgi.simpleerror(env, startreq, 500, "Internal Error", "Invalid WSGI handler.") -exts["wsgi"] = chain - -def application(env, startreq): - if not "SCRIPT_FILENAME" in env: - return wsgiutil.simplerror(env, startreq, 500, "Internal Error", "The server is erroneously configured.") +class handler(object): + def __init__(self): + self.lock = threading.Lock() + self.handlers = {} + self.exts = {} + self.addext("wsgi", "chain") + self.addext("wsgi2", "chain") + + def resolve(self, name): + self.lock.acquire() + try: + if name in self.handlers: + return self.handlers[name] + p = name.rfind('.') + if p < 0: + return globals()[name] + mname = name[:p] + hname = name[p + 1:] + mod = __import__(mname, fromlist = ["dummy"]) + ret = getattr(mod, hname) + self.handlers[name] = ret + return ret + finally: + self.lock.release() + + def addext(self, ext, handler): + self.exts[ext] = self.resolve(handler) + + def handle(self, env, startreq): + if not "SCRIPT_FILENAME" in env: + return wsgiutil.simpleerror(env, startreq, 500, "Internal Error", "The server is erroneously configured.") + path = env["SCRIPT_FILENAME"] + base = os.path.basename(path) + p = base.rfind('.') + if p < 0 or not os.access(path, os.R_OK): + return wsgiutil.simpleerror(env, startreq, 500, "Internal Error", "The server is erroneously configured.") + ext = base[p + 1:] + if not ext in self.exts: + return wsgiutil.simpleerror(env, startreq, 500, "Internal Error", "The server is erroneously configured.") + return(self.exts[ext](env, startreq)) + +def wmain(*argv): + """Main function for ashd(7)-compatible WSGI handlers + + Returns the `application' function. If any arguments are given, + they are parsed according to the module documentation. + """ + ret = handler() + for arg in argv: + if arg[0] == '.': + p = arg.index('=') + ret.addext(arg[1:p], arg[p + 1:]) + return ret.handle + +def chain(env, startreq): path = env["SCRIPT_FILENAME"] - base = os.path.basename(path) - p = base.rfind('.') - if p < 0 or not os.access(path, os.R_OK): - return wsgiutil.simplerror(env, startreq, 500, "Internal Error", "The server is erroneously configured.") - ext = base[p + 1:] - if not ext in exts: - return wsgiutil.simplerror(env, startreq, 500, "Internal Error", "The server is erroneously configured.") - return(exts[ext](path, env, startreq)) - -def wmain(argv): - return application + mod = getmod(path) + entry = None + if mod is not None: + mod.lock.acquire() + try: + if hasattr(mod, "entry"): + entry = mod.entry + else: + if hasattr(mod.mod, "wmain"): + entry = mod.mod.wmain() + elif hasattr(mod.mod, "application"): + entry = mod.mod.application + mod.entry = entry + finally: + mod.lock.release() + if entry is not None: + return entry(env, startreq) + return wsgiutil.simpleerror(env, startreq, 500, "Internal Error", "Invalid WSGI handler.") + +application = handler().handle