~launchpad-pqm/launchpad/devel

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
#!/usr/bin/python -S
#
# Copyright 2009, 2010 Canonical Ltd.  This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).

import _pythonpath

import logging
import os
import sys

from paste import httpserver
from paste.deploy.config import PrefixMiddleware
from paste.httpexceptions import HTTPExceptionHandler
from paste.request import construct_url
from paste.translogger import TransLogger

from canonical.config import config
import lp.codehosting

LISTEN_HOST = '0.0.0.0'
LISTEN_PORT = 8080
THREADPOOL_WORKERS = 10


class NoLockingFileHandler(logging.FileHandler):
    """A version of logging.FileHandler that doesn't do it's own locking.

    We experienced occasional hangs in production where gdb-ery on the server
    revealed that we sometimes end up with many threads blocking on the RLock
    held by the logging file handler, and log reading finds that an exception
    managed to kill a thread in an unsafe window for RLock's.

    Luckily, there's no real reason for us to take a lock during logging as
    each log message translates to one call to .write on a file object, which
    translates to one fwrite call, and it seems that this does enough locking
    itself for our purposes.

    So this handler just doesn't lock in log message handling.
    """

    def acquire(self):
        pass

    def release(self):
        pass


def setup_logging(home, foreground):
    # i hate that stupid logging config format, so just set up logging here.

    log_folder = config.codebrowse.log_folder
    if not log_folder:
        log_folder = os.path.join(home, 'logs')
    if not os.path.exists(log_folder):
        os.mkdir(log_folder)

    f = logging.Formatter(
        '%(levelname)-.3s [%(asctime)s.%(msecs)03d] [%(thread)d] %(name)s: %(message)s',
        '%Y%m%d-%H:%M:%S')
    debug_log = NoLockingFileHandler(os.path.join(log_folder, 'debug.log'))
    debug_log.setLevel(logging.DEBUG)
    debug_log.setFormatter(f)
    if foreground:
        stdout_log = logging.StreamHandler(sys.stdout)
        stdout_log.setLevel(logging.DEBUG)
        stdout_log.setFormatter(f)
    f = logging.Formatter('[%(asctime)s.%(msecs)03d] %(message)s',
                          '%Y%m%d-%H:%M:%S')
    access_log = NoLockingFileHandler(os.path.join(log_folder, 'access.log'))
    access_log.setLevel(logging.INFO)
    access_log.setFormatter(f)

    logging.getLogger('').setLevel(logging.DEBUG)
    logging.getLogger('').addHandler(debug_log)
    logging.getLogger('wsgi').addHandler(access_log)

    if foreground:
        logging.getLogger('').addHandler(stdout_log)
    else:
        class S(object):
            def write(self, str):
                logging.getLogger().error(str.rstrip('\n'))
            def flush(self):
                pass
        sys.stderr = S()



foreground = False
if len(sys.argv) > 1:
    if sys.argv[1] == '-f':
        foreground = True

home = os.path.realpath(os.path.dirname(__file__))
pidfile = os.path.join(home, 'loggerhead.pid')

if not foreground:
    sys.stderr.write('\n')
    sys.stderr.write('Launching loggerhead into the background.\n')
    sys.stderr.write('PID file: %s\n' % (pidfile,))
    sys.stderr.write('\n')

    from loggerhead.daemon import daemonize
    daemonize(pidfile, home)

setup_logging(home, foreground=foreground)

log = logging.getLogger('loggerhead')
log.info('Starting up...')

log.info('Loading the bzr plugins...')
from bzrlib.plugin import load_plugins
load_plugins()

import bzrlib.plugins
if getattr(bzrlib.plugins, 'loom', None) is None:
    log.error('Loom plugin loading failed.')

from launchpad_loggerhead.debug import (
    change_kill_thread_criteria, threadpool_debug)
from launchpad_loggerhead.app import RootApp, oops_middleware
from launchpad_loggerhead.session import SessionHandler

SESSION_VAR = 'lh.session'

secret = open(os.path.join(config.root, config.codebrowse.secret_path)).read()

app = RootApp(SESSION_VAR)
app = HTTPExceptionHandler(app)
app = SessionHandler(app, SESSION_VAR, secret)
def log_on_request_start(app):
    def wrapped(environ, start_response):
        log = logging.getLogger('loggerhead')
        log.info("Starting to process %s", construct_url(environ))
        return app(environ, start_response)
    return wrapped
app = log_on_request_start(app)
app = PrefixMiddleware(app)
app = TransLogger(app)
app = threadpool_debug(app)

def set_scheme(app):
    """Set wsgi.url_scheme in the environment correctly.

    We serve requests that originated from both http and https, and
    distinguish between them by adding a header in the https Apache config.
    """
    def wrapped(environ, start_response):
        environ['wsgi.url_scheme'] = environ.pop(
            'HTTP_X_FORWARDED_SCHEME', 'http')
        return app(environ, start_response)
    return wrapped
app = set_scheme(app)
app = change_kill_thread_criteria(app)
app = oops_middleware(app)

try:
    httpserver.serve(
        app, host=LISTEN_HOST, port=LISTEN_PORT,
        threadpool_workers=THREADPOOL_WORKERS,
        threadpool_options={
            # Kill threads after 300 seconds.  This is insanely high, but
            # lower enough than the default (1800 seconds!) that evidence
            # suggests it will be hit occasionally, and there's very little
            # chance of it having negative consequences.
            'kill_thread_limit': 300,
            # Check for threads that should be killed every 10 requests.  The
            # default is every 100, which is easily long enough for things to
            # gum up completely in between checks.
            'hung_check_period': 10,
            })
finally:
    log.info('Shutdown.')
    try:
        os.remove(pidfile)
    except OSError:
        pass