# Copyright (C) 2008-2009 Sun Microsystems, Inc. All rights reserved.
# Use is subject to license terms.
#
# 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; version 2 of the License.
#
# 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
# USA

use strict;
use lib 'lib';
use lib '../lib';
use Carp;
use DBI;
use Getopt::Long;

use GenTest::Properties;
use GenTest::Constants;
use GenTest::Executor::MySQL;
use GenTest::Simplifier::SQL;
use GenTest::Simplifier::Test;

my $options = {};
GetOptions($options,
           'config=s',
           'dsn=s@',
           'query=s');
my $config = GenTest::Properties->new(
    options => $options,
    defaults => {dsn=>['dbi:mysql:host=127.0.0.1:port=19306:user=root:database=test',
                       'dbi:mysql:host=127.0.0.1:port=19308:user=root:database=test']},
    required => ['dsn','query']);

my @executors;
my @results;

foreach my $dsn (@{$config->dsn}) {
    print "....$dsn\n";
	my $executor = GenTest::Executor->newFromDSN($dsn);
	$executor->init();
	push @executors, $executor;

	my $result = $executor->execute($config->query, 1);
	push @results, $result;
}

my $simplifier_test = GenTest::Simplifier::Test->new(
	executors => \@executors,
	queries => [ $config->query ],
	results => [ \@results ]
);

my $test = $simplifier_test->simplify();

print $test;


# Copyright (C) 2008-2009 Sun Microsystems, Inc. All rights reserved.
# Use is subject to license terms.
#
# 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; version 2 of the License.
#
# 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
# USA

use strict;
use lib 'lib';
use lib '../lib';
use Carp;
use Getopt::Long;

use GenTest;
use GenTest::Properties;
use GenTest::Grammar;

my $options = {};
GetOptions(
	$options,
	'grammar=s',
	'mask=i',
	'mask-level=i'
);

my $config = GenTest::Properties->new(
	options => $options,
	defaults => {
		'mask-level'	=> 1,
		'mask'		=> 0
	},
	required => ['grammar']
);

my ($grammar_file, $mask, $mask_level) = (
	$config->property('grammar'),
	$config->property('mask'),
	$config->property('mask-level')
);

say("Grammar: $grammar_file");
say("Mask: $mask");
say("Mask-level: $mask_level");

my $initial_grammar = GenTest::Grammar->new(
	'grammar_file'	=> $grammar_file
);

my $final_grammar;

if ($mask > 0) {
	my $top_grammar = $initial_grammar->topGrammar($mask_level, "query", "query_init");
	my $masked_top = $top_grammar->mask($mask);
	$final_grammar = $initial_grammar->patch($masked_top);
} else {
	$final_grammar = $initial_grammar;
}

print $final_grammar->toString();
print "\n";


# Copyright (C) 2008-2009 Sun Microsystems, Inc. All rights reserved.
# Use is subject to license terms.
#
# 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; version 2 of the License.
#
# 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
# USA

use strict;
use lib 'lib';
use lib '../lib';
use DBI;

use GenTest::Constants;
use GenTest::Executor::MySQL;
use GenTest::Simplifier::SQL;
use GenTest::Simplifier::Test;

#
# Please modify those settings to fit your environment before you run this script
#

my $basedir = '/home/philips/bzr/maria-5.3-mwl128/';
my $vardir = $basedir.'/mysql-test/var';
my $dsn = 'dbi:mysql:host=127.0.0.1:port=19300:user=root:database=test';

my $original_query = "
	SELECT 1 FROM DUAL
";

# Maximum number of seconds a query will be allowed to proceed. It is assumed that most crashes will happen immediately after takeoff
my $timeout = 10;

my @mtr_options = (
#	'--mysqld=--innodb',
	'--mysqld=--log-output=file',	# Prevents excessively long CSV recovery on each startup
	'--start-and-exit',
	'--start-dirty',
	"--vardir=$vardir",
	"--master_port=19300",
	'--skip-ndbcluster',
	'--mysqld=--loose-core-file-size=1',
	'--fast',
	'--mysqld=--key_buffer_size=16K',
	'--mysqld=--table_open_cache=4',
	'--mysqld=--sort_buffer_size=64K',
	'--mysqld=--read_buffer_size=256K',
	'--mysqld=--read_rnd_buffer_size=256K',
	'--mysqld=--thread_stack=240K',
	'--mysqld=--loose-innodb_buffer_pool_size=16M',
	'--mysqld=--loose-innodb_additional_mem_pool_size=2M',
	'--mysqld=--innodb_log_file_size=5M',
	'--mysqld=--innodb_log_buffer_size=8M',
	'--mysqld=--innodb_flush_log_at_trx_commit=2',
	'1st'	# Required for proper operation of MTR --start-and-exit
);

my $orig_database = 'test';
my $new_database = 'crash';

my $executor;

start_server();

my $simplifier = GenTest::Simplifier::SQL->new(
	oracle => sub {
		my $oracle_query = shift;
		my $dbh = $executor->dbh();

		my $connection_id = $dbh->selectrow_array("SELECT CONNECTION_ID()");
		$dbh->do("CREATE EVENT timeout ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL $timeout SECOND DO KILL QUERY $connection_id");

		$executor->execute($oracle_query);

		# Or, alternatively, execute as a prepared statement
		# $executor->execute("PREPARE prep_stmt FROM \"$oracle_query\"");
		# $executor->execute("EXECUTE prep_stmt");
		# $executor->execute("EXECUTE prep_stmt");
		# $executor->execute("DEALLOCATE PREPARE prep_stmt");

		$dbh->do("DROP EVENT IF EXISTS timeout");

		if (!$executor->dbh()->ping()) {
			start_server();
			return ORACLE_ISSUE_STILL_REPEATABLE;
		} else {
			return ORACLE_ISSUE_NO_LONGER_REPEATABLE;
		}
	}
);

my $simplified_query = $simplifier->simplify($original_query);
print "Simplified query:\n$simplified_query;\n\n";

my $simplifier_test = GenTest::Simplifier::Test->new(
	executors => [ $executor ],
	queries => [ $simplified_query , $original_query ]
);

my $simplified_test = $simplifier_test->simplify();

print "Simplified test\n\n";
print $simplified_test;

sub start_server {
	chdir($basedir.'/mysql-test') or die "Unable to chdir() to $basedir/mysql-test: $!";

	$executor = GenTest::Executor::MySQL->new( dsn => $dsn );
	$executor->init() if defined $executor;

	if ((not defined $executor) || (not defined $executor->dbh()) || (!$executor->dbh()->ping())) {
		system("MTR_VERSION=1 perl mysql-test-run.pl ".join(" ", @mtr_options));
		$executor = GenTest::Executor::MySQL->new( dsn => $dsn );
		$executor->init();
	}

	$executor->dbh()->do("SET GLOBAL EVENT_SCHEDULER = ON");
}


# Copyright (C) 2008-2009 Sun Microsystems, Inc. All rights reserved.
# Use is subject to license terms.
#
# 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; version 2 of the License.
#
# 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
# USA

use strict;
use lib 'lib';
use lib '../lib';
use DBI;
use Carp;
use Getopt::Long;
use Data::Dumper;

use GenTest;
use GenTest::Constants;
use GenTest::Grammar;
use GenTest::Properties;
use GenTest::Simplifier::Grammar;
use Time::HiRes;

#
# RQG grammar simplification with an oracle() function based on
# 1. RQG exit status codes (-> desired_status_codes)
# 2. expected RQG protocol output (-> expected_output)
# Hint: 2. will be not checked if 1. already failed
#
# You need to adjust parameters to your use case and environment.
# 1. Copy simplify-grammar_template.cfg to for example 1.cfg
# 2. Adjust the settings
# 2. perl util/simplify-grammar.pl --config 1.cfg
#
# This script is used to simplify grammar files to the smallest form
# that will still reproduce the desired outcome
# For the purpose, the GenTest::Simplifier::Grammar module provides
# progressively simple grammars, and we define an oracle() function
# that runs those grammars with the RQG and reports if the RQG returns
# the desired status code (usually something like
# STATUS_SERVER_CRASHED
#
# For more information, please see:
#
# http://forge.mysql.com/wiki/RandomQueryGeneratorSimplification
#

# get configuration

my $options = {};
GetOptions($options, 'config=s', 'trials=i','storage_prefix=s','expected_output=s@');
my $config = GenTest::Properties->new(
    options => $options,
    legal => ['desired_status_codes',
              'expected_output',
              'initial_grammar_file',
              'mask',
              'mask-level',
              'grammar_flags',
              'trials',
              'initial_seed',
              'search_var_size',
              'rqg_options',
              'vardir_prefix',
              'storage_prefix'],
    required=>['rqg_options',
               'initial_grammar_file',
               'vardir_prefix',
               'storage_prefix'],
    defaults => {expected_output => [],
                 desired_status_codes => [+STATUS_ANY_ERROR]}
    );

# Dump settings
say("SIMPLIFY RQG GRAMMAR BASED ON EXPECTED CONTENT WITHIN SOME FILE");
say("---------------------------------------------------------------");
$config->printProps;
say("---------------------------------------------------------------");

## Calculate mysqld and rqg options

my $mysqlopt = $config->genOpt('--mysqld=--', $config->rqg_options->{mysqld});

## The one below is a hack.... Need support for nested options like these
delete $config->rqg_options->{mysqld};

my $rqgoptions = $config->genOpt('--', 'rqg_options');

# Determine some runtime parameter, check parameters, ....

my $run_id = time();

say("The ID of this run is $run_id.");

my $initial_grammar;

if ($config->property('mask') > 0) {
   my $initial_grammar_obj = GenTest::Grammar->new( 'grammar_file'  => $config->initial_grammar_file );
   my $top_grammar = $initial_grammar_obj->topGrammar($config->property('mask-level'), "query", "query_init");
   my $masked_top = $top_grammar->mask($config->property('mask'));
   $initial_grammar = $initial_grammar_obj->patch($masked_top);
} else {
   open(INITIAL_GRAMMAR, $config->initial_grammar_file) or croak "Unable to open initial_grammar_file '" . $config->initial_grammar_file . "' : $!";
   read(INITIAL_GRAMMAR, $initial_grammar , -s $config->initial_grammar_file);
   close(INITIAL_GRAMMAR);
}

if ( ! -d $config->vardir_prefix ) {
   croak("vardir_prefix '" . $config->vardir_prefix . "' is not an existing directory");
}

# Calculate a unique vardir (use $MTR_BUILD_THREAD or $run_id)

my $vardir = $config->vardir_prefix . '/var_' . $run_id;
mkdir ($vardir);
push my @mtr_options, "--vardir=$vardir";

if ( ! -d $config->storage_prefix) {
   croak("storage_prefix '" . $config->storage_prefix . "' is not an existing directory");
}
my $storage = $config->storage_prefix.'/'.$run_id;
say "Storage is $storage";
mkdir ($storage);

my $errfile = $vardir . '/log/master.err';

my $iteration;
my $good_seed = $config->initial_seed;

