Back to index

moin  1.9.0~rc2
ajp_fork.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.preforkserver import PreforkServer
00093 
00094 __all__ = ['WSGIServer']
00095 
00096 class WSGIServer(BaseAJPServer, PreforkServer):
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                  bindAddress=('localhost', 8009), allowedServers=None,
00111                  loggingLevel=logging.INFO, debug=False, **kw):
00112         """
00113         scriptName is the initial portion of the URL path that "belongs"
00114         to your application. It is used to determine PATH_INFO (which doesn't
00115         seem to be passed in). An empty scriptName means your application
00116         is mounted at the root of your virtual host.
00117 
00118         environ, which must be a dictionary, can contain any additional
00119         environment variables you want to pass to your application.
00120 
00121         bindAddress is the address to bind to, which must be a tuple of
00122         length 2. The first element is a string, which is the host name
00123         or IPv4 address of a local interface. The 2nd element is the port
00124         number.
00125 
00126         allowedServers must be None or a list of strings representing the
00127         IPv4 addresses of servers allowed to connect. None means accept
00128         connections from anywhere.
00129 
00130         loggingLevel sets the logging level of the module-level logger.
00131         """
00132         BaseAJPServer.__init__(self, application,
00133                                scriptName=scriptName,
00134                                environ=environ,
00135                                multithreaded=False,
00136                                multiprocess=True,
00137                                bindAddress=bindAddress,
00138                                allowedServers=allowedServers,
00139                                loggingLevel=loggingLevel,
00140                                debug=debug)
00141         for key in ('multithreaded', 'multiprocess', 'jobClass', 'jobArgs'):
00142             if kw.has_key(key):
00143                 del kw[key]
00144         PreforkServer.__init__(self, jobClass=Connection, jobArgs=(self,), **kw)
00145 
00146     def run(self):
00147         """
00148         Main loop. Call this after instantiating WSGIServer. SIGHUP, SIGINT,
00149         SIGQUIT, SIGTERM cause it to cleanup and return. (If a SIGHUP
00150         is caught, this method returns True. Returns False otherwise.)
00151         """
00152         self.logger.info('%s starting up', self.__class__.__name__)
00153 
00154         try:
00155             sock = self._setupSocket()
00156         except socket.error, e:
00157             self.logger.error('Failed to bind socket (%s), exiting', e[1])
00158             return False
00159 
00160         ret = PreforkServer.run(self, sock)
00161 
00162         self._cleanupSocket(sock)
00163 
00164         self.logger.info('%s shutting down%s', self.__class__.__name__,
00165                          self._hupReceived and ' (reload requested)' or '')
00166 
00167         return ret
00168 
00169 if __name__ == '__main__':
00170     def test_app(environ, start_response):
00171         """Probably not the most efficient example."""
00172         import cgi
00173         start_response('200 OK', [('Content-Type', 'text/html')])
00174         yield '<html><head><title>Hello World!</title></head>\n' \
00175               '<body>\n' \
00176               '<p>Hello World!</p>\n' \
00177               '<table border="1">'
00178         names = environ.keys()
00179         names.sort()
00180         for name in names:
00181             yield '<tr><td>%s</td><td>%s</td></tr>\n' % (
00182                 name, cgi.escape(`environ[name]`))
00183 
00184         form = cgi.FieldStorage(fp=environ['wsgi.input'], environ=environ,
00185                                 keep_blank_values=1)
00186         if form.list:
00187             yield '<tr><th colspan="2">Form data</th></tr>'
00188 
00189         for field in form.list:
00190             yield '<tr><td>%s</td><td>%s</td></tr>\n' % (
00191                 field.name, field.value)
00192 
00193         yield '</table>\n' \
00194               '</body></html>\n'
00195 
00196     from wsgiref import validate
00197     test_app = validate.validator(test_app)
00198     # Explicitly set bindAddress to *:8009 for testing.
00199     WSGIServer(test_app,
00200                bindAddress=('', 8009), allowedServers=None,
00201                loggingLevel=logging.DEBUG).run()