1#!/usr/bin/python
2
3import common
4import sys, os, signal, time, subprocess, fcntl
5
6logdir = sys.argv[1]
7stdout_start = int(sys.argv[2])  # number of bytes we can skip on stdout
8stderr_start = int(sys.argv[3])  # nubmer of bytes we can skip on stderr
9# TODO (crosbug.com/38224)- sbasi: Remove extra logging.
10stderr = open(os.path.join(logdir, 'stderr'), 'a', 0)
11
12print >> stderr, 'Entered autotestd_monitor.'
13# if any of our tail processes die, the monitor should die too
14def kill_self(signum, frame):
15    os.kill(os.getpid(), signal.SIGTERM)
16signal.signal(signal.SIGCHLD, kill_self)
17
18devnull = open(os.devnull, 'w')
19
20# launch some tail processes to pump the std* streams
21def launch_tail(filename, outstream, start):
22    path = os.path.join(logdir, filename)
23    argv = ['tail', '--retry', '--follow=name', '--bytes=+%d' % start, path]
24    # stdout=sys.stdout fails on pre-2.5 python (bug in subprocess module)
25    if outstream != subprocess.PIPE and outstream.fileno() == 1:
26        return subprocess.Popen(argv, stderr=devnull)
27    else:
28        return subprocess.Popen(argv, stdout=outstream, stderr=devnull)
29stdout_pump = launch_tail('stdout', sys.stdout, stdout_start)
30stderr_pump = launch_tail('stderr', sys.stderr, stderr_start)
31
32print >> stderr, 'Finished launching tail subprocesses.'
33
34# wait for logdir/started to exist to be sure autotestd is started
35start_time = time.time()
36started_file_path = os.path.join(logdir, 'started')
37while not os.path.exists(started_file_path):
38    time.sleep(1)
39    if time.time() - start_time >= 30:
40        raise Exception("autotestd failed to start in %s" % logdir)
41
42print >> stderr, 'Finished waiting on autotestd to start.'
43
44# watch the exit code file for an exit
45exit_code_file = open(os.path.join(logdir, 'exit_code'))
46fcntl.flock(exit_code_file, fcntl.LOCK_EX)
47print >> stderr, 'Got lock of exit_code_file.'
48try:
49    exit_code = exit_code_file.read()
50    if len(exit_code) != 4:
51        exit_code = -signal.SIGKILL   # autotestd was nuked
52    else:
53        exit_code = int(exit_code)
54finally:
55    fcntl.flock(exit_code_file, fcntl.LOCK_UN)
56    exit_code_file.close()
57    print >> stderr, 'Released lock of exit_code_file and closed it.'
58
59# tail runs in 1s polling loop, so give them a chance to finish
60time.sleep(2)
61
62print >> stderr, 'Killing child processes.'
63# clear the SIGCHLD handler so that killing the tails doesn't kill us
64signal.signal(signal.SIGCHLD, signal.SIG_DFL)
65os.kill(stdout_pump.pid, signal.SIGTERM)
66os.kill(stderr_pump.pid, signal.SIGTERM)
67
68# exit (with the same code as autotestd)
69sys.exit(exit_code)
70