Back to index

moin  1.9.0~rc2
scgi_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 scgi - an SCGI/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 SCGI and mod_scgi for Apache1/Apache2, see
00037 http://www.mems-exchange.org/software/scgi/.
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 scgi 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 
00069 __author__ = 'Allan Saddi <allan@saddi.com>'
00070 __version__ = '$Revision$'
00071 
00072 import logging
00073 import socket
00074 
00075 from flup.server import NoDefault
00076 from flup.server.scgi_base import BaseSCGIServer, Connection
00077 from flup.server.preforkserver import PreforkServer
00078 
00079 __all__ = ['WSGIServer']
00080 
00081 class WSGIServer(BaseSCGIServer, PreforkServer):
00082     """
00083     SCGI/WSGI server. For information about SCGI (Simple Common Gateway
00084     Interface), see http://www.mems-exchange.org/software/scgi/.
00085 
00086     This server is similar to SWAP http://www.idyll.org/~t/www-tools/wsgi/,
00087     another SCGI/WSGI server.
00088 
00089     It differs from SWAP in that it isn't based on scgi.scgi_server and
00090     therefore, it allows me to implement concurrency using threads. (Also,
00091     this server was written from scratch and really has no other depedencies.)
00092     Which server to use really boils down to whether you want multithreading
00093     or forking. (But as an aside, I've found scgi.scgi_server's implementation
00094     of preforking to be quite superior. So if your application really doesn't
00095     mind running in multiple processes, go use SWAP. ;)
00096     """
00097     def __init__(self, application, scriptName=NoDefault, environ=None,
00098                  bindAddress=('localhost', 4000), umask=None,
00099                  allowedServers=None,
00100                  loggingLevel=logging.INFO, debug=False, **kw):
00101         """
00102         scriptName is the initial portion of the URL path that "belongs"
00103         to your application. It is used to determine PATH_INFO (which doesn't
00104         seem to be passed in). An empty scriptName means your application
00105         is mounted at the root of your virtual host.
00106 
00107         environ, which must be a dictionary, can contain any additional
00108         environment variables you want to pass to your application.
00109 
00110         bindAddress is the address to bind to, which must be a string or
00111         a tuple of length 2. If a tuple, the first element must be a string,
00112         which is the host name or IPv4 address of a local interface. The
00113         2nd element of the tuple is the port number. If a string, it will
00114         be interpreted as a filename and a UNIX socket will be opened.
00115 
00116         If binding to a UNIX socket, umask may be set to specify what
00117         the umask is to be changed to before the socket is created in the
00118         filesystem. After the socket is created, the previous umask is
00119         restored.
00120 
00121         allowedServers must be None or a list of strings representing the
00122         IPv4 addresses of servers allowed to connect. None means accept
00123         connections from anywhere.
00124 
00125         loggingLevel sets the logging level of the module-level logger.
00126         """
00127         BaseSCGIServer.__init__(self, application,
00128                                 scriptName=scriptName,
00129                                 environ=environ,
00130                                 multithreaded=False,
00131                                 multiprocess=True,
00132                                 bindAddress=bindAddress,
00133                                 umask=umask,
00134                                 allowedServers=allowedServers,
00135                                 loggingLevel=loggingLevel,
00136                                 debug=debug)
00137         for key in ('multithreaded', 'multiprocess', 'jobClass', 'jobArgs'):
00138             if kw.has_key(key):
00139                 del kw[key]
00140         PreforkServer.__init__(self, jobClass=Connection, jobArgs=(self,), **kw)
00141 
00142     def run(self):
00143         """
00144         Main loop. Call this after instantiating WSGIServer. SIGHUP, SIGINT,
00145         SIGQUIT, SIGTERM cause it to cleanup and return. (If a SIGHUP
00146         is caught, this method returns True. Returns False otherwise.)
00147         """
00148         self.logger.info('%s starting up', self.__class__.__name__)
00149 
00150         try:
00151             sock = self._setupSocket()
00152         except socket.error, e:
00153             self.logger.error('Failed to bind socket (%s), exiting', e[1])
00154             return False
00155 
00156         ret = PreforkServer.run(self, sock)
00157 
00158         self._cleanupSocket(sock)
00159 
00160         self.logger.info('%s shutting down%s', self.__class__.__name__,
00161                          self._hupReceived and ' (reload requested)' or '')
00162 
00163         return ret
00164 
00165 if __name__ == '__main__':
00166     def test_app(environ, start_response):
00167         """Probably not the most efficient example."""
00168         import cgi
00169         start_response('200 OK', [('Content-Type', 'text/html')])
00170         yield '<html><head><title>Hello World!</title></head>\n' \
00171               '<body>\n' \
00172               '<p>Hello World!</p>\n' \
00173               '<table border="1">'
00174         names = environ.keys()
00175         names.sort()
00176         for name in names:
00177             yield '<tr><td>%s</td><td>%s</td></tr>\n' % (
00178                 name, cgi.escape(`environ[name]`))
00179 
00180         form = cgi.FieldStorage(fp=environ['wsgi.input'], environ=environ,
00181                                 keep_blank_values=1)
00182         if form.list:
00183             yield '<tr><th colspan="2">Form data</th></tr>'
00184 
00185         for field in form.list:
00186             yield '<tr><td>%s</td><td>%s</td></tr>\n' % (
00187                 field.name, field.value)
00188 
00189         yield '</table>\n' \
00190               '</body></html>\n'
00191 
00192     from wsgiref import validate
00193     test_app = validate.validator(test_app)
00194     WSGIServer(test_app,
00195                loggingLevel=logging.DEBUG).run()