#!/usr/bin/python

# Find out when the "stress_killer sometimes does" bug appeared.
# Due to the random nature of the bug, we need to run the tests
# a large numer of times to catch the bug with a high probability.
# To speed things up a bit, we run multiple anita instances in
# parallel to take advantage of multiple CPU cores.

from __future__ import print_function

import sys
import anita
import pexpect
import time

from bracket import *

use_current_repository()

nruns = 12
ncpus = 4
ntotal = ncpus * nruns

def test_stress_killer(ts, logfile):
    anita_run_1(ts, 'test', logfile)
    status = run("cat %s | grep stress_killer | egrep 'panic|uvm_fault|assertion|lock error'" % logfile)
    # We succeed if grep does not find a panic
    return status != 0

def tests_stress_killer_multi(ts):
    nsuccess = 0
    for j in range(nruns):
        for i in range(ncpus):
            pid = os.fork()
            if (pid == 0):
                # child
                logfile = os.path.join(results_dir(ts), 'stress_killer.log.' + str(j * ncpus + i))
                if test_stress_killer(ts, logfile):
                    sys.exit(0)
                else:
                    sys.exit(1)

        for i in range(ncpus):
            result = os.wait()
            print("wait result", result)
            if result[1] == 0:
                nsuccess = nsuccess + 1

    cache_status(ts, 'stress_killer_%d_nsuccess' % ntotal, nsuccess)
    return nsuccess == ntotal

stress_killer_multi_op = TestOp(tests_stress_killer_multi, [install_op, boot_op], name = "stress_killer_multi")

find_failure(
    rcs2ts("2011.09.24.17.09.29"),
    rcs2ts("2011.09.24.21.11.23"),
    stress_killer_multi_op, confirm = False)
