~loggerhead-team/loggerhead/trunk-rich

« back to all changes in this revision

Viewing changes to serve-branches

  • Committer: Martin Pool
  • Date: 2009-01-23 22:36:38 UTC
  • mto: This revision was merged to the branch mainline in revision 298.
  • Revision ID: mbp@sourcefrog.net-20090123223638-s57mqtpu4um3stes
Act as a plugin only when loaded by bzr; update docs

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
#
2
 
# Copyright (C) 2008, 2009 Canonical Ltd
3
 
#
 
1
#!/usr/bin/env python
4
2
# This program is free software; you can redistribute it and/or modify
5
3
# it under the terms of the GNU General Public License as published by
6
4
# the Free Software Foundation; either version 2 of the License, or
21
19
import os
22
20
import sys
23
21
 
24
 
from bzrlib.plugin import load_plugins
 
22
from optparse import OptionParser
25
23
 
26
24
from paste import httpserver
27
 
from paste.httpexceptions import HTTPExceptionHandler, HTTPInternalServerError
 
25
from paste.httpexceptions import HTTPExceptionHandler
28
26
from paste.translogger import TransLogger
29
27
 
30
28
from loggerhead import __version__
31
 
from loggerhead.apps.transport import (
32
 
    BranchesFromTransportRoot, UserBranchesFromTransportRoot)
33
 
from loggerhead.config import LoggerheadConfig
 
29
from loggerhead.apps.filesystem import (
 
30
    BranchesFromFileSystemRoot, UserBranchesFromFileSystemRoot)
34
31
from loggerhead.util import Reloader
35
32
from loggerhead.apps.error import ErrorHandlerApp
36
33
 
37
34
 
38
 
def get_config_and_path(args):
39
 
    config = LoggerheadConfig(args)
40
 
 
41
 
    if config.get_option('show_version'):
42
 
        print "loggerhead %s" % (__version__,)
 
35
def command_line_parser():
 
36
    parser = OptionParser("%prog [options] <path>")
 
37
    parser.set_defaults(
 
38
        user_dirs=False,
 
39
        show_version=False,
 
40
        log_folder=None,
 
41
        )
 
42
    parser.add_option("--user-dirs", action="store_true", dest="user_dirs",
 
43
                      help="Serve user directories as ~user.")
 
44
    parser.add_option("--trunk-dir", metavar="DIR",
 
45
                      help="The directory that contains the trunk branches.")
 
46
    parser.add_option("--port", dest="user_port",
 
47
                      help=("Port Loggerhead should listen on "
 
48
                            "(defaults to 8080)."))
 
49
    parser.add_option("--host", dest="user_host",
 
50
                      help="Host Loggerhead should listen on.")
 
51
    parser.add_option("--prefix", dest="user_prefix",
 
52
                      help="Specify host prefix.")
 
53
    parser.add_option("--profile", action="store_true", dest="profile",
 
54
                      help="Generate callgrind profile data to "
 
55
                        "%d-stats.callgrind on each request.")
 
56
    parser.add_option("--reload", action="store_true", dest="reload",
 
57
                      help="Restarts the application when changing python"
 
58
                           " files. Only used for development purposes.")
 
59
    parser.add_option('--log-folder', dest="log_folder",
 
60
                      type=str, help="The directory to place log files in.")
 
61
    parser.add_option("--version", action="store_true", dest="show_version",
 
62
                      help="Print the software version and exit")
 
63
    return parser
 
64
 
 
65
 
 
66
def main(args):
 
67
    parser = command_line_parser()
 
68
    (options, args) = parser.parse_args(sys.argv[1:])
 
69
 
 
70
    if options.show_version:
 
71
        print "loggerhead %s" % __version__
43
72
        sys.exit(0)
44
73
 
45
 
    if config.arg_count > 1:
46
 
        config.print_help()
47
 
        sys.exit(1)
48
 
    elif config.arg_count == 1:
49
 
        base = config.get_arg(0)
50
 
    else:
51
 
        base = '.'
