summaryrefslogtreecommitdiff
path: root/buildscripts/buildlogger.py
blob: a6f91d840f8552ed2f6fb3142f77ced708bb16c4 (plain)
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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
"""
buildlogger.py

Wrap a command (specified on the command line invocation of buildlogger.py)
and send output in batches to the buildlogs web application via HTTP POST.

The script configures itself from environment variables:

  required env vars:
    MONGO_BUILDER_NAME (e.g. "Nightly Linux 64-bit")
    MONGO_BUILD_NUMBER (an integer)
    MONGO_TEST_FILENAME (not required when invoked with -g)

  optional env vars:
    MONGO_PHASE (e.g. "core", "slow nightly", etc)
    MONGO_* (any other environment vars are passed to the web app)

This script has two modes: a "test" mode, intended to wrap the invocation of
an individual test file, and a "global" mode, intended to wrap the mongod
instances that run throughout the duration of a mongo test phase (the logs
from "global" invocations are displayed interspersed with the logs of each
test, in order to let the buildlogs web app display the full output sensibly.)
"""

import functools
import os
import os.path
import re
import signal
import subprocess
import sys
import time
import traceback
import urllib2

try:
    import json
except:
    try:
        import simplejson as json
    except:
        json = None

# try to load the shared secret from settings.py
# which will be one, two, or three directories up
# from this file's location
here = os.path.abspath(os.path.dirname(__file__))
possible_paths = [
    os.path.abspath(os.path.join(here, '..')),
    os.path.abspath(os.path.join(here, '..', '..')),
    os.path.abspath(os.path.join(here, '..', '..', '..')),
]

username, password = None, None
for path in possible_paths:
    buildbot_tac = os.path.join(path, 'buildbot.tac')
    if os.path.isfile(buildbot_tac):
        tac_globals = {}
        tac_locals = {}
        try:
            execfile(buildbot_tac, tac_globals, tac_locals)
            tac_globals.update(tac_locals)
            username = tac_globals['slavename']
            password = tac_globals['passwd']
            break
        except:
            traceback.print_exc()


URL_ROOT = 'http://buildlogs.mongodb.org/'
TIMEOUT_SECONDS = 10

digest_handler = urllib2.HTTPDigestAuthHandler()
digest_handler.add_password(
    realm='buildlogs',
    uri=URL_ROOT,
    user=username,
    passwd=password)
url_opener = urllib2.build_opener(digest_handler)

def url(endpoint):
    if not endpoint.endswith('/'):
        endpoint = '%s/' % endpoint

    return '%s/%s' % (URL_ROOT.rstrip('/'), endpoint)

def post(endpoint, data, headers=None):
    data = json.dumps(data, encoding='utf-8')

    headers = headers or {}
    headers.update({'Content-Type': 'application/json; charset=utf-8'})

    req = urllib2.Request(url=url(endpoint), data=data, headers=headers)
    response = url_opener.open(req, timeout=TIMEOUT_SECONDS)
    response_headers = dict(response.info())

    # eg "Content-Type: application/json; charset=utf-8"
    content_type = response_headers.get('content-type')
    match = re.match(r'(?P<mimetype>[^;]+).*(?:charset=(?P<charset>[^ ]+))?$', content_type)
    if match and match.group('mimetype') == 'application/json':
        encoding = match.group('charset') or 'utf-8'
        return json.load(response, encoding=encoding)

    return response.read()

def traceback_to_stderr(func):
    """
    decorator which logs any exceptions encountered to stderr
    and returns none.
    """
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except urllib2.HTTPError, err:
            sys.stderr.write('error: HTTP code %d\n----\n' % err.code)
            if hasattr(err, 'hdrs'):
                for k, v in err.hdrs.items():
                    sys.stderr.write("%s: %s\n" % (k, v))
                sys.stderr.write('\n')
            sys.stderr.write(err.read())
            sys.stderr.write('\n----\n')
            sys.stderr.flush()
        except:
            sys.stderr.write('Traceback from buildlogger:\n')
            traceback.print_exc(file=sys.stderr)
            sys.stderr.flush()
        return None
    return wrapper