my $simplifier = GenTest::Simplifier::Grammar->new(
    grammar_flags => $config->grammar_flags,
    oracle => sub {
        $iteration++;
        my $oracle_grammar = shift;

        my $current_grammar = $storage . '/' . $iteration . '.yy';
        open (GRAMMAR, ">$current_grammar")
           or croak "unable to create $current_grammar : $!";
        print GRAMMAR $oracle_grammar;
        close (GRAMMAR);

        foreach my $trial (1..$config->trials) {
            say("run_id = $run_id; iteration = $iteration; trial = $trial");

            # $current_seed -- The seed value to be used for the next run.
            # The test results of many grammars are quite sensitive to the
            # seed value.
            # 1. Run the first trial on the initial grammar with
            #    $config->initial_seed .  This should raise the chance
            #    that the initial oracle check passes.
            # 2. Run the first trial on a just simplified grammar with the
            #    last successfull seed value. In case the last
            #    simplification did remove some random determined we
            #    should have a bigger likelihood to reach the expected
            #    result.
            # 3. In case of "threads = 1" it turned out that after a minor
            #    simplification the desired bad effect disappeared
            #    sometimes on the next run with the same seed value
            #    whereas a different seed value was again
            #    successful. Therefore we manipulate the seed value.  In
            #    case of "threads > 1" this manipulation might be not
            #    required, but it will not make the conditions worse.
            my $current_seed = $good_seed - 1 + $trial;

            my $current_rqg_log = $storage . '/' . $iteration . '-'. $trial . '.log';

            my $start_time = Time::HiRes::time();

            # Note(mleich): In case of "threads = 1" it turned out that
            #    after a minor simplification the desired bad effect
            #    disappeared sometimes on the next run with the same
            #    seed value whereas a different seed value was again
            #    successful. Therefore we manipulate the seed value.  In
            #    case of "threads > 1" this manipulation might be not
            #    required, but it will not make the conditions worse.

            my $rqgcmd =
                "perl runall.pl $rqgoptions $mysqlopt ".
                "--grammar=$current_grammar ".
                "--vardir=$vardir ".
                "--seed=$current_seed >$current_rqg_log 2>&1";

            say($rqgcmd);
            my $rqg_status = system($rqgcmd);
            $rqg_status = $rqg_status >> 8;

            my $end_time = Time::HiRes::time();
            my $duration = $end_time - $start_time;

            say("rqg_status = $rqg_status; duration = $duration");

            return ORACLE_ISSUE_NO_LONGER_REPEATABLE
                if $rqg_status == STATUS_ENVIRONMENT_FAILURE;

            foreach my $desired_status_code (@{$config->desired_status_codes}) {
                if (($rqg_status == $desired_status_code) ||
                    (($rqg_status != 0) && ($desired_status_code == STATUS_ANY_ERROR))) {
                    # "backtrace" output (independend of server crash
                    # or RQG kills the server) is in $current_rqg_log
                    open (my $my_logfile,'<'.$current_rqg_log)
                        or croak "unable to open $current_rqg_log : $!";
                    # If open (above) did not fail than size
                    # determination must be successful.
                    my @filestats = stat($current_rqg_log);
                    my $filesize = $filestats[7];
                    my $offset = $filesize - $config->search_var_size;
                    # Of course read fails if $offset < 0
                    $offset = 0 if $offset < 0;
                    read($my_logfile, my $rqgtest_output, $config->search_var_size, $offset );
                    close ($my_logfile);
                    # Debug print("$rqgtest_output");

                    # Every element of @expected_output must be found
                    # in $rqgtest_output.
                    my $success = 1;
                    foreach my $expected_output (@{$config->expected_output}) {
                        if ($rqgtest_output =~ m{$expected_output}sio) {
                            say ("###### Found pattern:  $expected_output ######");
                        } else {
                            say ("###### Not found pattern:  $expected_output ######");
                            $success = 0;
                            last;
                        }
                    }
                    if ( $success ) {
                        say ("###### SUCCESS with $current_grammar ######");
                        $good_seed = $current_seed;
                        return ORACLE_ISSUE_STILL_REPEATABLE;
                    }
                } # End of check if the output matches given string patterns
            } # End of loop over desired_status_codes
            if ($rqg_status == STATUS_OK) {
               # Run with exit status 0 -> RQG output is not of interest
               unlink($current_rqg_log);
            }
        } # End of loop over the trials
        return ORACLE_ISSUE_NO_LONGER_REPEATABLE;
    }
    );

my $simplified_grammar = $simplifier->simplify($initial_grammar);

print "Simplified grammar:\n\n$simplified_grammar;\n\n" if defined $simplified_grammar;


# Copyright (C) 2008-2010 Sun Microsystems, Inc. All rights reserved.
# Use is subject to license terms.
#
# 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; version 2 of the License.
#
# 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
# USA

$| = 1;

use strict;
use lib 'lib';
use lib '../lib';
use DBI;
use Carp;
use File::Compare;
use File::Copy;
use Getopt::Long;
use Time::HiRes;

use GenTest;
use GenTest::Properties;
use GenTest::Constants;
use GenTest::Simplifier::Mysqltest;

# NOTE: oracle function behaves differently if basedir2 is specified in addition
#       to basedir. In this case expected_mtr_output is ignored, and result
#       comparison between servers is performed instead.

my $options = {};
my $o = GetOptions($options,
           'config=s',
           'input_file=s',
           'basedir=s',
           'basedir2=s',
           'expected_mtr_output=s',
           'verbose!',
           'mtr_options=s%',
           'mysqld=s%');
my $config = GenTest::Properties->new(
    options => $options,
    legal => [
        'config',
        'input_file',
        'basedir',
        'basedir2',
        'expected_mtr_output',
        'mtr_options',
        'verbose',
        'header',
        'footer',
        'filter',
        'mysqld',
        'use_connections'
    ],
    required => [
        'basedir',
        'input_file',
        'mtr_options']
    );

$config->printHelp if not $o;
$config->printProps;

my $header = $config->header() || [];
my $footer = $config->footer() || [];

# End of user-configurable section

my $iteration = 0;
my $run_id = time();

say("run_id = $run_id");

my $simplifier = GenTest::Simplifier::Mysqltest->new(
    filter => $config->filter(),
    use_connections => $config->use_connections(),
    oracle => sub {
        my $oracle_mysqltest = shift;
        $iteration++;

        chdir($config->basedir.'/mysql-test'); # assume forward slash works

        my $testfile_base_name = $run_id.'-'.$iteration; # we need this for both test- and result file name
        my $testfile = $testfile_base_name.'.test';      # test file of this iteration
        my $resultfile = $testfile_base_name.'.result';      # test file of this iteration

        open (ORACLE_MYSQLTEST, ">t/$testfile") or croak "Unable to open $testfile: $!";

        print ORACLE_MYSQLTEST join("\n",@{$header})."\n\n";
        print ORACLE_MYSQLTEST $oracle_mysqltest;
        print ORACLE_MYSQLTEST "\n\n".join("\n",@{$footer})."\n";
        close ORACLE_MYSQLTEST;

        my $mysqldopt = $config->genOpt('--mysqld=--', 'mysqld');
        my $mtr_start_time = Time::HiRes::time();
        my $mysqltest_cmd = "perl mysql-test-run.pl $mysqldopt ". $config->genOpt('--', 'mtr_options')." t/$testfile 2>&1";
        my $mysqltest_output = `$mysqltest_cmd`;
        my $mtr_exit_code = $? >> 8;
        my $mtr_duration = Time::HiRes::time() - $mtr_start_time;
        if ($iteration == 1) {
            say ($mysqltest_output);
        } else {
            say ("MTR test duration: $mtr_duration; exit_code: $mtr_exit_code");
        }

        system("grep 'Unsafe statement binlogged' ".$config->basedir()."/mysql-test/var/log/mysqld.1.err");
        my $grep_exit_code = $? >> 8;
        if ($grep_exit_code == 0) {
            say("Messages about unsafe replication found in master error log.");
            return ORACLE_ISSUE_NO_LONGER_REPEATABLE;
        } elsif ($grep_exit_code > 1) {
            say("grep on the mysqld.1.err error log failed");
        }

        ########################################################################
        # Start of comparison mode (two basedirs)
        ########################################################################

        if (defined $config->basedir2) {
            if ($iteration == 1) {
                say ('Two basedirs specified. Will compare outputs instead of looking for expected output.');
                say ('Server A: '.$config->basedir);
                say ('Server B: '.$config->basedir2);
                # NOTE: --record MTR option is required. TODO: Check for this?
            }

            #
            # Run the test against basedir2 and compare results against the previous run.
            #

            chdir($config->basedir2.'/mysql-test');

            # working dir is now for Server B, so we need full path to Server A's files for later
            my $testfile_full_path = $config->basedir.'/mysql-test/t/'.$testfile;
            my $resultfile_full_path = $config->basedir.'/mysql-test/r/'.$testfile_base_name.'.result';

            # tests/results for Server B include "-b" in the filename
            my $testfile2_base_name = $run_id.'-'.$iteration.'-b';
            my $testfile2 = $testfile2_base_name.'.test';
            my $testfile2_full_path = $config->basedir2.'/mysql-test/t/'.$testfile2;
            my $resultfile2_full_path = $config->basedir2.'/mysql-test/r/'.$testfile2_base_name.'.result';

            # Copy test file to server B
            copy($testfile_full_path, $testfile2_full_path) or croak("Unable to copy test file $testfile to $testfile2");

            my $mysqltest_cmd2 =
                "perl mysql-test-run.pl $mysqldopt ". $config->genOpt('--', 'mtr_options').
                " $testfile2 2>&1";

            # Run the test against server B
            # we don't really use this output for anything right now
            my $mysqltest_output2 = `$mysqltest_cmd2`;
            #say $mysqltest_output2 if $iteration == 1;

            # Compare the two results
            # We declare the tests to have failed properly only if the results
            # from the two test runs differ.
            # (We ignore expected_mtr_output in this mode)
            my $compare_result = compare($resultfile_full_path, $resultfile2_full_path);
            if ( $compare_result == 0) {
                # no diff
                say('Issue not repeatable (results were equal) with test '.$testfile_base_name);
                if ($iteration > 1) {
                    unlink($testfile_full_path); # deletes test for Server A
                    unlink($testfile2_full_path); # deletes test for Server B
                    unlink($resultfile_full_path); # deletes result for Server A
                    unlink($resultfile2_full_path); # deletes result for Server B
                }
                return ORACLE_ISSUE_NO_LONGER_REPEATABLE;
            } elsif ($compare_result > 0) {
                # diff
                say("Issue is repeatable (results differ) with test $testfile_base_name");
                return ORACLE_ISSUE_STILL_REPEATABLE;
            } else {
                # error ($compare_result < 0)
                if ( (! -e $resultfile_full_path) && (! -e $resultfile2_full_path) ) {
                    # both servers are lacking result file. Probably due to bad SQL in simplified test.
                    return ORACLE_ISSUE_NO_LONGER_REPEATABLE;
                }
                if (! -e $resultfile_full_path) {
                    say("Error ($compare_result) comparing result files for test $testfile_base_name");
                    say("Test output was:");
                    say $mysqltest_output;
                    croak("Resultfile  $resultfile_full_path not found");
                } elsif (! -e $resultfile2_full_path) {
                    say("Error ($compare_result) comparing result files for test $testfile_base_name");
                    say("Test output was:");
                    say $mysqltest_output2;
                    croak("Resultfile2 $resultfile2_full_path not found");
                }
            }

        ########################################################################
        # End of comparison mode (two basedirs)
        ########################################################################

        } else {
            # Only one basedir specified - retain old behavior (look for expected output).

            #
            # We declare the test to have failed properly only if the
            # desired message is present in the output and it is not a
            # result of an error that caused part of the test, including
            # the --croak construct, to be printed to stdout.
            #

            my $expected_mtr_output = $config->expected_mtr_output;
            if (
                ($mysqltest_output =~ m{$expected_mtr_output}sio) &&
                ($mysqltest_output !~ m{--die}sio)
            ) {
                say("Issue repeatable with $testfile");
                return ORACLE_ISSUE_STILL_REPEATABLE;
            } else {
                say("Issue not repeatable with $testfile.");
                if (
                    ($mtr_exit_code == 0) &&
                    ($iteration > 1)
                ) {
                    unlink('t/'.$testfile);
                    unlink('r/'.$resultfile);
                }

                say $mysqltest_output if $iteration > 1 && $mtr_exit_code != 0;
                return ORACLE_ISSUE_NO_LONGER_REPEATABLE;
            }
        }
    }
);

