Code

More cleaning up of configuration, and the "instance" -> "tracker"
[roundup.git] / roundup / scripts / roundup_server.py
1 # Copyright (c) 2001 Bizar Software Pty Ltd (http://www.bizarsoftware.com.au/)
2 # This module is free software, and you may redistribute it and/or modify
3 # under the same terms as Python, so long as this copyright message and
4 # disclaimer are retained in their original form.
5 #
6 # IN NO EVENT SHALL BIZAR SOFTWARE PTY LTD BE LIABLE TO ANY PARTY FOR
7 # DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING
8 # OUT OF THE USE OF THIS CODE, EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE
9 # POSSIBILITY OF SUCH DAMAGE.
10 #
11 # BIZAR SOFTWARE PTY LTD SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
12 # BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
13 # FOR A PARTICULAR PURPOSE.  THE CODE PROVIDED HEREUNDER IS ON AN "AS IS"
14 # BASIS, AND THERE IS NO OBLIGATION WHATSOEVER TO PROVIDE MAINTENANCE,
15 # SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
16
17 """ HTTP Server that serves roundup.
19 $Id: roundup_server.py,v 1.10 2002-09-10 03:01:19 richard Exp $
20 """
22 # python version check
23 from roundup import version_check
25 import sys, os, urllib, StringIO, traceback, cgi, binascii, getopt, imp
26 import BaseHTTPServer
28 # Roundup modules of use here
29 from roundup.cgi import cgitb, client
30 import roundup.instance
31 from roundup.i18n import _
33 #
34 ##  Configuration
35 #
37 # This indicates where the Roundup instance lives
38 TRACKER_HOMES = {
39     'bar': '/tmp/bar',
40 }
42 ROUNDUP_USER = None
45 # Where to log debugging information to. Use an instance of DevNull if you
46 # don't want to log anywhere.
47 # TODO: actually use this stuff
48 #class DevNull:
49 #    def write(self, info):
50 #        pass
51 #LOG = open('/var/log/roundup.cgi.log', 'a')
52 #LOG = DevNull()
54 #
55 ##  end configuration
56 #
59 class RoundupRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
60     TRACKER_HOMES = TRACKER_HOMES
61     ROUNDUP_USER = ROUNDUP_USER
63     def run_cgi(self):
64         """ Execute the CGI command. Wrap an innner call in an error
65             handler so all errors can be caught.
66         """
67         save_stdin = sys.stdin
68         sys.stdin = self.rfile
69         try:
70             self.inner_run_cgi()
71         except client.NotFound:
72             self.send_error(404, self.path)
73         except client.Unauthorised:
74             self.send_error(403, self.path)
75         except:
76             # it'd be nice to be able to detect if these are going to have
77             # any effect...
78             self.send_response(400)
79             self.send_header('Content-Type', 'text/html')
80             self.end_headers()
81             try:
82                 reload(cgitb)
83                 self.wfile.write(cgitb.breaker())
84                 self.wfile.write(cgitb.html())
85             except:
86                 self.wfile.write("<pre>")
87                 s = StringIO.StringIO()
88                 traceback.print_exc(None, s)
89                 self.wfile.write(cgi.escape(s.getvalue()))
90                 self.wfile.write("</pre>\n")
91         sys.stdin = save_stdin
93     do_GET = do_POST = do_HEAD = send_head = run_cgi
95     def index(self):
96         ''' Print up an index of the available instances
97         '''
98         self.send_response(200)
99         self.send_header('Content-Type', 'text/html')
100         self.end_headers()
101         w = self.wfile.write
102         w(_('<html><head><title>Roundup instances index</title></head>\n'))
103         w(_('<body><h1>Roundup instances index</h1><ol>\n'))
104         for instance in self.TRACKER_HOMES.keys():
105             w(_('<li><a href="%(instance_url)s/index">%(instance_name)s</a>\n')%{
106                 'instance_url': urllib.quote(instance),
107                 'instance_name': cgi.escape(instance)})
108         w(_('</ol></body></html>'))
110     def inner_run_cgi(self):
111         ''' This is the inner part of the CGI handling
112         '''
114         rest = self.path
115         i = rest.rfind('?')
116         if i >= 0:
117             rest, query = rest[:i], rest[i+1:]
118         else:
119             query = ''
121         # figure the instance
122         if rest == '/':
123             return self.index()
124         l_path = rest.split('/')
125         instance_name = urllib.unquote(l_path[1])
126         if self.TRACKER_HOMES.has_key(instance_name):
127             instance_home = self.TRACKER_HOMES[instance_name]
128             instance = roundup.instance.open(instance_home)
129         else:
130             raise client.NotFound
132         # figure out what the rest of the path is
133         if len(l_path) > 2:
134             rest = '/'.join(l_path[2:])
135         else:
136             rest = '/'
138         # Set up the CGI environment
139         env = {}
140         env['TRACKER_NAME'] = instance_name
141         env['REQUEST_METHOD'] = self.command
142         env['PATH_INFO'] = urllib.unquote(rest)
143         if query:
144             env['QUERY_STRING'] = query
145         host = self.address_string()
146         if self.headers.typeheader is None:
147             env['CONTENT_TYPE'] = self.headers.type
148         else:
149             env['CONTENT_TYPE'] = self.headers.typeheader
150         length = self.headers.getheader('content-length')
151         if length:
152             env['CONTENT_LENGTH'] = length
153         co = filter(None, self.headers.getheaders('cookie'))
154         if co:
155             env['HTTP_COOKIE'] = ', '.join(co)
156         env['SCRIPT_NAME'] = ''
157         env['SERVER_NAME'] = self.server.server_name
158         env['SERVER_PORT'] = str(self.server.server_port)
159         env['HTTP_HOST'] = self.headers['host']
161         decoded_query = query.replace('+', ' ')
163         # do the roundup thang
164         c = instance.Client(instance, self, env)
165         c.main()
167 def usage(message=''):
168     if message:
169         message = _('Error: %(error)s\n\n')%{'error': message}
170     print _('''%(message)sUsage:
171 roundup-server [-n hostname] [-p port] [-l file] [-d file] [name=instance home]*
173  -n: sets the host name
174  -p: sets the port to listen on
175  -l: sets a filename to log to (instead of stdout)
176  -d: daemonize, and write the server's PID to the nominated file
178  name=instance home
179    Sets the instance home(s) to use. The name is how the instance is
180    identified in the URL (it's the first part of the URL path). The
181    instance home is the directory that was identified when you did
182    "roundup-admin init". You may specify any number of these name=home
183    pairs on the command-line. For convenience, you may edit the
184    TRACKER_HOMES variable in the roundup-server file instead.
185 ''')%locals()
186     sys.exit(0)
188 def daemonize(pidfile):
189     ''' Turn this process into a daemon.
190         - make sure the sys.std(in|out|err) are completely cut off
191         - make our parent PID 1
193         Write our new PID to the pidfile.
195         From A.M. Kuuchling (possibly originally Greg Ward) with
196         modification from Oren Tirosh, and finally a small mod from me.
197     '''
198     # Fork once
199     if os.fork() != 0:
200         os._exit(0)
202     # Create new session
203     os.setsid()
205     # Second fork to force PPID=1
206     pid = os.fork()
207     if pid:
208         pidfile = open(pidfile, 'w')
209         pidfile.write(str(pid))
210         pidfile.close()
211         os._exit(0)         
213     os.chdir("/")         
214     os.umask(0)
216     # close off sys.std(in|out|err), redirect to devnull so the file
217     # descriptors can't be used again
218     devnull = os.open('/dev/null', 0)
219     os.dup2(devnull, 0)
220     os.dup2(devnull, 1)
221     os.dup2(devnull, 2)
223 def run():
224     hostname = ''
225     port = 8080
226     pidfile = None
227     logfile = None
228     try:
229         # handle the command-line args
230         try:
231             optlist, args = getopt.getopt(sys.argv[1:], 'n:p:u:d:l:')
232         except getopt.GetoptError, e:
233             usage(str(e))
235         user = ROUNDUP_USER
236         for (opt, arg) in optlist:
237             if opt == '-n': hostname = arg
238             elif opt == '-p': port = int(arg)
239             elif opt == '-u': user = arg
240             elif opt == '-d': pidfile = arg
241             elif opt == '-l': logfile = arg
242             elif opt == '-h': usage()
244         if hasattr(os, 'getuid'):
245             # if root, setuid to the running user
246             if not os.getuid() and user is not None:
247                 try:
248                     import pwd
249                 except ImportError:
250                     raise ValueError, _("Can't change users - no pwd module")
251                 try:
252                     uid = pwd.getpwnam(user)[2]
253                 except KeyError:
254                     raise ValueError, _("User %(user)s doesn't exist")%locals()
255                 os.setuid(uid)
256             elif os.getuid() and user is not None:
257                 print _('WARNING: ignoring "-u" argument, not root')
259             # People can remove this check if they're really determined
260             if not os.getuid() and user is None:
261                 raise ValueError, _("Can't run as root!")
263         # handle instance specs
264         if args:
265             d = {}
266             for arg in args:
267                 try:
268                     name, home = arg.split('=')
269                 except ValueError:
270                     raise ValueError, _("Instances must be name=home")
271                 d[name] = home
272             RoundupRequestHandler.TRACKER_HOMES = d
273     except SystemExit:
274         raise
275     except:
276         exc_type, exc_value = sys.exc_info()[:2]
277         usage('%s: %s'%(exc_type, exc_value))
279     # we don't want the cgi module interpreting the command-line args ;)
280     sys.argv = sys.argv[:1]
281     address = (hostname, port)
283     # fork?
284     if pidfile:
285         daemonize(pidfile)
287     # redirect stdout/stderr to our logfile
288     if logfile:
289         sys.stdout = sys.stderr = open(logfile, 'a')
291     httpd = BaseHTTPServer.HTTPServer(address, RoundupRequestHandler)
292     print _('Roundup server started on %(address)s')%locals()
293     httpd.serve_forever()
295 if __name__ == '__main__':
296     run()
298 # vim: set filetype=python ts=4 sw=4 et si