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

« back to all changes in this revision

Viewing changes to MoinMoin/support/flup/server/ajp.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.threadedserver import ThreadedServer
93
 
 
94
 
__all__ = ['WSGIServer']
95
 
 
96
 
class WSGIServer(BaseAJPServer, ThreadedServer):
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
 
                 multithreaded=True, multiprocess=False,
111
 
                 bindAddress=('localhost', 8009), allowedServers=None,
112
 
                 loggingLevel=logging.INFO, debug=False, **kw):
113
 
        """
114
 
        scriptName is the initial portion of the URL path that "belongs"
115
 
        to your application. It is used to determine PATH_INFO (which doesn't
116
 
        seem to be passed in). An empty scriptName means your application
117
 
        is mounted at the root of your virtual host.
118
 
 
119
 
        environ, which must be a dictionary, can contain any additional
120
 
        environment variables you want to pass to your application.
121
 
 
122
 
        bindAddress is the address to bind to, which must be a tuple of
123
 
        length 2. The first element is a string, which is the host name
124
 
        or IPv4 address of a local interface. The 2nd element is the port
125
 
        number.
126
 
 
127
 
        allowedServers must be None or a list of strings representing the
128
 
        IPv4 addresses of servers allowed to connect. None means accept
129
 
        connections from anywhere.
130
 
 
131
 
        loggingLevel sets the logging level of the module-level logger.
132
 
        """
133
 
        BaseAJPServer.__init__(self, application,
134
 
                               scriptName=scriptName,
135
 
                               environ=environ,
136
 
                               multithreaded=multithreaded,
137
 
                               multiprocess=multiprocess,
138
 
                               bindAddress=bindAddress,
139
 
                               allowedServers=allowedServers,
140
 
                               loggingLevel=loggingLevel,
141
 
                               debug=debug)
142
 
        for key in ('jobClass', 'jobArgs'):
143
 
            if kw.has_key(key):
144
 
                del kw[key]
145
 
        ThreadedServer.__init__(self, jobClass=Connection,
146
 
                                jobArgs=(self, None), **kw)
147
 
 
148
 
    def run(self):
149
 
        """
150
 
        Main loop. Call this after instantiating WSGIServer. SIGHUP, SIGINT,
151
 
        SIGQUIT, SIGTERM cause it to cleanup and return. (If a SIGHUP
152
 
        is caught, this method returns True. Returns False otherwise.)
153
 
        """
154
 
        self.logger.info('%s starting up', self.__class__.__name__)
155
 
 
156
 
        try:
157
 
            sock = self._setupSocket()
158
 
        except socket.error, e:
159
 
            self.logger.error('Failed to bind socket (%s), exiting', e[1])
160
 
            return False
161
 
 
162
 
        ret = ThreadedServer.run(self, sock)
163
 
 
164
 
        self._cleanupSocket(sock)
165
 
        # AJP connections are more or less persistent. .shutdown() will
166
 
        # not return until the web server lets go. So don't bother calling
167
 
        # it...
168
 
        #self.shutdown()
169
 
 
170
 
        self.logger.info('%s shutting down%s', self.__class__.__name__,
171
 
                         self._hupReceived and ' (reload requested)' or '')
172
 
 
173
 
        return ret
174
 
 
175
 
if __name__ == '__main__':
176
 
    def test_app(environ, start_response):
177
 
        """Probably not the most efficient example."""
178
 
        import cgi
179
 
        start_response('200 OK', [('Content-Type', 'text/html')])
180
 
        yield '<html><head><title>Hello World!</title></head>\n' \
181
 
              '<body>\n' \
182
 
              '<p>Hello World!</p>\n' \
183
 
              '<table border="1">'
184
 
        names = environ.keys()
185
 
        names.sort()
186
 
        for name in names:
187
 
            yield '<tr><td>%s</td><td>%s</td></tr>\n' % (
188
 
                name, cgi.escape(`environ[name]`))
189
 
 
190
 
        form = cgi.FieldStorage(fp=environ['wsgi.input'], environ=environ,
191
 
                                keep_blank_values=1)
192
 
        if form.list:
193
 
            yield '<tr><th colspan="2">Form data</th></tr>'
194
 
 
195
 
        for field in form.list:
196
 
            yield '<tr><td>%s</td><td>%s</td></tr>\n' % (
197
 
                field.name, field.value)
198
 
 
199
 
        yield '</table>\n' \
200
 
              '</body></html>\n'
201
 
 
202
 
    from wsgiref import validate
203
 
    test_app = validate.validator(test_app)
204
 
    # Explicitly set bindAddress to *:8009 for testing.
205
 
    WSGIServer(test_app,
206
 
               bindAddress=('', 8009), allowedServers=None,
207
 
               loggingLevel=logging.DEBUG).run()