my $simplified_mysqltest;

## Copy input file
if (-f $config->input_file){
    $config->input_file =~ m/\.([a-z]+$)/i;
    my $extension = $1;
    my $input_file_copy = $config->basedir."/mysql-test/t/".$run_id."-0.".$extension;
    system("cp ".$config->input_file." ".$input_file_copy);

    if (lc($extension) eq 'csv') {
        say("Treating ".$config->input_file." as a CSV file");
        $simplified_mysqltest = $simplifier->simplifyFromCSV($input_file_copy);
    } elsif (lc($extension) eq 'test') {
        say("Treating ".$config->input_file." as a mysqltest file");
        open (MYSQLTEST_FILE , $input_file_copy) or croak "Unable to open ".$input_file_copy." as a .test file: $!";
        read (MYSQLTEST_FILE , my $initial_mysqltest, -s $input_file_copy);
        close (MYSQLTEST_FILE);
        $simplified_mysqltest = $simplifier->simplify($initial_mysqltest);
    } else {
        carp "Unknown file type for ".$config->input_file;
    }

    if (defined $simplified_mysqltest) {
        say "Simplified mysqltest:";
        print "\n\n".join("\n",@{$header})."\n\n\n".$simplified_mysqltest.join("\n",@{$footer})."\n\n";
        exit (STATUS_OK);
    } else {
        say "Unable to simplify ". $config->input_file.".\n";
        exit (STATUS_ENVIRONMENT_FAILURE);
    }
} else {
    croak "Can't find ".$config->input_file;
}
##


# Copyright (C) 2008-2009 Sun Microsystems, Inc. All rights reserved.
# Use is subject to license terms.
#
# 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; version 2 of the License.
#
# 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
# USA

use warnings;
use strict;
use DBI;
use Time::HiRes;
use lib 'lib';
use lib '../lib';

$| = 1;

use GenTest::Constants;
use GenTest::Executor::MySQL;
use GenTest::Simplifier::Test;
use GenTest::Simplifier::SQL;
use GenTest::Comparator;

#
# This script demonstrates the simplification of queries. More information is available at
#
# http://forge.mysql.com/wiki/RandomQueryGeneratorSimplification
#

my $query = "SELECT 1 FROM DUAL";

my @dsns = (
	'dbi:mysql:host=127.0.0.1:port=19300:user=root:database=test',
	'dbi:mysql:host=127.0.0.1:port=19302:user=root:database=test'
);

my $maximum_query_duration = 2;
my $performance_threshold = 1.25;

# End of user-editable part

my @executors;
my @connection_ids;

foreach my $dsn (@dsns) {
	my $executor = GenTest::Executor::MySQL->new( dsn => $dsn );
	my $init_status = $executor->init();
	exit ($init_status) if $init_status != STATUS_OK;
	push @connection_ids, $executor->dbh()->selectrow_array("SELECT CONNECTION_ID()");
	$executor->dbh()->do("SET GLOBAL EVENT_SCHEDULER=ON");
	push @executors, $executor;
}

my $simplifier = GenTest::Simplifier::SQL->new(
	oracle => sub {
		my $oracle_query = shift;
		print ".";

		my $outcome;
		my @oracle_results;
		my @oracle_times;

		foreach my $executor_id (0..$#executors) {
			my $executor = $executors[$executor_id];
			$executor->dbh()->do("CREATE EVENT timeout ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL $maximum_query_duration SECOND DO KILL QUERY ".$connection_ids[$executor_id]);
			my $time_start = Time::HiRes::time();
			my $oracle_result = $executor->execute($oracle_query);
			my $duration = (Time::HiRes::time() - $time_start);
			$executor->dbh()->do("DROP EVENT IF EXISTS timeout");
			return ORACLE_ISSUE_NO_LONGER_REPEATABLE if $oracle_result->status() > STATUS_OK;
			push @oracle_times, $duration;
			push @oracle_results, $oracle_result;
		}

		my $best_time = $oracle_times[0] > $oracle_times[1] ? $oracle_times[0] : $oracle_times[1];
		my $worst_time = $oracle_times[0] < $oracle_times[1] ? $oracle_times[0] : $oracle_times[1];

		if (
			($best_time / $worst_time >= $performance_threshold) &&
			($worst_time > 1)
		) {
			print "Repeatable with: $oracle_query\n\n";
			return ORACLE_ISSUE_STILL_REPEATABLE;
		} else {
			return ORACLE_ISSUE_NO_LONGER_REPEATABLE;
		}
	}
);

my $simplified_query = $simplifier->simplify($query);

print "\nSimplified query:\n$simplified_query ;\n\n";

my @simplified_results;

foreach my $executor (@executors) {
        my $simplified_result = $executor->execute($simplified_query);
        push @simplified_results, $simplified_result;
}

my $simplifier_test = GenTest::Simplifier::Test->new(
        executors => \@executors,
        queries => [ $simplified_query, $query ],
        results => [ \@simplified_results ]
);

my $test = $simplifier_test->simplify();

print "Simplified test:\n\n";
print $test;


# Copyright (C) 2008-2009 Sun Microsystems, Inc. All rights reserved.
# Use is subject to license terms.
#
# 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; version 2 of the License.
#
# 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
# USA

use warnings;
use strict;
use DBI;
use lib 'lib';
use lib '../lib';

$| = 1;

use GenTest::Constants;
use GenTest::Executor::MySQL;
use GenTest::Simplifier::Test;
use GenTest::Simplifier::SQL;
use GenTest::Comparator;

#
# This script demonstrates the simplification of queries. More information is available at
#
# http://forge.mysql.com/wiki/RandomQueryGeneratorSimplification
#

my $query = "SELECT 1 FROM DUAL";

my @desired_outcomes = (
	STATUS_CONTENT_MISMATCH,
	STATUS_LENGTH_MISMATCH
);

my @dsns = (
	'dbi:mysql:host=127.0.0.1:port=19300:user=root:database=test',
	'dbi:mysql:host=127.0.0.1:port=19302:user=root:database=test'
);

# End of user-editable part

my @executors;

foreach my $dsn (@dsns) {
	my $executor = GenTest::Executor::MySQL->new( dsn => $dsn );
	my $init_status = $executor->init();
	exit ($init_status) if $init_status != STATUS_OK;
	push @executors, $executor;
}

my $simplifier = GenTest::Simplifier::SQL->new(
	oracle => sub {
		my $oracle_query = shift;
		print ".";

		my $outcome;
		my @oracle_results;

		foreach my $executor (@executors) {
			my $oracle_result = $executor->execute($oracle_query, 1);
			push @oracle_results, $oracle_result;
		}

		if ($#executors == 0) {
			$outcome = $oracle_results[0]->status();
		} else {
			$outcome = GenTest::Comparator::compare($oracle_results[0], $oracle_results[1]);
		}

		foreach my $desired_outcome (@desired_outcomes) {
			return ORACLE_ISSUE_STILL_REPEATABLE if $outcome == $desired_outcome;
		}

		return ORACLE_ISSUE_NO_LONGER_REPEATABLE;
	}
);

my $simplified_query = $simplifier->simplify($query);

print "\nSimplified query:\n$simplified_query ;\n\n";

my @simplified_results;

foreach my $executor (@executors) {
        my $simplified_result = $executor->execute($simplified_query);
        push @simplified_results, $simplified_result;
}

my $simplifier_test = GenTest::Simplifier::Test->new(
        executors => \@executors,
        queries => [ $simplified_query, $query ],
        results => [ \@simplified_results ]
);

my $test = $simplifier_test->simplify();

print "Simplified test:\n\n";
print $test;


# Copyright (C) 2008-2009 Sun Microsystems, Inc. All rights reserved.
# Use is subject to license terms.
#
# 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; version 2 of the License.
#
# 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
# USA

use strict;
use DBI;
use lib 'lib';
use lib '../lib';

$| = 1;
require GenTest::Simplifier::SQL;

#
# This script demonstrates the simplification of queries that fail sporadically. In order to account for the sporadicity,
# we define an oracle() that runs every query 5000 times, and reports that the problem is gone only if all 5000 instances
# returned the same number of rows. Otherwise, it reports that the problem remains, and the Simplifier will use this information
# to further quide the simplification process. More information is available at:
#
# http://forge.mysql.com/wiki/RandomQueryGeneratorSimplification
#

my $query = " SELECT table3 .`date_key` field1  FROM B table1  LEFT  JOIN B  JOIN ( B table3  JOIN ( AA table4  JOIN ( C table6  JOIN A table7  ON table6 .`varchar_nokey`  )  ON table6 .`int_key`  )  ON table6 .`int_nokey`  )  ON table6 .`varchar_nokey`  ON table6 .`date_key`  WHERE  NOT ( (  NOT (  NOT (  NOT (  NOT table7 .`int_key`  >= table1 .`varchar_key`  OR table3 .`time_nokey`  <> table1 .`pk`  )  AND table4 .`date_key`  >= table1 .`date_key`  )  OR table3 .`time_key`  > '2005-07-24 11:06:03' )  AND table1 .`datetime_key`  <=  8  )  AND table7 .`pk`  <  6  )  GROUP  BY field1  ORDER  BY field1  , field1  , field1  , field1  LIMIT  7 ";
my $trials = 1000;

my $dsn = 'dbi:mysql:host=127.0.0.1:port=19306:user=root:database=test';
my $dbh = DBI->connect($dsn);

