ajp_fork.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. # Copyright (c) 2005, 2006 Allan Saddi <allan@saddi.com>
  2. # All rights reserved.
  3. #
  4. # Redistribution and use in source and binary forms, with or without
  5. # modification, are permitted provided that the following conditions
  6. # are met:
  7. # 1. Redistributions of source code must retain the above copyright
  8. # notice, this list of conditions and the following disclaimer.
  9. # 2. Redistributions in binary form must reproduce the above copyright
  10. # notice, this list of conditions and the following disclaimer in the
  11. # documentation and/or other materials provided with the distribution.
  12. #
  13. # THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
  14. # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  15. # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  16. # ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  17. # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  18. # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  19. # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  20. # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  21. # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  22. # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  23. # SUCH DAMAGE.
  24. #
  25. # $Id$
  26. """
  27. ajp - an AJP 1.3/WSGI gateway.
  28. For more information about AJP and AJP connectors for your web server, see
  29. <http://jakarta.apache.org/tomcat/connectors-doc/>.
  30. For more information about the Web Server Gateway Interface, see
  31. <http://www.python.org/peps/pep-0333.html>.
  32. Example usage:
  33. #!/usr/bin/env python
  34. import sys
  35. from myapplication import app # Assume app is your WSGI application object
  36. from ajp import WSGIServer
  37. ret = WSGIServer(app).run()
  38. sys.exit(ret and 42 or 0)
  39. See the documentation for WSGIServer for more information.
  40. About the bit of logic at the end:
  41. Upon receiving SIGHUP, the python script will exit with status code 42. This
  42. can be used by a wrapper script to determine if the python script should be
  43. re-run. When a SIGINT or SIGTERM is received, the script exits with status
  44. code 0, possibly indicating a normal exit.
  45. Example wrapper script:
  46. #!/bin/sh
  47. STATUS=42
  48. while test $STATUS -eq 42; do
  49. python "$@" that_script_above.py
  50. STATUS=$?
  51. done
  52. Example workers.properties (for mod_jk):
  53. worker.list=foo
  54. worker.foo.port=8009
  55. worker.foo.host=localhost
  56. worker.foo.type=ajp13
  57. Example httpd.conf (for mod_jk):
  58. JkWorkersFile /path/to/workers.properties
  59. JkMount /* foo
  60. Note that if you mount your ajp application anywhere but the root ("/"), you
  61. SHOULD specifiy scriptName to the WSGIServer constructor. This will ensure
  62. that SCRIPT_NAME/PATH_INFO are correctly deduced.
  63. """
  64. __author__ = 'Allan Saddi <allan@saddi.com>'
  65. __version__ = '$Revision$'
  66. import socket
  67. import logging
  68. from flup.server.ajp_base import BaseAJPServer, Connection
  69. from flup.server.preforkserver import PreforkServer
  70. __all__ = ['WSGIServer']
  71. class WSGIServer(BaseAJPServer, PreforkServer):
  72. """
  73. AJP1.3/WSGI server. Runs your WSGI application as a persistant program
  74. that understands AJP1.3. Opens up a TCP socket, binds it, and then
  75. waits for forwarded requests from your webserver.
  76. Why AJP? Two good reasons are that AJP provides load-balancing and
  77. fail-over support. Personally, I just wanted something new to
  78. implement. :)
  79. Of course you will need an AJP1.3 connector for your webserver (e.g.
  80. mod_jk) - see <http://jakarta.apache.org/tomcat/connectors-doc/>.
  81. """
  82. def __init__(self, application, scriptName='', environ=None,
  83. bindAddress=('localhost', 8009), allowedServers=None,
  84. loggingLevel=logging.INFO, debug=True, **kw):
  85. """
  86. scriptName is the initial portion of the URL path that "belongs"
  87. to your application. It is used to determine PATH_INFO (which doesn't
  88. seem to be passed in). An empty scriptName means your application
  89. is mounted at the root of your virtual host.
  90. environ, which must be a dictionary, can contain any additional
  91. environment variables you want to pass to your application.
  92. bindAddress is the address to bind to, which must be a tuple of
  93. length 2. The first element is a string, which is the host name
  94. or IPv4 address of a local interface. The 2nd element is the port
  95. number.
  96. allowedServers must be None or a list of strings representing the
  97. IPv4 addresses of servers allowed to connect. None means accept
  98. connections from anywhere.
  99. loggingLevel sets the logging level of the module-level logger.
  100. """
  101. BaseAJPServer.__init__(self, application,
  102. scriptName=scriptName,
  103. environ=environ,
  104. multithreaded=False,
  105. multiprocess=True,
  106. bindAddress=bindAddress,
  107. allowedServers=allowedServers,
  108. loggingLevel=loggingLevel,
  109. debug=debug)
  110. for key in ('multithreaded', 'multiprocess', 'jobClass', 'jobArgs'):
  111. if kw.has_key(key):
  112. del kw[key]
  113. PreforkServer.__init__(self, jobClass=Connection, jobArgs=(self,), **kw)
  114. def run(self):
  115. """
  116. Main loop. Call this after instantiating WSGIServer. SIGHUP, SIGINT,
  117. SIGQUIT, SIGTERM cause it to cleanup and return. (If a SIGHUP
  118. is caught, this method returns True. Returns False otherwise.)
  119. """
  120. self.logger.info('%s starting up', self.__class__.__name__)
  121. try:
  122. sock = self._setupSocket()
  123. except socket.error, e:
  124. self.logger.error('Failed to bind socket (%s), exiting', e[1])
  125. return False
  126. ret = PreforkServer.run(self, sock)
  127. self._cleanupSocket(sock)
  128. self.logger.info('%s shutting down%s', self.__class__.__name__,
  129. self._hupReceived and ' (reload requested)' or '')
  130. return ret
  131. if __name__ == '__main__':
  132. def test_app(environ, start_response):
  133. """Probably not the most efficient example."""
  134. import cgi
  135. start_response('200 OK', [('Content-Type', 'text/html')])
  136. yield '<html><head><title>Hello World!</title></head>\n' \
  137. '<body>\n' \
  138. '<p>Hello World!</p>\n' \
  139. '<table border="1">'
  140. names = environ.keys()
  141. names.sort()
  142. for name in names:
  143. yield '<tr><td>%s</td><td>%s</td></tr>\n' % (
  144. name, cgi.escape(`environ[name]`))
  145. form = cgi.FieldStorage(fp=environ['wsgi.input'], environ=environ,
  146. keep_blank_values=1)
  147. if form.list:
  148. yield '<tr><th colspan="2">Form data</th></tr>'
  149. for field in form.list:
  150. yield '<tr><td>%s</td><td>%s</td></tr>\n' % (
  151. field.name, field.value)
  152. yield '</table>\n' \
  153. '</body></html>\n'
  154. from wsgiref import validate
  155. test_app = validate.validator(test_app)
  156. # Explicitly set bindAddress to *:8009 for testing.
  157. WSGIServer(test_app,
  158. bindAddress=('', 8009), allowedServers=None,
  159. loggingLevel=logging.DEBUG).run()