52
 
 
53
 
    if not config.get_option('allow_writes'):
54
 
        base = 'readonly+' + base
55
 
 
56
 
    return config, base
57
 
 
58
 
 
59
 
def setup_logging(config, init_logging=True, log_file=None):
60
 
    log_level = config.get_log_level()
61
 
    if init_logging:
62
 
        logging.basicConfig()
63
 
        if log_level is not None:
64
 
            logging.getLogger('').setLevel(log_level)
65
 
    logger = logging.getLogger('loggerhead')
66
 
    if log_level is not None:
67
 
        logger.setLevel(log_level)
68
 
    if log_file is not None:
69
 
        handler = logging.StreamHandler(log_file)
70
 
    else:
71
 
        if config.get_option('log_folder'):
72
 
            logfile_path = os.path.join(
73
 
                config.get_option('log_folder'), 'serve-branches.log')
74
 
        else:
75
 
            logfile_path = 'serve-branches.log'
76
 
        handler = logging.FileHandler(logfile_path, 'a')
77
 
        formatter = logging.Formatter('%(asctime)s %(levelname)-8s %(name)s:'
78
 
                                      ' %(message)s')
79
 
        handler.setFormatter(formatter)
80
 
    # We set the handler to accept all messages, the *logger* won't emit them
81
 
    # if it is configured to suppress it
82
 
    handler.setLevel(logging.DEBUG)
83
 
    logger.addHandler(handler)
84
 
    def _restrict_logging(logger_name):
85
 
        logger = logging.getLogger(logger_name)
86
 
        if logger.getEffectiveLevel() < logging.INFO:
87
 
            logger.setLevel(logging.INFO)
88
 
    # simpleTAL is *very* verbose in DEBUG mode, which is otherwise the
89
 
    # default. So quiet it up a bit.
90
 
    _restrict_logging('simpleTAL')
91
 
    _restrict_logging('simpleTALES')
92
 
    return logger
93
 
 
94
 
 
95
 
def make_app_for_config_and_path(config, base):
96
 
    if config.get_option('trunk_dir') and not config.get_option('user_dirs'):
 
74
    if len(args) > 1:
 
75
        parser.print_help()
 
76
        sys.exit(1)
 
77
    elif len(args) == 1:
 
78
        [path] = args
 
79
    else:
 
80
        path = '.'
 
81
 
 
82
    if not os.path.isdir(path):
 
83
        print "%s is not a directory" % path
 
84
        sys.exit(1)
 
85
 
 
86
    if options.trunk_dir and not options.user_dirs:
97
87
        print "--trunk-dir is only valid with --user-dirs"
98
88
        sys.exit(1)
99
89
 
100
 
    if config.get_option('reload'):
 
90
    if options.reload:
101
91
        if Reloader.is_installed():
102
92
            Reloader.install()
103
93
        else:
104
94
            return Reloader.restart_with_reloader()
105
95
 
106
 
    if config.get_option('user_dirs'):
107
 
        if not config.get_option('trunk_dir'):
 
96
    if options.user_dirs:
 
97
        if not options.trunk_dir:
108
98
            print "You didn't specify a directory for the trunk directories."
109
99
            sys.exit(1)
110
 
        app = UserBranchesFromTransportRoot(base, config)
111
 
    else:
112
 
        app = BranchesFromTransportRoot(base, config)
113
 
 
114
 
    setup_logging(config)
115
 
 
116
 
    if config.get_option('profile'):
 
100
        app = UserBranchesFromFileSystemRoot(path, options.trunk_dir)
 
101
    else:
 
102
        app = BranchesFromFileSystemRoot(path)
 
103
 
 
104
    # setup_logging()
 
105
    logging.basicConfig()
 
106
    logging.getLogger('').setLevel(logging.DEBUG)
 
107
    logger = getattr(app, 'log', logging.getLogger('loggerhead'))
 
108
    if options.log_folder:
 
109
        logfile_path = os.path.join(options.log_folder, 'serve-branches.log')
 
110
    else:
 
