Back to index

moin  1.9.0~rc2
ajp.py
Go to the documentation of this file.
00001 """
00002 .. highlight:: python
00003    :linenothreshold: 5
00004 
00005 .. highlight:: bash
00006    :linenothreshold: 5
00007 
00008 ajp - an AJP 1.3/WSGI gateway.
00009 
00010 :copyright: Copyright (c) 2005, 2006 Allan Saddi <allan@saddi.com>
00011   All rights reserved.
00012 :license:
00013 
00014  Redistribution and use in source and binary forms, with or without
00015  modification, are permitted provided that the following conditions
00016  are met:
00017 
00018  1. Redistributions of source code must retain the above copyright
00019     notice, this list of conditions and the following disclaimer.
00020  2. Redistributions in binary form must reproduce the above copyright
00021     notice, this list of conditions and the following disclaimer in the
00022     documentation and/or other materials provided with the distribution.
00023 
00024  THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS **AS IS** AND
00025  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
00026  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
00027  ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
00028  FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
00029  DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
00030  OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
00031  HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
00032  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
00033  OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
00034  SUCH DAMAGE.
00035 
00036 For more information about AJP and AJP connectors for your web server, see
00037 http://jakarta.apache.org/tomcat/connectors-doc/.
00038 
00039 For more information about the Web Server Gateway Interface, see
00040 http://www.python.org/peps/pep-0333.html.
00041 
00042 Example usage::
00043 
00044   #!/usr/bin/env python
00045   import sys
00046   from myapplication import app # Assume app is your WSGI application object
00047   from ajp import WSGIServer
00048   ret = WSGIServer(app).run()
00049   sys.exit(ret and 42 or 0)
00050 
00051 See the documentation for WSGIServer for more information.
00052 
00053 About the bit of logic at the end:
00054 Upon receiving SIGHUP, the python script will exit with status code 42. This
00055 can be used by a wrapper script to determine if the python script should be
00056 re-run. When a SIGINT or SIGTERM is received, the script exits with status
00057 code 0, possibly indicating a normal exit.
00058 
00059 Example wrapper script::
00060 
00061   #!/bin/sh
00062   STATUS=42
00063   while test $STATUS -eq 42; do
00064     python "$@" that_script_above.py
00065     STATUS=$?
00066   done
00067 
00068 Example workers.properties (for mod_jk)::
00069 
00070   worker.list=foo
00071   worker.foo.port=8009
00072   worker.foo.host=localhost
00073   worker.foo.type=ajp13
00074 
00075 Example httpd.conf (for mod_jk)::
00076 
00077   JkWorkersFile /path/to/workers.properties
00078   JkMount /* foo
00079 
00080 Note that if you mount your ajp application anywhere but the root ("/"), you
00081 SHOULD specifiy scriptName to the WSGIServer constructor. This will ensure
00082 that SCRIPT_NAME/PATH_INFO are correctly deduced.
00083 """
00084 
00085 __author__ = 'Allan Saddi <allan@saddi.com>'
00086 __version__ = '$Revision$'
00087 
00088 import socket
00089 import logging
00090 
00091 from flup.server.ajp_base import BaseAJPServer, Connection
00092 from flup.server.threadedserver import ThreadedServer
00093 
00094 __all__ = ['WSGIServer']
00095 
00096 class WSGIServer(BaseAJPServer, ThreadedServer):
00097     """
00098     AJP1.3/WSGI server. Runs your WSGI application as a persistant program
00099     that understands AJP1.3. Opens up a TCP socket, binds it, and then
00100     waits for forwarded requests from your webserver.
00101 
00102     Why AJP? Two good reasons are that AJP provides load-balancing and
00103     fail-over support. Personally, I just wanted something new to
00104     implement. :)
00105 
00106     Of course you will need an AJP1.3 connector for your webserver (e.g.
00107     mod_jk) - see http://jakarta.apache.org/tomcat/connectors-doc/.
00108     """
00109     def __init__(self, application, scriptName='', environ=None,
00110                  multithreaded=True, multiprocess=False,
00111                  bindAddress=('localhost', 8009), allowedServers=None,
00112                  loggingLevel=logging.INFO, debug=False, **kw):
00113         """
00114         scriptName is the initial portion of the URL path that "belongs"
00115         to your application. It is used to determine PATH_INFO (which doesn't
00116         seem to be passed in). An empty scriptName means your application
00117         is mounted at the root of your virtual host.
00118 
00119         environ, which must be a dictionary, can contain any additional
00120         environment variables you want to pass to your application.
00121 
00122         bindAddress is the address to bind to, which must be a tuple of
00123         length 2. The first element is a string, which is the host name
00124         or IPv4 address of a local interface. The 2nd element is the port
00125         number.
00126 
00127         allowedServers must be None or a list of strings representing the
00128         IPv4 addresses of servers allowed to connect. None means accept
00129         connections from anywhere.
00130 
00131         loggingLevel sets the logging level of the module-level logger.
00132         """
00133         BaseAJPServer.__init__(self, application,
00134                                scriptName=scriptName,
00135                                environ=environ,
00136                                multithreaded=multithreaded,
00137                                multiprocess=multiprocess,
00138                                bindAddress=bindAddress,
00139                                allowedServers=allowedServers,
00140                                loggingLevel=loggingLevel,
00141                                debug=debug)
00142         for key in ('jobClass', 'jobArgs'):
00143             if kw.has_key(key):
00144                 del kw[key]
00145         ThreadedServer.__init__(self, jobClass=Connection, jobArgs=(self,),
00146                                 **kw)
00147 
00148     def run(self):
00149         """
00150         Main loop. Call this after instantiating WSGIServer. SIGHUP, SIGINT,
00151         SIGQUIT, SIGTERM cause it to cleanup and return. (If a SIGHUP
00152         is caught, this method returns True. Returns False otherwise.)
00153         """
00154         self.logger.info('%s starting up', self.__class__.__name__)
00155 
00156         try:
00157             sock = self._setupSocket()
00158         except socket.error, e:
00159             self.logger.error('Failed to bind socket (%s), exiting', e[1])
00160             return False
00161 
00162         ret = ThreadedServer.run(self, sock)
00163 
00164         self._cleanupSocket(sock)
00165         # AJP connections are more or less persistent. .shutdown() will
00166         # not return until the web server lets go. So don't bother calling
00167         # it...
00168         #self.shutdown()
00169 
00170         self.logger.info('%s shutting down%s', self.__class__.__name__,
00171                          self._hupReceived and ' (reload requested)' or '')
00172 
00173         return ret
00174 
00175 if __name__ == '__main__':
00176     def test_app(environ, start_response):
00177         """Probably not the most efficient example."""
00178         import cgi
00179         start_response('200 OK', [('Content-Type', 'text/html')])
00180         yield '<html><head><title>Hello World!</title></head>\n' \
00181               '<body>\n' \
00182               '<p>Hello World!</p>\n' \
00183               '<table border="1">'
00184         names = environ.keys()
00185         names.sort()
00186         for name in names:
00187             yield '<tr><td>%s</td><td>%s</td></tr>\n' % (
00188                 name, cgi.escape(`environ[name]`))
00189 
00190         form = cgi.FieldStorage(fp=environ['wsgi.input'], environ=environ,
00191                                 keep_blank_values=1)
00192         if form.list:
00193             yield '<tr><th colspan="2">Form data</th></tr>'
00194 
00195         for field in form.list:
00196             yield '<tr><td>%s</td><td>%s</td></tr>\n' % (
00197                 field.name, field.value)
00198 
00199         yield '</table>\n' \
00200               '</body></html>\n'
00201 
00202     from wsgiref import validate
00203     test_app = validate.validator(test_app)
00204     # Explicitly set bindAddress to *:8009 for testing.
00205     WSGIServer(test_app,
00206                bindAddress=('', 8009), allowedServers=None,
00207                loggingLevel=logging.DEBUG).run()