my $simplifier = GenTest::Simplifier::SQL->new(
	oracle => sub {
		my $query = shift;
		print "testing $query\n";
		my %outcomes;
		foreach my $trial (1..$trials) {
			my $sth = $dbh->prepare($query);
			$sth->execute();
			return 0 if $sth->err() > 0;
			$outcomes{$sth->rows()}++;
			print "*";
			return 1 if scalar(keys %outcomes) > 1;
		}
		return 0;
	}
);
my $simplified = $simplifier->simplify($query);

print "Simplified query:\n$simplified;\n";


#!/usr/bin/perl

# Copyright (c) 2002 MySQL AB, 2009 Sun Microsystems, Inc.
# Use is subject to license terms.
#
# 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; version 2 of the License.
#
# 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA

die "No files specified\n" unless $ARGV[0];

$ctags="exctags -x -f - --c-types=f -u";

sub get_tag {
  local $.; local $_=<TAGS>;
  ($symbol, $line)= /^(.*\S)\s+function\s+(\d+)/;
  $symbol=$1 if /[\s*]([^\s*]+)\s*\(/;
  $line=1e50 unless $line;
}

while($src=shift)
{
  warn "==> $src\n";

  $dst=$src.$$;
  open(TAGS, "$ctags $src|") || die "Cannot exec('$ctags $src'): $!";
  open(SRC, "<$src") || die "Cannot open $src: $!";
  open(DST, ">$dst") || die "Cannot create $dst: $!";
  select DST;

  &get_tag;
  $in_func=0;
  while(<SRC>)
  {
    my $orig=$_;
    if ($in_func)
    {
      if (/\breturn\b/ && !/\/\*.*\breturn\b.*\*\// && !/;/ )
      {
        $_.=<SRC> until /;/;
      }
      s/(?<=\s)return\s*;/DBUG_VOID_RETURN;/;
      s/(?<=\s)return\s*(.+)\s*;/DBUG_RETURN(\1);/s;
      $ret_line=$. if /DBUG_(VOID_)?RETURN/; #{{
      print "$tab  DBUG_VOID_RETURN;\n" if /^$tab}/ && $ret_line < $.-1;
      $in_func=0 if /^$tab}/;
      warn "$src:".($.-1)."\t$orig" if /\breturn\b/;
    }
    print;
    next if $. < $line;
    die "Something wrong: \$.=$., \$line=$line, \$symbol=$symbol\n" if $. > $line;
    &get_tag && next if /^\s*inline /;
    print $_=<SRC> until /{/; $tab=$`;
    &get_tag && next if /}/; # skip one-liners
    $semicolon=1;
    while(<SRC>)
    {
      $skip=!$semicolon;
      $semicolon= /;\s*$/;
      print && next if $skip ||
        (/^\s+\w+((::\w+)?|<\w+>)\s+\**\w+/ && !/^\s*return\b/);
      last if /DBUG_ENTER/;
      print "$tab  DBUG_ENTER(\"$symbol\");\n";
      print "\n" unless $_ eq "\n";
      last;
    }
    $in_func=1;
    &get_tag;
    redo;
  }
  close SRC;
  close DST;
  close TAGS;
  unlink("$src.orig");
  rename($src, "$src.orig") || die "Cannot rename $src to $src.orig: $!";
  rename($dst, $src) || die "Cannot rename $dst to $src: $!";
}

warn "All done!\n";


#!/usr/bin/perl

die <<EEE unless @ARGV;
Usage: $0 func1 [func2 [ ...] ]

This filter (stdin->stdout) removes lines from dbug trace that were generated
by specified functions and all functions down the call stack. Produces the
same effect as if the original source had DBUG_PUSH(""); right after
DBUG_ENTER() and DBUG_POP(); right before DBUG_RETURN in every such a function.
EEE

$re=join('|', @ARGV);
$skip='';

while(<STDIN>) {
  print unless $skip;
  next unless /^(?:.*: )*((?:\| )*)([<>])($re)\n/o;
  if ($2 eq '>') {
    $skip=$1.$3 unless $skip;
    next;
  }
  next if $skip ne $1.$3;
  $skip='';
  print;
}


#!/usr/bin/env perl

#
#  A driver program to test DBUG features - runs tests (shell commands)
#  from the end of file to invoke tests.c, which does the real dbug work.
#

use Test::More;

$exe=$0;

die unless $exe =~ s/(tests)-t(\.exe)?$/$1$2 /;

# load tests
@tests=();
while (<DATA>) {
  if (/^% \.\/tests /) {
    push @tests, [ $' ]
  } elsif (/^#/) {
    next;
  } else {
    push @{$tests[$#tests]}, $_
  }
}

plan skip_all => "because dbug is disabled" if system $exe;

plan tests => scalar(@tests);

for (@tests) {
  $t=$exe . shift @$_;
  chomp($t);
  open F, '-|',  $t or die "open($t|): $!";
  local $";
  $out=join($", <F>); close(F);
  # special cases are handled here:
  $out =~ s/Memory: 0x[0-9A-Fa-f]+/Memory: 0x####/g if $t =~ /dump/;
  # compare ("\n" at the beginning makes better output in case of errors)
  is("\n$out","\n@$_", $t);
}

__DATA__
% ./tests -#d
func2: info: s=ok
=> execute
=> evaluate: ON
=> evaluate_if: OFF
main: explain: dbug explained: d
func2: info: s=ok
% ./tests d,ret3
=> evaluate: OFF
=> evaluate_if: OFF
#
## Testing negative lists
#
% ./tests d:-d,ret3
func2: info: s=ko
=> execute
=> evaluate: ON
=> evaluate_if: OFF
main: explain: dbug explained: d:-d,ret3
func2: info: s=ko
% ./tests t:-d,ret3
>main
| >func1
| | >func2
| | | >func3
| | | <func3
| | <func2
| <func1
=> evaluate: OFF
=> evaluate_if: OFF
| >func2
| | >func3
| | <func3
| <func2
<main
% ./tests t:d,info:-d,ret3
>main
| >func1
| | >func2
| | | >func3
| | | <func3
| | | info: s=ko
| | <func2
| <func1
=> evaluate: OFF
=> evaluate_if: OFF
| >func2
| | >func3
| | <func3
| | info: s=ko
| <func2
<main
% ./tests t:d,info:-d,ret3:-f,func2
>main
| >func1
| | | >func3
| | | <func3
| <func1
=> evaluate: OFF
=> evaluate_if: OFF
| | >func3
| | <func3
<main
% ./tests t:d,info:-d,ret3:-f,func2 d,evaluate
=> evaluate: ON
=> evaluate_if: OFF
% ./tests t:d,info:-d,ret3:-f,func2 d,evaluate_if
=> evaluate: OFF
=> evaluate_if: ON
% ./tests t:d:-d,ret3:-f,func2 d,evaluate_if
=> evaluate: OFF
=> evaluate_if: ON
% ./tests t:d:-d,ret3:-f,func2
>main
| >func1
| | | >func3
| | | <func3
| <func1
=> execute
=> evaluate: ON
=> evaluate_if: OFF
| explain: dbug explained: d:-d,ret3:f:-f,func2:t
| | >func3
| | <func3
<main
#
## Adding incremental settings to the brew
#
% ./tests t:d:-d,ret3:-f,func2 +d,evaluate_if
>main
| >func1
| | | >func3
| | | <func3
| <func1
=> evaluate: OFF
=> evaluate_if: ON
| | >func3
| | <func3
<main
#
## DBUG_DUMP
#
% ./tests t:d:-d,ret3:f:-f,func2 +d,dump
>main
| >func1
| | | >func3
| | | <func3
| <func1
| dump: Memory: 0x####  Bytes: (27)
64 2C 64 75 6D 70 3A 2D 64 2C 72 65 74 33 3A 66 3A 2D 66 2C 66 75 6E 63 32 3A
74
=> evaluate: OFF
=> evaluate_if: OFF
| | >func3
| | <func3
<main
% ./tests t:d:-d,ret3:f:-f,func2 +d,dump
>main
| >func1
| | | >func3
| | | <func3
| <func1
| dump: Memory: 0x####  Bytes: (27)
64 2C 64 75 6D 70 3A 2D 64 2C 72 65 74 33 3A 66 3A 2D 66 2C 66 75 6E 63 32 3A
74
=> evaluate: OFF
=> evaluate_if: OFF
| | >func3
| | <func3
<main
% ./tests t:d:-d,ret3:f:-f,func2:+d,dump
>main
| >func1
| | | >func3
| | | <func3
| <func1
| dump: Memory: 0x####  Bytes: (27)
64 2C 64 75 6D 70 3A 2D 64 2C 72 65 74 33 3A 66 3A 2D 66 2C 66 75 6E 63 32 3A
74
=> evaluate: OFF
=> evaluate_if: OFF
| | >func3
| | <func3
<main
% ./tests t:d:-d,ret3:f:-f,func2 +d,dump,explain
>main
| >func1
| | | >func3
| | | <func3
| <func1
| dump: Memory: 0x####  Bytes: (35)
64 2C 64 75 6D 70 2C 65 78 70 6C 61 69 6E 3A 2D 64 2C 72 65 74 33 3A 66 3A 2D
66 2C 66 75 6E 63 32 3A 74
=> evaluate: OFF
=> evaluate_if: OFF
| explain: dbug explained: d,dump,explain:-d,ret3:f:-f,func2:t
| | >func3
| | <func3
<main
% ./tests t:d:-d,ret3:f:-f,func2 +d,dump,explain:P
dbug: >main
dbug-tests: | >func1
dbug-tests: | | | >func3
dbug-tests: | | | <func3
dbug-tests: | <func1
dbug-tests: | dump: Memory: 0x####  Bytes: (37)
64 2C 64 75 6D 70 2C 65 78 70 6C 61 69 6E 3A 2D 64 2C 72 65 74 33 3A 66 3A 2D
66 2C 66 75 6E 63 32 3A 50 3A 74
=> evaluate: OFF
=> evaluate_if: OFF
dbug-tests: | explain: dbug explained: d,dump,explain:-d,ret3:f:-f,func2:P:t
dbug-tests: | | >func3
dbug-tests: | | <func3
dbug-tests: <main
% ./tests t:d:-d,ret3:f:-f,func2 +d,dump,explain:P:F
dbug:        tests.c: >main
dbug-tests:        tests.c: | >func1
dbug-tests:        tests.c: | | | >func3
dbug-tests:        tests.c: | | | <func3
dbug-tests:        tests.c: | <func1
dbug-tests:        tests.c: | dump: Memory: 0x####  Bytes: (39)
64 2C 64 75 6D 70 2C 65 78 70 6C 61 69 6E 3A 2D 64 2C 72 65 74 33 3A 66 3A 2D
66 2C 66 75 6E 63 32 3A 46 3A 50 3A 74
=> evaluate: OFF
=> evaluate_if: OFF
dbug-tests:        tests.c: | explain: dbug explained: d,dump,explain:-d,ret3:f:-f,func2:F:P:t
dbug-tests:        tests.c: | | >func3
dbug-tests:        tests.c: | | <func3
dbug-tests:        tests.c: <main
#
## DBUG_EXPLAIN, DBUG_PUSH, DBUG_POP, DBUG_SET
#
% ./tests t:d:-d,ret3:f:-f,func2
>main
| >func1
| | | >func3
| | | <func3
| <func1
=> execute
=> evaluate: ON
=> evaluate_if: OFF
| explain: dbug explained: d:-d,ret3:f:-f,func2:t
| | >func3
| | <func3
<main
% ./tests t:d:-d,ret3
>main
| >func1
| | >func2
| | | >func3
| | | <func3
| | | info: s=ko
| | <func2
| <func1
=> execute
=> evaluate: ON
=> evaluate_if: OFF
| explain: dbug explained: d:-d,ret3:t
| >func2
| | >func3
| | <func3
| | info: s=ko
| <func2
<main
% ./tests d,info:-d,ret3:d,push
func2: info: s=ko
=> evaluate: OFF
=> evaluate_if: OFF
| >func2
| | >func3
| | <func3
| | info: s=ko
| <func2
<main
% ./tests d,info:-d,ret3:d,push,explain
func2: info: s=ko
=> evaluate: OFF
=> evaluate_if: OFF
| explain: dbug explained: d,info,push,explain:-d,ret3:t
| >func2
| | >func3
| | <func3
| | info: s=ko
| <func2
<main
% ./tests d,info:-d,ret3:d,explain
func2: info: s=ko
=> evaluate: OFF
=> evaluate_if: OFF
main: explain: dbug explained: d,info,explain:-d,ret3
func2: info: s=ko
% ./tests d,info:-d,ret3:d,explain,pop
func2: info: s=ko
=> evaluate: OFF
=> evaluate_if: OFF
% ./tests d,info:-d,ret3:d,explain t:d,pop
>main
| >func1
| | >func2
| | | >func3
| | | <func3
| | <func2
| <func1
=> evaluate: OFF
=> evaluate_if: OFF
main: explain: dbug explained: d,info,explain:-d,ret3
func2: info: s=ko
% ./tests d,info:-d,ret3:d,explain,pop +t
>main
| >func1
| | >func2
| | | >func3
| | | <func3
| | | info: s=ko
| | <func2
| <func1
=> evaluate: OFF
=> evaluate_if: OFF
main: explain: dbug explained: d,info,explain,pop:-d,ret3
func2: info: s=ko
% ./tests d,info:-d,ret3:d,explain,set
func2: info: s=ko
=> evaluate: OFF
=> evaluate_if: OFF
       tests.c: main: explain: dbug explained: d,info,explain,set:-d,ret3:F
       tests.c: func2: info: s=ko
% ./tests d,info:-d,ret3:d,explain,set:t
>main
| >func1
| | >func2
| | | >func3
| | | <func3
| | | info: s=ko
| | <func2
| <func1
=> evaluate: OFF
=> evaluate_if: OFF
       tests.c: | explain: dbug explained: d,info,explain,set:-d,ret3:F:t
       tests.c: | >func2
       tests.c: | | >func3
       tests.c: | | <func3
       tests.c: | | info: s=ko
       tests.c: | <func2
       tests.c: <main
% ./tests t d,info:-d,ret3:d,explain,set:t
>main
| >func1
| | >func2
| | | >func3
| | | <func3
| | | info: s=ko
| | <func2
| <func1
=> evaluate: OFF
=> evaluate_if: OFF
       tests.c: | explain: dbug explained: d,info,explain,set:-d,ret3:F:t
       tests.c: | >func2
       tests.c: | | >func3
       tests.c: | | <func3
       tests.c: | | info: s=ko
       tests.c: | <func2
       tests.c: <main
% ./tests t d,info:-d,ret3:d,explain,set,pop
func2: info: s=ko
=> evaluate: OFF
=> evaluate_if: OFF
| >func2
| | >func3
| | <func3
| <func2
<main
% ./tests t:f,func2
| | >func2
| | <func2
=> evaluate: OFF
=> evaluate_if: OFF
| >func2
| <func2
#
## Testing SUBDIR rules
#
% ./tests t:-f,func2/:d
>main
| >func1
| <func1
=> execute
=> evaluate: ON
=> evaluate_if: OFF
| explain: dbug explained: d:f:-f,func2/:t
<main
% ./tests t:f,func1/:d
| >func1
| | >func2
| | | >func3
| | | <func3
| | | info: s=ok
| | <func2
| <func1
=> evaluate: OFF
=> evaluate_if: OFF
% ./tests t:f,main/:d,pop
>main
| >func1
| | >func2
| | | >func3
| | | <func3
| | <func2
| <func1
=> evaluate: OFF
=> evaluate_if: OFF
% ./tests f,main/:d,push
=> evaluate: OFF
=> evaluate_if: OFF
| >func2
| | >func3
| | <func3
| <func2
<main
#
## Testing FixTraceFlags() - when we need to traverse the call stack
# (these tests fail with FixTraceFlags() disabled)
#
# delete the INCLUDE rule up the stack
% ./tests t:f,func1/ --push1=t:f,func3/
| >func1
| | >func2
| | | >func3
| | | <func3
| | <func2
=> push1
=> evaluate: OFF
=> evaluate_if: OFF
| | >func3
| | <func3
# delete the EXCLUDE rule up the stack
% ./tests t:-f,func1/ --push1=t
>main
=> push1
| <func1
=> evaluate: OFF
=> evaluate_if: OFF
| >func2
| | >func3
| | <func3
| <func2
<main
# add the INCLUDE rule up the stack
% ./tests t:f,func3 --push1=t:f,main/
| | | >func3
| | | <func3
=> push1
| <func1
=> evaluate: OFF
=> evaluate_if: OFF
| >func2
| | >func3
| | <func3
| <func2
<main
# add the EXCLUDE rule up the stack
% ./tests t --push1=t:-f,main/
>main
| >func1
| | >func2
| | | >func3
| | | <func3
| | <func2
=> push1
=> evaluate: OFF
=> evaluate_if: OFF
# change the defaults
% ./tests t:f,func3 --push1=t
| | | >func3
| | | <func3
=> push1
| <func1
=> evaluate: OFF
=> evaluate_if: OFF
| >func2
| | >func3
| | <func3
| <func2
<main
# repeated keyword
% ./tests d:-d,info,info
=> execute
=> evaluate: ON
=> evaluate_if: OFF
main: explain: dbug explained: d:-d,info
% ./tests d:-d,info/,info
=> execute
=> evaluate: ON
=> evaluate_if: OFF
main: explain: dbug explained: d:-d,info/


#!/usr/bin/perl

# Copyright (C) 2006 MySQL AB
# Use is subject to license terms
#
# 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; version 2 of the License.
#
# 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA

#
# This script generates defines for all functions
# in yassl/include/openssl/ so they are renamed to
# ya<old_function_name>. Hopefully that is unique enough.
#
# The script is to be run manually when we import
# a new version of yaSSL
#

# Find all functions in "input" and add macros
# to prefix/rename them into "output
sub generate_prefix($$)
{
  my $input= shift;
  my $output= shift;
  open(IN, $input)
      or die("Can't open input file $input: $!");
  open(OUT, ">", $output)
    or mtr_error("Can't open output file $output: $!");

  while (<IN>)
  {
    chomp;

    if ( /typedef/ )
    {
      next;
    }

    if ( /^\s*[a-zA-Z0-9*_ ]+\s+\*?([_a-zA-Z0-9]+)\s*\(/ )
    {
      print OUT "#define $1 ya$1\n";
    }
  }

  close OUT;
  close IN;
}

generate_prefix("ssl.h", "prefix_ssl.h");
generate_prefix("crypto.h", "prefix_crypto.h");


#!/usr/bin/perl

# Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU Library General Public
# License as published by the Free Software Foundation; version 2
# of the License.
#
# 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
# Library 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

# ======================================================================
#                     MySQL server stress test system
# ======================================================================
#
##########################################################################
#
#                       SCENARIOS AND REQUIREMENTS
#
#   The system should perform stress testing of MySQL server with
# following requirements and basic scenarios:
#
# Basic requirements:
#
# Design of stress script should allow one:
#
#   - to use for stress testing mysqltest binary as test engine
#   - to use for stress testing both regular test suite and any
#     additional test suites (e.g. mysql-test-extra-5.0)
#   - to specify files with lists of tests both for initialization of
#     stress db and for further testing itself
#   - to define number of threads that will be concurrently used in testing
#   - to define limitations for test run. e.g. number of tests or loops
#     for execution or duration of testing, delay between test executions, etc.
#   - to get readable log file which can be used for identification of
#     errors arose during testing
#
# Basic scenarios:
#
#     * It should be possible to run stress script in standalone mode
#       which will allow to create various scenarios of stress workloads:
#
#       simple ones:
#
#         box #1:
#           - one instance of script with list of tests #1
#
#       and more advanced ones:
#
#         box #1:
#           - one instance of script with list of tests #1
#           - another instance of script with list of tests #2
#         box #2:
#           - one instance of script with list of tests #3
#           - another instance of script with list of tests #4
#             that will recreate whole database to back it to clean
#             state
#
#       One kind of such complex scenarios maybe continued testing
#       when we want to run stress tests from many boxes with various
#       lists of tests that will last very long time. And in such case
#       we need some wrapper for MySQL server that will restart it in
#       case of crashes.
#
#     * It should be possible to run stress script in ad-hoc mode from
#       shell or perl versions of mysql-test-run. This allows developers
#       to reproduce and debug errors that was found in continued stress
#       testing
#
# 2009-01-28 OBN Additions and modifications per WL#4685
#
########################################################################

use Config;

if (!defined($Config{useithreads}))
{
  die <<EOF;
It is unable to run threaded version of stress test on this system
due to disabled ithreads. Please check that installed perl binary
was built with support of ithreads.
EOF
}

use threads;
use threads::shared;

use IO::Socket;
use Sys::Hostname;
use File::Copy;
use File::Spec;
use File::Find;
use File::Basename;
use File::Path;
use Cwd;

use Data::Dumper;
use Getopt::Long;

my $stress_suite_version="1.0";

$|=1;

$opt_server_host="";
$opt_server_logs_dir="";
$opt_help="";
$opt_server_port="";
$opt_server_socket="";
$opt_server_user="";
$opt_server_password="";
$opt_server_database="";
$opt_cleanup="";
$opt_verbose="";
$opt_log_error_details="";

$opt_suite="main";
$opt_stress_suite_basedir="";
$opt_stress_basedir="";
$opt_stress_datadir="";
$opt_test_suffix="";

$opt_stress_mode="random";

$opt_loop_count=0;
$opt_test_count=0;
$opt_test_duration=0;
# OBN: Changing abort-on-error default to -1 (for WL-4626/4685): -1 means no abort
$opt_abort_on_error=-1;
$opt_sleep_time = 0;
$opt_threads=1;
$pid_file="mysql_stress_test.pid";
$opt_mysqltest= ($^O =~ /mswin32/i) ? "mysqltest.exe" : "mysqltest";
$opt_check_tests_file="";
# OBM adding a setting for 'max-connect-retries=20' the default of 500 is to high
@mysqltest_args=("--silent", "-v", "--max-connect-retries=20");

# Client ip address
$client_ip=inet_ntoa((gethostbyname(hostname()))[4]);
$client_ip=~ s/\.//g;

%tests_files=(client => {mtime => 0, data => []},
              initdb => {mtime => 0, data => []});

# Error codes and sub-strings with corresponding severity
#
# S1 - Critical errors - cause immediately abort of testing. These errors
#                        could be caused by server crash or impossibility
#                        of test execution.
#
# S2 - Serious errors - these errors are bugs for sure as it knowns that
#                       they shouldn't appear during stress testing
#
# S3 - Unknown errors - Errors were returned but we don't know what they are
#                       so script can't determine if they are OK or not
#
# S4 - Non-seriuos errros - these errors could be caused by fact that
#                           we execute simultaneously statements that
#                           affect tests executed by other threads

%error_strings = ( 'Failed in mysql_real_connect()' => S1,
                   'Can\'t connect' => S1,
                   'not found (Errcode: 2)' => S1,
                   'does not exist' => S1,
                   'Could not open connection \'default\' after \d+ attempts' => S1,
                   'wrong errno ' => S3,
                   'Result length mismatch' => S4,
                   'Result content mismatch' => S4);

%error_codes = ( 1012 => S2, 1015 => S2, 1021 => S2,
                 1027 => S2, 1037 => S2, 1038 => S2,
                 1039 => S2, 1040 => S2, 1046 => S2,
                 1053 => S2, 1180 => S2, 1181 => S2,
                 1203 => S2, 1205 => S4, 1206 => S2,
                 1207 => S2, 1213 => S4, 1223 => S2,
                 2002 => S1, 2003 => S1, 2006 => S1,
                 2013 => S1
                 );

share(%test_counters);
%test_counters=( loop_count => 0, test_count=>0);

share($exiting);
$exiting=0;

# OBN Code and 'set_exit_code' function added by ES to set an exit code based on the error category returned
#     in combination with the --abort-on-error value see WL#4685)
use constant ABORT_MAKEWEIGHT => 20;
share($gExitCode);
$gExitCode = 0;   # global exit code
sub set_exit_code {
	my $severity = shift;
	my $code = 0;
	if ( $severity =~ /^S(\d+)/ ) {
		$severity = $1;
		$code = 11 - $severity; # S1=10, S2=9, ... -- as per WL
	}
	else {
	# we know how we call the sub: severity should be S<num>; so, we should never be here...
		print STDERR "Unknown severity format: $severity; setting to S1\n";
		$severity = 1;
	}
	$abort = 0;
	if ( $severity <= $opt_abort_on_error ) {
		# the test finished with a failure severe enough to abort. We are adding the 'abort flag' to the exit code
		$code += ABORT_MAKEWEIGHT;
		# but are not exiting just yet -- we need to update global exit code first
		$abort = 1;
	}
	lock $gExitCode; # we can use lock here because the script uses threads anyway
	$gExitCode = $code if $code > $gExitCode;
	kill INT, $$ if $abort; # this is just a way to call sig_INT_handler: it will set exiting flag, which should do the rest
}

share($test_counters_lock);
$test_counters_lock=0;
share($log_file_lock);
$log_file_lock=0;

$SIG{INT}= \&sig_INT_handler;
$SIG{TERM}= \&sig_TERM_handler;

GetOptions("server-host=s", "server-logs-dir=s", "server-port=s",
           "server-socket=s", "server-user=s", "server-password=s",
           "server-database=s",
           "stress-suite-basedir=s", "suite=s", "stress-init-file:s",
           "stress-tests-file:s", "stress-basedir=s", "stress-mode=s",
           "stress-datadir=s",
           "threads=s", "sleep-time=s", "loop-count=i", "test-count=i",
           "test-duration=i", "test-suffix=s", "check-tests-file",
           "verbose", "log-error-details", "cleanup", "mysqltest=s",
           # OBN: (changing 'abort-on-error' to numberic for WL-4626/4685)
           "abort-on-error=i" => \$opt_abort_on_error, "help") || usage(1);

usage(0) if ($opt_help);

#$opt_abort_on_error=1;

$test_dirname=get_timestamp();
$test_dirname.="-$opt_test_suffix" if ($opt_test_suffix ne '');

print <<EOF;
#############################################################
                  CONFIGURATION STAGE
#############################################################
EOF

if ($opt_stress_basedir eq '' || $opt_stress_suite_basedir eq '' ||
    $opt_server_logs_dir eq '')
{
  die <<EOF;

Options --stress-basedir, --stress-suite-basedir and --server-logs-dir are
required. Please use these options to specify proper basedir for
client, test suite and location of server logs.

stress-basedir: '$opt_stress_basedir'
stress-suite-basedir: '$opt_stress_suite_basedir'
server-logs-dir: '$opt_server_logs_dir'

EOF
}

#Workaround for case when we got relative but not absolute path
$opt_stress_basedir=File::Spec->rel2abs($opt_stress_basedir);
$opt_stress_suite_basedir=File::Spec->rel2abs($opt_stress_suite_basedir);
$opt_server_logs_dir=File::Spec->rel2abs($opt_server_logs_dir);

if ($opt_stress_datadir ne '')
{
  $opt_stress_datadir=File::Spec->rel2abs($opt_stress_datadir);
}

if (! -d "$opt_stress_basedir")
{
  die <<EOF;

Directory '$opt_stress_basedir' does not exist.
Use --stress-basedir option to specify proper basedir for client

EOF
}

if (!-d $opt_stress_suite_basedir)
{
  die <<EOF;

Directory '$opt_stress_suite_basedir' does not exist.
Use --stress-suite-basedir option to specify proper basedir for test suite

EOF
}

$test_dataset_dir=$opt_stress_suite_basedir;
if ($opt_stress_datadir ne '')
{
  if (-d $opt_stress_datadir)
  {
    $test_dataset_dir=$opt_stress_datadir;

  }
  else
  {
    die <<EOF;
Directory '$opt_stress_datadir' not exists. Please specify proper one
with --stress-datadir option.
EOF
  }
}

if ($^O =~ /mswin32/i)
{
  $test_dataset_dir=~ s/\\/\\\\/g;
}
else
{
  $test_dataset_dir.="/";
}

if (!-d $opt_server_logs_dir)
{
  die <<EOF;

Directory server-logs-dir '$opt_server_logs_dir' does not exist.
Use --server-logs-dir option to specify proper directory for storing
logs

EOF
}
else
{
  #Create sub-directory for test session logs
  mkpath(File::Spec->catdir($opt_server_logs_dir, $test_dirname), 0, 0755);
  #Define filename of global session log file
  $stress_log_file=File::Spec->catfile($opt_server_logs_dir, $test_dirname,
                                       "mysql-stress-test.log");
}

if ($opt_suite ne '' && $opt_suite ne 'main' && $opt_suite ne 'default')
{
  $test_suite_dir=File::Spec->catdir($opt_stress_suite_basedir, "suite", $opt_suite);
}
else
{
  $test_suite_dir= $opt_stress_suite_basedir;
}

if (!-d $test_suite_dir)
{
  die <<EOF

Directory '$test_suite_dir' does not exist.
Use --suite options to specify proper dir for test suite

EOF
}

$test_suite_t_path=File::Spec->catdir($test_suite_dir,'t');
$test_suite_r_path=File::Spec->catdir($test_suite_dir,'r');

foreach my $suite_dir ($test_suite_t_path, $test_suite_r_path)
{
  if (!-d $suite_dir)
  {
    die <<EOF;

Directory '$suite_dir' does not exist.
Please ensure that you specified proper source location for
test/result files with --stress-suite-basedir option and name
of test suite with --suite option

EOF
  }
}

$test_t_path=File::Spec->catdir($opt_stress_basedir,'t');
$test_r_path=File::Spec->catdir($opt_stress_basedir,'r');

foreach $test_dir ($test_t_path, $test_r_path)
{
  if (-d $test_dir)
  {
    if ($opt_cleanup)
    {
      #Delete existing 't', 'r', 'r/*' subfolders in $stress_basedir
      rmtree("$test_dir", 0, 0);
      print "Cleanup $test_dir\n";
    }
    else
    {
      die <<EOF;
Directory '$test_dir' already exist.
Please ensure that you specified proper location of working dir
for current test run with --stress-basedir option or in case of staled
directories use --cleanup option to remove ones
EOF
    }
  }
  #Create empty 't', 'r' subfolders that will be filled later
  mkpath("$test_dir", 0, 0777);
}

if (!defined($opt_stress_tests_file) && !defined($opt_stress_init_file))
{
  die <<EOF;
You should run stress script either with --stress-tests-file or with
--stress-init-file otions. See help for details.
EOF
}

if (defined($opt_stress_tests_file))
{
  if ($opt_stress_tests_file eq '')
  {
    #Default location of file with set of tests for current test run
    $tests_files{client}->{filename}= File::Spec->catfile($opt_stress_suite_basedir,
                                      "testslist_client.txt");
  }
  else
  {
    $tests_files{client}->{filename}= $opt_stress_tests_file;
  }

  if (!-f $tests_files{client}->{filename})
  {
    die <<EOF;

File '$tests_files{client}->{filename}' with list of tests not exists.
Please ensure that this file exists, readable or specify another one with
--stress-tests-file option.

EOF
  }
}

if (defined($opt_stress_init_file))
{
  if ($opt_stress_init_file eq '')
  {
    #Default location of file with set of tests for current test run
    $tests_files{initdb}->{filename}= File::Spec->catfile($opt_stress_suite_basedir,
                                      "testslist_initdb.txt");
  }
  else
  {
    $tests_files{initdb}->{filename}= $opt_stress_init_file;
  }

  if (!-f $tests_files{initdb}->{filename})
  {
    die <<EOF;

File '$tests_files{initdb}->{filename}' with list of tests for initialization of database
for stress test not exists.
Please ensure that this file exists, readable or specify another one with
--stress-init-file option.

EOF
  }
}

if ($opt_stress_mode !~ /^(random|seq)$/)
{
  die <<EOF
Was specified wrong --stress-mode. Correct values 'random' and 'seq'.
EOF
}

if (open(TEST, "$opt_mysqltest -V |"))
{
  $mysqltest_version=join("",<TEST>);
  close(TEST);
  print "FOUND MYSQLTEST BINARY: ", $mysqltest_version,"\n";
}
else
{
  die <<EOF;
ERROR: mysqltest binary $opt_mysqltest not found $!.
You must either specify file location explicitly using --mysqltest
option, or make sure path to mysqltest binary is listed
in your PATH environment variable.
EOF
}

#
#Adding mysql server specific command line options for mysqltest binary
#
$opt_server_host= $opt_server_host ? $opt_server_host : "localhost";
$opt_server_port= $opt_server_port ? $opt_server_port : "3306";
$opt_server_user= $opt_server_user ? $opt_server_user : "root";
$opt_server_socket= $opt_server_socket ? $opt_server_socket : "/tmp/mysql.sock";
$opt_server_database= $opt_server_database ? $opt_server_database : "test";

unshift @mysqltest_args, "--host=$opt_server_host";
unshift @mysqltest_args, "--port=$opt_server_port";
unshift @mysqltest_args, "--user=$opt_server_user";
unshift @mysqltest_args, "--password=$opt_server_password";
unshift @mysqltest_args, "--socket=$opt_server_socket";
unshift @mysqltest_args, "--database=$opt_server_database";

#Export variables that could be used in tests
$ENV{MYSQL_TEST_DIR}=$test_dataset_dir;
$ENV{MASTER_MYPORT}=$opt_server_port;
$ENV{MASTER_MYSOCK}=$opt_server_socket;

print <<EOF;
TEST-SUITE-BASEDIR: $opt_stress_suite_basedir
SUITE:              $opt_suite
TEST-BASE-DIR:      $opt_stress_basedir
TEST-DATADIR:       $test_dataset_dir
SERVER-LOGS-DIR:    $opt_server_logs_dir

THREADS:            $opt_threads
TEST-MODE:          $opt_stress_mode

EOF

#-------------------------------------------------------------------------------
#At this stage we've already checked all needed pathes/files
#and ready to start the test
#-------------------------------------------------------------------------------

if (defined($opt_stress_tests_file) || defined($opt_stress_init_file))
{
  print <<EOF;
#############################################################
                  PREPARATION STAGE
#############################################################
EOF

  #Copy Test files from network share to 't' folder
  print "\nCopying Test files from $test_suite_t_path to $test_t_path folder...";
  find({wanted=>\&copy_test_files, bydepth=>1}, "$test_suite_t_path");
  print "Done\n";

  #$test_r_path/r0 dir reserved for initdb
  $count_start= defined($opt_stress_init_file) ? 0 : 1;

  our $r_folder='';
  print "\nCreating 'r' folder and copying Protocol files to each 'r#' sub-folder...";
  for($count=$count_start; $count <= $opt_threads; $count++)
  {
    $r_folder = File::Spec->catdir($test_r_path, "r".$count);
    mkpath("$r_folder", 0, 0777);

    find(\&copy_result_files,"$test_suite_r_path");
  }
  print "Done\n\n";
}

if (defined($opt_stress_init_file))
{
  print <<EOF;
#############################################################
                  INITIALIZATION STAGE
#############################################################
EOF

  #Set limits for stress db initialization
  %limits=(loop_count => 1, test_count => undef);

  #Read list of tests from $opt_stress_init_file
  read_tests_names($tests_files{initdb});
  test_loop($client_ip, 0, 'seq', $tests_files{initdb});
  #print Dumper($tests_files{initdb}),"\n";
  print <<EOF;

Done initialization of stress database by tests from
$tests_files{initdb}->{filename} file.

EOF
}

if (defined($opt_stress_tests_file))
{
  print <<EOF;
#############################################################
                  STRESS TEST RUNNING STAGE
#############################################################
EOF

  $exiting=0;
  #Read list of tests from $opt_stress_tests_file
  read_tests_names($tests_files{client});

  #Reset current counter and set limits
  %test_counters=( loop_count => 0, test_count=>0);
  %limits=(loop_count => $opt_loop_count, test_count => $opt_test_count);

  if (($opt_loop_count && $opt_threads > $opt_loop_count) ||
      ($opt_test_count && $opt_threads > $opt_test_count))
  {
    warn <<EOF;

WARNING: Possible inaccuracies in number of executed loops or
         tests because number of threads bigger than number of
         loops or tests:

         Threads will be started: $opt_threads
         Loops will be executed:  $opt_loop_count
         Tests will be executed:  $opt_test_count

EOF
  }

  #Create threads (number depending on the variable )
  for ($id=1; $id<=$opt_threads && !$exiting; $id++)
  {
    $thrd[$id] = threads->create("test_loop", $client_ip, $id,
                                 $opt_stress_mode, $tests_files{client});

    print "main: Thread ID $id TID ",$thrd[$id]->tid," started\n";
    select(undef, undef, undef, 0.5);
  }

  if ($opt_test_duration)
  {
  # OBN - At this point we need to wait for the duration of the test, hoever
  #       we need to be able to quit if an 'abort-on-error' condition has happend
  #       with one of the children (WL#4685). Using solution by ES and replacing
  #       the 'sleep' command with a loop checking the abort condition every second

	foreach ( 1..$opt_test_duration ) {
		last if $exiting;
		sleep 1;
	}
    kill INT, $$;                             #Interrupt child threads
  }

  #Let other threads to process INT signal
  sleep(1);

  for ($id=1; $id<=$opt_threads;$id++)
  {
    if (defined($thrd[$id]))
    {
      $thrd[$id]->join();
    }
  }
  print "EXIT\n";
}

exit $gExitCode; # ES WL#4685: script should return a meaningful exit code

sub test_init
{
  my ($env)=@_;

  $env->{session_id}=$env->{ip}."_".$env->{thread_id};
  $env->{r_folder}='r'.$env->{thread_id};
  $env->{screen_logs}=File::Spec->catdir($opt_server_logs_dir, $test_dirname,
                                         "screen_logs", $env->{session_id});
  $env->{reject_logs}=File::Spec->catdir($opt_server_logs_dir, $test_dirname,
                                         "reject_logs", $env->{session_id});

  mkpath($env->{screen_logs}, 0, 0755) unless (-d $env->{screen_logs});
  mkpath($env->{reject_logs}, 0, 0755) unless (-d $env->{reject_logs});

  $env->{session_log}= File::Spec->catfile($env->{screen_logs}, $env->{session_id}.".log");
}

sub test_execute
{
  my $env= shift;
  my $test_name= shift;

  my $g_start= "";
  my $g_end= "";
  my $mysqltest_cmd= "";
  my @mysqltest_test_args=();
  my @stderr=();

  #Get time stamp
  $g_start = get_timestamp();
  $env->{errors}={};
  @{$env->{test_status}}=();

  my $test_file= $test_name.".test";
  my $result_file= $test_name.".result";
  my $reject_file = $test_name.'.reject';
  my $output_file = $env->{session_id}.'_'.$test_name.'_'.$g_start."_".$env->{test_count}.'.txt';

  my $test_filename = File::Spec->catfile($test_t_path, $test_file);
  my $result_filename = File::Spec->catdir($test_r_path, $env->{r_folder}, $result_file);
  my $reject_filename = File::Spec->catdir($test_r_path, $env->{r_folder}, $reject_file);
  my $output_filename = File::Spec->catfile($env->{screen_logs}, $output_file);

  push @mysqltest_test_args, "--basedir=$opt_stress_suite_basedir/",
                             "--tmpdir=$opt_stress_basedir",
                             "-x $test_filename",
                             "-R $result_filename",
                             "2>$output_filename";

  $cmd= "$opt_mysqltest --no-defaults ".join(" ", @mysqltest_args)." ".
                                        join(" ", @mysqltest_test_args);

  system($cmd);

  $exit_value  = $? >> 8;
  $signal_num  = $? & 127;
  $dumped_core = $? & 128;

  my $tid= threads->self->tid;

  if (-s $output_filename > 0)
  {
    #Read stderr for further analysis
    open (STDERR_LOG, $output_filename) or
                             warn "Can't open file $output_filename";
    @stderr=<STDERR_LOG>;
    close(STDERR_LOG);

    if ($opt_verbose)
    {
      $session_debug_file="$opt_stress_basedir/error$tid.txt";

      stress_log($session_debug_file,
                "Something wrong happened during execution of this command line:");
      stress_log($session_debug_file, "MYSQLTEST CMD - $cmd");
      stress_log($session_debug_file, "STDERR:".join("",@stderr));

      stress_log($session_debug_file, "EXIT STATUS:\n1. EXIT: $exit_value \n".
                                      "2. SIGNAL: $signal_num\n".
                                      "3. CORE: $dumped_core\n");
    }
  }

  #If something wrong trying to analyse stderr
  if ($exit_value || $signal_num)
  {
    if (@stderr)
    {
      foreach my $line (@stderr)
      {
        #FIXME: we should handle case when for one sub-string/code
        #       we have several different error messages
        #       Now for both codes/substrings we assume that
        #       first found message will represent error

        #Check line for error codes
        if (($err_msg, $err_code)= $line=~/failed: ((\d+):.+?$)/)
        {
          if (!exists($error_codes{$err_code}))
          {
            # OBN Changing severity level to S4 from S3 as S3 now reserved
            #     for the case where the error is unknown (for WL#4626/4685
            $severity="S4";
            $err_code=0;
          }
          else
          {
            $severity=$error_codes{$err_code};
          }

          if (!exists($env->{errors}->{$severity}->{$err_code}))
          {
            $env->{errors}->{$severity}->{$err_code}=[0, $err_msg];
          }
          $env->{errors}->{$severity}->{$err_code}->[0]++;
          $env->{errors}->{$severity}->{total}++;
        }

        #Check line for error patterns
        foreach $err_string (keys %error_strings)
        {
          $pattern= quotemeta $err_string;
          if ($line =~ /$pattern/i)
          {
            my $severity= $error_strings{$err_string};
            if (!exists($env->{errors}->{$severity}->{$err_string}))
            {
              $env->{errors}->{$severity}->{$err_string}=[0, $line];
            }
            $env->{errors}->{$severity}->{$err_string}->[0]++;
            $env->{errors}->{$severity}->{total}++;
          }
        }
      }
    }
    else
    {
      $env->{errors}->{S3}->{'Unknown error'}=
                              [1,"Unknown error. Nothing was output to STDERR"];
      $env->{errors}->{S3}->{total}=1;
    }
  }

  #
  #FIXME: Here we can perform further analysis of recognized
  #       error codes
  #

  foreach my $severity (sort {$a cmp $b} keys %{$env->{errors}})
  {
    my $total=$env->{errors}->{$severity}->{total};
    if ($total)
    {
      push @{$env->{test_status}}, "Severity $severity: $total";
      $env->{errors}->{total}=+$total;
      set_exit_code($severity);
    }
  }

  #FIXME: Should we take into account $exit_value here?
  #       Now we assume that all stringified errors(i.e. errors without
  #       error codes) which are not exist in %error_string structure
  #       are OK
  if (!$env->{errors}->{total})
  {
    push @{$env->{test_status}},"No Errors. Test Passed OK";
  }

  log_session_errors($env, $test_file);

  #OBN Removing the case of S1 and abort-on-error as that is now set
  #     inside the set_exit_code function (for WL#4626/4685)
  #if (!$exiting && ($signal_num == 2 || $signal_num == 15 ||
  #       ($opt_abort_on_error && $env->{errors}->{S1} > 0)))
  if (!$exiting && ($signal_num == 2 || $signal_num == 15))
  {
    #mysqltest was interrupted with INT or TERM signals
    #so we assume that we should cancel testing and exit
    $exiting=1;
    # OBN - Adjusted text to exclude case of S1 and abort-on-error that
    #       was mentioned (for WL#4626/4685)
    print STDERR<<EOF;
WARNING:
   mysqltest was interrupted with INT or TERM signals  so we assume that
   we should cancel testing and exit. Please check log file for this thread
   in $stress_log_file or
   inspect below output of the last test case executed with mysqltest to
   find out cause of error.

   Output of mysqltest:
   @stderr

EOF
  }

  if (-e $reject_filename)
  {
    move_to_logs($env->{reject_logs}, $reject_filename, $reject_file);
  }

  if (-e $output_filename)
  {
    move_to_logs($env->{screen_logs}, $output_filename, $output_file);
  }

}

sub test_loop
{
  my %client_env=();
  my $test_name="";

  # KEY for session identification: IP-THREAD_ID
  $client_env{ip} = shift;
  $client_env{thread_id} = shift;

  $client_env{mode} = shift;
  $client_env{tests_file}=shift;

  $client_env{test_seq_idx}=0;

  #Initialize session variables
  test_init(\%client_env);

LOOP:

  while(!$exiting)
  {
    if ($opt_check_tests_file)
    {
      #Check if tests_file was modified and reread it in this case
      read_tests_names($client_env{tests_file}, 0);
    }

    {
      lock($test_counters_lock);

      if (($limits{loop_count} && $limits{loop_count} <= $test_counters{loop_count}*1) ||
          ($limits{test_count} && $limits{test_count} <= $test_counters{test_count}*1) )
      {
        $exiting=1;
        next LOOP;
      }
    }

    #Get random file name
    if (($test_name = get_test(\%client_env)) ne '')
    {
      {
        lock($test_counters_lock);

        #Save current counters values
        $client_env{loop_count}=$test_counters{loop_count};
        $client_env{test_count}=$test_counters{test_count};
      }
      #Run test and analyze results
      test_execute(\%client_env, $test_name);

      print "test_loop[".$limits{loop_count}.":".
             $limits{test_count}." ".
             $client_env{loop_count}.":".
             $client_env{test_count}."]:".
             " TID ".$client_env{thread_id}.
             " test: '$test_name' ".
             " Errors: ".join(" ",@{$client_env{test_status}}).
                ( $exiting ? " (thread aborting)" : "" )."\n";
    }

    # OBN - At this point we need to wait until the 'wait' time between test
    #       executions passes (in case it is specifed) passes, hoever we need
    #       to be able to quit and break out of the test if an 'abort-on-error'
    #       condition has happend with one of the other children (WL#4685).
    #       Using solution by ES and replacing the 'sleep' command with a loop
    #       checking the abort condition every second

	if ( $opt_sleep_time ) {
		foreach ( 1..$opt_sleep_time ) {
			last if $exiting;
			sleep 1;
		}
	}
  }
}

sub move_to_logs ($$$)
{
  my $path_to_logs = shift;
  my $src_file = shift;
  my $random_filename = shift;

  my $dst_file = File::Spec->catfile($path_to_logs, $random_filename);

  move ($src_file, $dst_file) or warn<<EOF;
ERROR: move_to_logs: File $src_file cannot be moved to $dst_file: $!
EOF
}

sub copy_test_files ()
{
  if (/\.test$/)
  {
    $src_file = $File::Find::name;
    #print "## $File::Find::topdir - $File::Find::dir - $src_file\n";

    if ($File::Find::topdir eq $File::Find::dir && $src_file !~ /SCCS/)
    {
      $test_filename = basename($src_file);
      $dst_file = File::Spec->catfile($test_t_path, $test_filename);

      copy($src_file, $dst_file) or die "ERROR: copy_test_files: File cannot be copied. $!";
    }
  }
}

sub copy_result_files ()
{
  if (/\.result$/)
  {
    $src_file = $File::Find::name;

    if ($File::Find::topdir eq $File::Find::dir && $src_file !~ /SCCS/)
    {
      $result_filename = basename($src_file) ;
      $dst_file = File::Spec->catfile($r_folder, $result_filename);

      copy($src_file, $dst_file) or die "ERROR: copy_result_files: File cannot be copied. $!";
    }
  }
}

sub get_timestamp
{
  my ($sec,$min,$hour,$mday,$mon,$year,$wday,$ydat,$isdst) = localtime();

  return sprintf("%04d%02d%02d%02d%02d%02d", $year+1900, $mon+1, $mday, $hour, $min, $sec);
}

sub read_tests_names
{
  my $tests_file = shift;
  my $force_load = shift;

  if ($force_load || ( (stat($tests_file->{filename}))[9] != $tests_file->{mtime}) )
  {
    open (TEST, $tests_file->{filename}) || die ("Could not open file <".
                                                  $tests_file->{filename}."> $!");
    @{$tests_file->{data}}= grep {!/^[#\r\n]|^$/} map { s/[\r\n]//g; $_ } <TEST>;

    close (TEST);
    $tests_file->{mtime}=(stat(_))[9];
  }
}

sub get_random_test
{
  my $envt=shift;
  my $tests= $envt->{tests_file}->{data};

  my $random = int(rand(@{$tests}));
  my $test = $tests->[$random];

  return $test;
}

sub get_next_test
{
  my $envt=shift;
  my $test;

  if (@{$envt->{tests_file}->{data}})
  {
    $test=${$envt->{tests_file}->{data}}[$envt->{test_seq_idx}];
    $envt->{test_seq_idx}++;
  }

  #If we reach bound of array, reset seq index and increment loop counter
  if ($envt->{test_seq_idx} == scalar(@{$envt->{tests_file}->{data}}))
  {
    $envt->{test_seq_idx}=0;
    {
      lock($test_counters_lock);
      $test_counters{loop_count}++;
    }
  }

  return $test;
}

sub get_test
{
   my $envt=shift;

   {
     lock($test_counters_lock);
     $test_counters{test_count}++;
   }

   if ($envt->{mode} eq 'seq')
   {
     return get_next_test($envt);
   }
   elsif ($envt->{mode} eq 'random')
   {
     return get_random_test($envt);
   }
}

sub stress_log
{
  my ($log_file, $line)=@_;

  {
    open(SLOG,">>$log_file") or warn "Error during opening log file $log_file";
    print SLOG $line,"\n";
    close(SLOG);
  }
}

sub log_session_errors
{
  my ($env, $test_name) = @_;
  my $line='';

  {
    lock ($log_file_lock);

    #header in the begining of log file
    if (!-e $stress_log_file)
    {
      stress_log($stress_log_file,
                   "TestID TID      Suite         TestFileName Found Errors");
      stress_log($stress_log_file,
                   "=======================================================");
    }

    $line=sprintf('%6d %3d %10s %20s %s', $env->{test_count}, threads->self->tid,
                                          $opt_suite, $test_name,
                                          join(",", @{$env->{test_status}}));

    stress_log($stress_log_file, $line);
    #stress_log_with_lock($stress_log_file, "\n");

    if ($opt_log_error_details)
    {
      foreach $severity (sort {$a cmp $b} keys %{$env->{errors}})
      {
        stress_log($stress_log_file, "");
        foreach $error (keys %{$env->{errors}->{$severity}})
        {
          if ($error ne 'total')
          {
            stress_log($stress_log_file, "$severity: Count:".
                      $env->{errors}->{$severity}->{$error}->[0].
                      " Error:". $env->{errors}->{$severity}->{$error}->[1]);
          }
        }
      }
    }
  }
}

sub sig_INT_handler
{
  $SIG{INT}= \&sig_INT_handler;
  $exiting=1;
  print STDERR "$$: Got INT signal-------------------------------------------\n";

}

sub sig_TERM_handler
{
  $SIG{TERM}= \&sig_TERM_handler;
  $exiting=1;
  print STDERR "$$: Got TERM signal\n";
}

sub usage
{
  my $retcode= shift;
  print <<EOF;

The MySQL Stress suite Ver $stress_suite_version

mysql-stress-test.pl --stress-basedir=<dir> --stress-suite-basedir=<dir> --server-logs-dir=<dir>

--server-host
--server-port
--server-socket
--server-user
--server-password
--server-logs-dir
  Directory where all clients session logs will be stored. Usually
  this is shared directory associated with server that used
  in testing

  Required option.

--stress-suite-basedir=<dir>
  Directory that has r/ t/ subfolders with test/result files
  which will be used for testing. Also by default we are looking
  in this directory for 'stress-tests.txt' file which contains
  list of tests.  It is possible to specify other location of this
  file with --stress-tests-file option.

  Required option.

--stress-basedir=<dir>
  Working directory for this test run. This directory will be used
  as temporary location for results tracking during testing

  Required option.

--stress-datadir=<dir>
  Location of data files used which will be used in testing.
  By default we search for these files in <dir>/data where dir
  is value of --stress-suite-basedir option.

--stress-init-file[=/path/to/file with tests for initialization of stress db]
  Using of this option allows to perform initialization of database
  by execution of test files. List of tests will be taken either from
  specified file or if it omited from default file 'stress-init.txt'
  located in <--stress-suite-basedir/--suite> dir

--stress-tests-file[=/path/to/file with tests]
  Using of this option allows to run stress test itself. Tests for testing
  will be taken either from specified file or if it omited from default
  file 'stress-tests.txt' located in <--stress-suite-basedir/--suite> dir

--stress-mode= [random|seq]
  There are two possible modes which affect order of selecting tests
  from the list:
    - in random mode tests will be selected in random order
    - in seq mode each thread will execute tests in the loop one by one as
      they specified in the list file.

--sleep-time=<time in seconds>
  Delay between test execution. Could be usefull in continued testsing
  when one of instance of stress script perform periodical cleanup or
  recreating of some database objects

--threads=#number of threads
  Define number of threads

--check-tests-file
  Check file with list of tests. If file was modified it will force to
  reread list of tests. Could be usefull in continued testing for
  adding/removing tests without script interruption

--mysqltest=/path/to/mysqltest binary

--verbose

--cleanup
  Force to clean up working directory (specified with --stress-basedir)

--abort-on-error=<number>
  Causes the script to abort if an error with severity <= number was encounterd

--log-error-details
  Enable errors details in the global error log file. (Default: off)

--test-count=<number of executed tests before we have to exit>
--loop-count=<number of executed loops in sequential mode before we have to exit>
--test-duration=<number of seconds that stress test should run>

Example of tool usage:

perl mysql-stress-test.pl \
--stress-suite-basedir=/opt/qa/mysql-test-extra-5.0/mysql-test \
--stress-basedir=/opt/qa/test \
--server-logs-dir=/opt/qa/logs \
--test-count=20  \
--stress-tests-file=innodb-tests.txt \
--stress-init-file=innodb-init.txt \
--threads=5 \
--suite=funcs_1  \
--mysqltest=/opt/mysql/mysql-5.0/client/mysqltest \
--server-user=root \
--server-database=test \
--cleanup \

EOF
exit($retcode);
}