~mnordhoff/loggerhead/cheezum

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
#
# Copyright (C) 2008, 2009 Canonical Ltd
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

"""Search for branches underneath a directory and serve them all."""

import logging
import os
import sys

from bzrlib.plugin import load_plugins

from paste import httpserver
from paste.httpexceptions import (
    HTTPExceptionHandler,
    HTTPForbidden,
    HTTPInternalServerError,
    HTTPMovedPermanently,
    )
from paste.translogger import TransLogger

from loggerhead import __version__
from loggerhead import config as _mod_config
from loggerhead.apps.transport import (
    BranchesFromTransportRoot, UserBranchesFromTransportRoot)
from loggerhead.util import Reloader
from loggerhead.apps.error import ErrorHandlerApp


def get_config_and_path(args):
    default_args = [
        '--port', '8004',
        '--host', '127.0.0.1',
        '--prefix', '/loggerhead',
        '--use-cdn',
        # Use a persistent cache directory
        # I'm disabling this code because the cache just got corrupted, so it's
        # safer when a new cache is created every time LH starts. I thought of
        # this issue when I originally wrote this code, but I never thought it
        # would actually happen.
        #'--cache-dir', '/home/mnordhoff/loggerhead/cache',
        '/srv/bzr',
    ]
    args = default_args + args

    config = _mod_config.LoggerheadConfig(args)

    if config.get_option('show_version'):
        print "loggerhead %s" % (__version__,)
        sys.exit(0)

    if config.arg_count > 1:
        config.print_help()
        sys.exit(1)
    elif config.arg_count == 1:
        base = config.get_arg(0)
    else:
        base = '.'

    if not config.get_option('allow_writes'):
        base = 'readonly+' + base

    return config, base


def setup_logging(config):
    # My logging setup is heavily based on start-loggerhead.py's
    # setup_logging()

    default_f = logging.Formatter('%(asctime)s %(levelname)-8s %(name)s: %(message)s')
    # XXX Do I need to explicitly specify the formatter in this case?
    null_f = logging.Formatter('%(message)s')

    access_log = logging.FileHandler('/home/mnordhoff/loggerhead/logs/access.log', 'a')
    access_log.setLevel(logging.INFO)
    access_log.setFormatter(null_f)

    debug_log = logging.FileHandler('/home/mnordhoff/loggerhead/logs/debug.log', 'a')
    debug_log.setLevel(logging.DEBUG)
    debug_log.setFormatter(default_f)

    stdout_log = logging.StreamHandler(sys.stdout)
    stdout_log.setLevel(logging.DEBUG)
    stdout_log.setFormatter(default_f)

    # XXX Loggerhead uses getLogger('loggerhead') here.
    logging.getLogger('').setLevel(logging.DEBUG)
    logging.getLogger('').addHandler(debug_log)
    logging.getLogger('').addHandler(stdout_log)
    # Paste's CLF-format log messages
    logging.getLogger('wsgi').addHandler(access_log)
    #logging.getLogger('wsgi').addHandler(debug_log)
    #logging.getLogger('wsgi').addHandler(stdout_log)

    def _restrict_logging(logger_name):
        logger = logging.getLogger(logger_name)
        if logger.getEffectiveLevel() < logging.INFO:
            logger.setLevel(logging.INFO)
    # simpleTAL is *very* verbose in DEBUG mode, which is otherwise the
    # default. So quiet it up a bit.
    _restrict_logging('simpleTAL')
    _restrict_logging('simpleTALES')

    return logging.getLogger('loggerhead')


def make_app_for_config_and_path(config, base):
    if config.get_option('trunk_dir') and not config.get_option('user_dirs'):
        print "--trunk-dir is only valid with --user-dirs"
        sys.exit(1)

    if config.get_option('reload'):
        if Reloader.is_installed():
            Reloader.install()
        else:
            return Reloader.restart_with_reloader()

    if config.get_option('user_dirs'):
        if not config.get_option('trunk_dir'):
            print "You didn't specify a directory for the trunk directories."
            sys.exit(1)
        app = UserBranchesFromTransportRoot(base, config)
    else:
        app = BranchesFromTransportRoot(base, config)

    setup_logging(config)

    def redirect_bzr_requests(application):
        """WSGI middleware to redirect /.bzr/ requests to /bzr"""
        def new_app(environ, start_response):
            path = environ['PATH_INFO']
            if '/.bzr/' in path:
                # This is probably always True, but I want to be careful.
                if path.startswith('/'):
                    new_url = 'http://bzr.mattnordhoff.com/bzr' + path
                else:
                    new_url = 'http://bzr.mattnordhoff.com/bzr/' + path
                raise HTTPMovedPermanently(new_url)
            return application(environ, start_response)
        return new_app

    app = redirect_bzr_requests(app)

    if config.get_option('profile'):
        from loggerhead.middleware.profile import LSProfMiddleware
        app = LSProfMiddleware(app)
    if config.get_option('memory_profile'):
        from dozer import Dozer
        app = Dozer(app)

    def block_broken_dozer_image(application):
        """One Dozer image gets thousands of pixels wide, crashing my browser.
        """
        # XXX Make the response a properly-sized image, so it displays nicely
        # on the page.
        msg = ("There is something wrong with the generation of this image, "
            "often leading to it being thousands of pixels wide and causing "
            "browser crashes, so you can't see it. Sorry.")
        def new_app(environ, start_response):
            if environ['PATH_INFO'] == '/_dozer/chart/ctypes.CFunctionType':
                raise HTTPForbidden(detail=msg)
            return application(environ, start_response)
        return new_app

    app = block_broken_dozer_image(app)

    if not config.get_option('user_prefix'):
        prefix = '/'
    else:
        prefix = config.get_option('user_prefix')
        if not prefix.startswith('/'):
            prefix = '/' + prefix

    try:
        from paste.deploy.config import PrefixMiddleware
    except ImportError:
        cant_proxy_correctly_message = (
            'Unsupported configuration: PasteDeploy not available, but '
            'loggerhead appears to be behind a proxy.')
        def check_not_proxied(app):
            def wrapped(environ, start_response):
                if 'HTTP_X_FORWARDED_SERVER' in environ:
                    exc = HTTPInternalServerError()
                    exc.explanation = cant_proxy_correctly_message
                    raise exc
                return app(environ, start_response)
            return wrapped
        app = check_not_proxied(app)
    else:
        app = PrefixMiddleware(app, prefix=prefix)

    app = HTTPExceptionHandler(app)
    app = ErrorHandlerApp(app)
    app = TransLogger(app, logger=logging.getLogger('wsgi'))

    return app


def main(args):
    load_plugins()

    config, path = get_config_and_path(args)

    app = make_app_for_config_and_path(config, path)

    if not config.get_option('user_port'):
        port = '8080'
    else:
        port = config.get_option('user_port')

    if not config.get_option('user_host'):
        host = '0.0.0.0'
    else:
        host = config.get_option('user_host')

    if not config.get_option('protocol'):
        protocol = 'http'
    else:
        protocol = config.get_option('protocol')

    if protocol == 'http':
        httpserver.serve(app, host=host, port=port, threadpool_workers=6)
    else:
        if protocol == 'fcgi':
            from flup.server.fcgi import WSGIServer
        elif protocol == 'scgi':
            from flup.server.scgi import WSGIServer
        elif protocol == 'ajp':
            from flup.server.ajp import WSGIServer
        else:
            print 'Unknown protocol: %s.' % (protocol)
            sys.exit(1)
        WSGIServer(app, bindAddress=(host, int(port))).run()