111
        logfile_path = 'serve-branches.log'
 
112
    logfile = logging.FileHandler(logfile_path, 'a')
 
113
    formatter = logging.Formatter('%(asctime)s %(levelname)-8s %(name)s:'
 
114
                                  ' %(message)s')
 
115
    logfile.setFormatter(formatter)
 
116
    logfile.setLevel(logging.DEBUG)
 
117
    logger.addHandler(logfile)
 
118
    # setup_logging() #end
 
119
    app = ErrorHandlerApp(app)
 
120
    app = HTTPExceptionHandler(app)
 
121
    app = TransLogger(app, logger=logger)
 
122
    if options.profile:
117
123
        from loggerhead.middleware.profile import LSProfMiddleware
118
124
        app = LSProfMiddleware(app)
119
 
    if config.get_option('memory_profile'):
120
 
        from dozer import Dozer
121
 
        app = Dozer(app)
122
125
 
123
 
    if not config.get_option('user_prefix'):
 
126
    if not options.user_prefix:
124
127
        prefix = '/'
125
128
    else:
126
 
        prefix = config.get_option('user_prefix')
127
 
        if not prefix.startswith('/'):
128
 
            prefix = '/' + prefix
 
129
        prefix = options.user_prefix
129
130
 
130
131
    try:
131
132
        from paste.deploy.config import PrefixMiddleware
132
133
    except ImportError:
133
 
        cant_proxy_correctly_message = (
134
 
            'Unsupported configuration: PasteDeploy not available, but '
135
 
            'loggerhead appears to be behind a proxy.')
136
 
        def check_not_proxied(app):
137
 
            def wrapped(environ, start_response):
138
 
                if 'HTTP_X_FORWARDED_SERVER' in environ:
139
 
                    exc = HTTPInternalServerError()
140
 
                    exc.explanation = cant_proxy_correctly_message
141
 
                    raise exc
142
 
                return app(environ, start_response)
143
 
            return wrapped
144
 
        app = check_not_proxied(app)
 
134
        pass
145
135
    else:
146
136
        app = PrefixMiddleware(app, prefix=prefix)
147
137
 
148
 
    app = HTTPExceptionHandler(app)
149
 
    app = ErrorHandlerApp(app)
150
 
    app = TransLogger(app, logger=logging.getLogger('loggerhead'))
151
 
 
152
 
    return app
153
 
 
154
 
 
155
 
def main(args):
156
 
    load_plugins()
157
 
 
158
 
    config, path = get_config_and_path(args)
159
 
 
160
 
    app = make_app_for_config_and_path(config, path)
161
 
 
162
 
    if not config.get_option('user_port'):
 
138
    if not options.user_port:
163
139
        port = '8080'
164
140
    else:
165
 
        port = config.get_option('user_port')
 
141
        port = options.user_port
166
142
 
167
 
    if not config.get_option('user_host'):
 
143
    if not options.user_host:
168
144
        host = '0.0.0.0'
169
145
    else:
170
 
        host = config.get_option('user_host')
171
 
 
172
 
    if not config.get_option('protocol'):
173
 
        protocol = 'http'
174
 
    else:
175
 
        protocol = config.get_option('protocol')
176
 
 
177
 
    if protocol == 'http':
178
 
        httpserver.serve(app, host=host, port=port)
179
 
    else:
180
 
        if protocol == 'fcgi':
181
 
            from flup.server.fcgi import WSGIServer
182
 
        elif protocol == 'scgi':
183
 
            from flup.server.scgi import WSGIServer
184
 
        elif protocol == 'ajp':
185
 
            from flup.server.ajp import WSGIServer
186
 
        else:
187
 
            print 'Unknown protocol: %s.' % (protocol)
188
 
            sys.exit(1)
189
 
        WSGIServer(app, bindAddress=(host, int(port))).run()
 
146
        host = options.user_host
 
147
 
 
148
    httpserver.serve(app, host=host, port=port)
 
149
 
 
150
 
 
151
if __name__ == "__main__":
 
152
    main(sys.argv)