@traceback_to_stderr
def get_or_create_build(builder, buildnum, extra={}):
    data = {'builder': builder, 'buildnum': buildnum}
    data.update(extra)
    response = post('build', data)
    return response['id']

@traceback_to_stderr
def create_test(build_id, test_filename, test_command, test_phase):
    response = post('build/%s/test' % build_id, {
        'test_filename': test_filename,
        'command': test_command,
        'phase': test_phase,
    })
    return response['id']

@traceback_to_stderr
def append_test_logs(build_id, test_id, log_lines):
    post('build/%s/test/%s' % (build_id, test_id), data=log_lines)
    return True

@traceback_to_stderr
def append_global_logs(build_id, log_lines):
    """
    "global" logs are for the mongod(s) started by smoke.py
    that last the duration of a test phase -- since there
    may be output in here that is important but spans individual
    tests, the buildlogs webapp handles these logs specially.
    """
    post('build/%s' % build_id, data=log_lines)
    return True

@traceback_to_stderr
def finish_test(build_id, test_id, failed=False):
    post('build/%s/test/%s' % (build_id, test_id), data=[], headers={
        'X-Sendlogs-Test-Done': 'true',
        'X-Sendlogs-Test-Failed': failed and 'true' or 'false',
    })
    return True

def run_and_echo(command):
    """
    this just calls the command, and returns its return code,
    allowing stdout and stderr to work as normal. it is used
    as a fallback when environment variables or python
    dependencies cannot be configured, or when the logging
    webapp is unavailable, etc
    """
    return subprocess.call(command)

def wrap_test(command):
    """
    call the given command, intercept its stdout and stderr,
    and send results in batches of 100 lines or 10s to the 
    buildlogger webapp
    """

    # get builder name and build number from environment
    builder = os.environ.get('MONGO_BUILDER_NAME')
    buildnum = os.environ.get('MONGO_BUILD_NUMBER')

    if builder is None or buildnum is None:
        return run_and_echo(command)

    try:
        buildnum = int(buildnum)
    except ValueError:
        sys.stderr.write('buildlogger: build number ("%s") was not an int\n' % buildnum)
        sys.stderr.flush()
        return run_and_echo(command)

    # test takes some extra info
    phase = os.environ.get('MONGO_PHASE', 'unknown')
    test_filename = os.environ.get('MONGO_TEST_FILENAME', 'unknown')

    build_info = dict((k, v) for k, v in os.environ.items() if k.startswith('MONGO_'))
    build_info.pop('MONGO_BUILDER_NAME', None)
    build_info.pop('MONGO_BUILD_NUMBER', None)
    build_info.pop('MONGO_PHASE', None)
    build_info.pop('MONGO_TEST_FILENAME', None)

    build_id = get_or_create_build(builder, buildnum, extra=build_info)
    if not build_id:
        return run_and_echo(command)

    test_id = create_test(build_id, test_filename, ' '.join(command), phase)
    if not test_id:
        return run_and_echo(command)

    start_time = time.time()
    buf = [(start_time, '*** beginning test %r ***' % test_filename)]
    def callback(line):
        if line is None:
            # callback is called with None when the
            # command is finished
            end_time = time.time()
            buf.append((end_time, '*** finished test %r in %f seconds ***' % (test_filename, end_time - start_time)))
            append_test_logs(build_id, test_id, buf)
        else:
            buf.append((time.time(), line))
            if len(buf) > 100 or (buf and time.time() - buf[0][0] > 10):
                append_test_logs(build_id, test_id, buf)

                # this is like "buf = []", but doesn't change
                # the "buf" reference -- necessary to  make
                # the closure work
                buf[:] = []

    # the peculiar formatting here matches what is printed by
    # smoke.py when starting tests
    output_url = '%s/build/%s/test/%s/' % (URL_ROOT.rstrip('/'), build_id, test_id)
    sys.stdout.write('                (output suppressed; see %s)\n' % output_url)
    sys.stdout.flush()

    returncode = loop_and_callback(command, callback)

    failed = bool(returncode != 0)
    finish_test(build_id, test_id, failed)

    return returncode

