~ubuntu-branches/ubuntu/natty/moin/natty-updates

« back to all changes in this revision

Viewing changes to MoinMoin/support/flup/server/ajp_fork.py

  • Committer: Bazaar Package Importer
  • Author(s): Jonas Smedegaard
  • Date: 2008-06-22 21:17:13 UTC
  • mto: This revision was merged to the branch mainline in revision 18.
  • Revision ID: james.westby@ubuntu.com-20080622211713-inlv5k4eifxckelr
ImportĀ upstreamĀ versionĀ 1.7.0

Show diffs side-by-side

added added

removed removed

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