def wrap_global(command):
    """
    call the given command, intercept its stdout and stderr,
    and send results in batches of 100 lines or 10s to the
    buildlogger webapp. see :func:`append_global_logs` for the
    difference between "global" and "test" log output.
    """

    # get builder name and build number from environment
    builder = os.environ.get('MONGO_BUILDER_NAME')
    buildnum = os.environ.get('MONGO_BUILD_NUMBER')

    if builder is None or buildnum is None:
        return run_and_echo(command)

    try:
        buildnum = int(buildnum)
    except ValueError:
        sys.stderr.write('int(os.environ["MONGO_BUILD_NUMBER"]):\n')
        sys.stderr.write(traceback.format_exc())
        sys.stderr.flush()
        return run_and_echo(command)

    build_info = dict((k, v) for k, v in os.environ.items() if k.startswith('MONGO_'))
    build_info.pop('MONGO_BUILDER_NAME', None)
    build_info.pop('MONGO_BUILD_NUMBER', None)

    build_id = get_or_create_build(builder, buildnum, extra=build_info)
    if not build_id:
        return run_and_echo(command)

    buf = []
    def callback(line):
        if line is None and buf:
            # callback is called with None when the
            # command is finished
            append_global_logs(build_id, buf)
        else:
            buf.append((time.time(), line))
            if len(buf) > 100 or (buf and time.time() - buf[0][0] > 10):
                append_global_logs(build_id, buf)

                # this is like "buf = []", but doesn't change
                # the "buf" reference -- necessary to  make
                # the closure work
                buf[:] = []

    return loop_and_callback(command, callback)

def loop_and_callback(command, callback):
    """
    run the given command (a sequence of arguments, ordinarily
    from sys.argv), and call the given callback with each line
    of stdout or stderr encountered. after the command is finished,
    callback is called once more with None instead of a string.
    """
    proc = subprocess.Popen(
        command,
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
    )

    def handle_sigterm(signum, frame):
        proc.send_signal(signum)

    # register a handler to delegate SIGTERM
    # to the child process
    orig_handler = signal.signal(signal.SIGTERM, handle_sigterm)

    while proc.poll() is None:
        try:
            line = proc.stdout.readline().strip('\r\n')
            callback(line)
        except IOError:
            # if the signal handler is called while
            # we're waiting for readline() to return,
            # don't show a traceback
            break

    # restore the original signal handler, if any
    signal.signal(signal.SIGTERM, orig_handler)

    callback(None)
    return proc.returncode


if __name__ == '__main__':
    # argv[0] is 'buildlogger.py'
    del sys.argv[0]

    if sys.argv[0] in ('-g', '--global'):
        # then this is wrapping a "global" command, and should
        # submit global logs to the build, not test logs to a
        # test within the build
        del sys.argv[0]
        wrapper = wrap_global

    else:
        wrapper = wrap_test

    # if we are missing credentials or the json module, then
    # we can't use buildlogger; so just echo output, but also
    # log why we can't work.
    if json is None:
        sys.stderr.write('buildlogger: could not import a json module\n')
        sys.stderr.flush()
        wrapper = run_and_echo

    elif username is None or password is None:
        sys.stderr.write('buildlogger: could not find or import buildbot.tac for authentication\n')
        sys.stderr.flush()
        wrapper = run_and_echo

    # otherwise wrap a test command as normal; the
    # wrapper functions return the return code of
    # the wrapped command, so that should be our
    # exit code as well.
    sys.exit(wrapper(sys.argv))