mysql-test-run.pl 185 KB
Newer Older
1 2 3
#!/usr/bin/perl
# -*- cperl -*-

4
# Copyright (c) 2004, 2014, Oracle and/or its affiliates.
5
# Copyright (c) 2009, 2018, MariaDB Corporation
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
#
# 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

#
##############################################################################
#
#  mysql-test-run.pl
#
#  Tool used for executing a suite of .test files
#
#  See the "MySQL Test framework manual" for more information
28
#  https://mariadb.com/kb/en/library/mysqltest/
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
#
#
##############################################################################

use strict;
use warnings;

BEGIN {
  # Check that mysql-test-run.pl is started from mysql-test/
  unless ( -f "mysql-test-run.pl" )
  {
    print "**** ERROR **** ",
      "You must start mysql-test-run from the mysql-test/ directory\n";
    exit(1);
  }
  # Check that lib exist
  unless ( -d "lib/" )
  {
    print "**** ERROR **** ",
      "Could not find the lib/ directory \n";
    exit(1);
  }
}

BEGIN {
  # Check backward compatibility support
  # By setting the environment variable MTR_VERSION
  # it's possible to use a previous version of
  # mysql-test-run.pl
  my $version= $ENV{MTR_VERSION} || 2;
  if ( $version == 1 )
  {
    print "=======================================================\n";
    print "  WARNING: Using mysql-test-run.pl version 1!  \n";
    print "=======================================================\n";
    # Should use exec() here on *nix but this appears not to work on Windows
    exit(system($^X, "lib/v1/mysql-test-run.pl", @ARGV) >> 8);
  }
  elsif ( $version == 2 )
  {
    # This is the current version, just continue
    ;
  }
  else
  {
    print "ERROR: Version $version of mysql-test-run does not exist!\n";
    exit(1);
  }
}

use lib "lib";

use Cwd ;
use Cwd 'realpath';
use Getopt::Long;
use My::File::Path; # Patched version of File::Path
use File::Basename;
use File::Copy;
use File::Find;
use File::Temp qw/tempdir/;
use File::Spec::Functions qw/splitdir rel2abs/;
use My::Platform;
use My::SafeProcess;
use My::ConfigFactory;
use My::Options;
94
use My::Tee;
95 96 97 98 99 100 101 102 103 104 105
use My::Find;
use My::SysInfo;
use My::CoreDump;
use mtr_cases;
use mtr_report;
use mtr_match;
use mtr_unique;
use mtr_results;
use IO::Socket::INET;
use IO::Select;

106 107 108 109
require "mtr_process.pl";
require "mtr_io.pl";
require "mtr_gprof.pl";
require "mtr_misc.pl";
110 111

$SIG{INT}= sub { mtr_error("Got ^C signal"); };
112
$SIG{HUP}= sub { mtr_error("Hangup detected on controlling terminal"); };
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138

our $mysql_version_id;
my $mysql_version_extra;
our $glob_mysql_test_dir;
our $basedir;
our $bindir;

our $path_charsetsdir;
our $path_client_bindir;
our $path_client_libdir;
our $path_language;

our $path_current_testlog;
our $path_testlog;

our $default_vardir;
our $opt_vardir;                # Path to use for var/ dir
our $plugindir;
my $path_vardir_trace;          # unix formatted opt_vardir for trace files
my $opt_tmpdir;                 # Path to use for tmp/ dir
my $opt_tmpdir_pid;

my $opt_start;
my $opt_start_dirty;
my $opt_start_exit;
my $start_only;
139 140 141
my $file_wsrep_provider;

our @global_suppressions;
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172

END {
  if ( defined $opt_tmpdir_pid and $opt_tmpdir_pid == $$ )
  {
    if (!$opt_start_exit)
    {
      # Remove the tempdir this process has created
      mtr_verbose("Removing tmpdir $opt_tmpdir");
      rmtree($opt_tmpdir);
    }
    else
    {
      mtr_warning("tmpdir $opt_tmpdir should be removed after the server has finished");
    }
  }
}

sub env_or_val($$) { defined $ENV{$_[0]} ? $ENV{$_[0]} : $_[1] }

my $path_config_file;           # The generated config file, var/my.cnf

# Visual Studio produces executables in different sub-directories based on the
# configuration used to build them.  To make life easier, an environment
# variable or command-line option may be specified to control which set of
# executables will be used by the test suite.
our $opt_vs_config = $ENV{'MTR_VS_CONFIG'};

my @DEFAULT_SUITES= qw(
    main-
    archive-
    binlog-
173
    binlog_encryption-
174
    csv-
175
    compat/oracle-
176
    encryption-
177 178 179
    federated-
    funcs_1-
    funcs_2-
180
    gcol-
181 182 183 184
    handler-
    heap-
    innodb-
    innodb_fts-
185
    innodb_gis-
186
    innodb_zip-
187
    json-
188
    maria-
189
    mariabackup-
190 191 192 193 194 195 196 197
    multi_source-
    optimizer_unfixed_bugs-
    parts-
    perfschema-
    plugins-
    roles-
    rpl-
    sys_vars-
198
    sql_sequence-
199 200
    unit-
    vcol-
201
    versioning-
202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
  );
my $opt_suites;

our $opt_verbose= 0;  # Verbose output, enable with --verbose
our $exe_patch;
our $exe_mysql;
our $exe_mysql_plugin;
our $exe_mysqladmin;
our $exe_mysqltest;
our $exe_libtool;
our $exe_mysql_embedded;

our $opt_big_test= 0;
our $opt_staging_run= 0;

our @opt_combinations;

our @opt_extra_mysqld_opt;
our @opt_mysqld_envs;

my $opt_stress;
223
my $opt_tail_lines= 20;
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268

my $opt_dry_run;

my $opt_compress;
my $opt_ssl;
my $opt_skip_ssl;
my @opt_skip_test_list;
our $opt_ssl_supported;
my $opt_ps_protocol;
my $opt_sp_protocol;
my $opt_cursor_protocol;
my $opt_view_protocol;
my $opt_non_blocking_api;

our $opt_debug;
my $debug_d= "d,*";
my $opt_debug_common;
our $opt_debug_server;
our @opt_cases;                  # The test cases names in argv
our $opt_embedded_server;

# Options used when connecting to an already running server
my %opts_extern;
sub using_extern { return (keys %opts_extern > 0);};

our $opt_fast= 0;
our $opt_force= 0;
our $opt_mem= $ENV{'MTR_MEM'};
our $opt_clean_vardir= $ENV{'MTR_CLEAN_VARDIR'};

our $opt_gcov;
our $opt_gprof;
our %gprof_dirs;

our $glob_debugger= 0;
our $opt_gdb;
our $opt_client_gdb;
my $opt_boot_gdb;
our $opt_dbx;
our $opt_client_dbx;
my $opt_boot_dbx;
our $opt_ddd;
our $opt_client_ddd;
my $opt_boot_ddd;
our $opt_manual_gdb;
269
our $opt_manual_lldb;
270 271 272 273 274 275 276 277 278 279 280 281
our $opt_manual_dbx;
our $opt_manual_ddd;
our $opt_manual_debug;
our $opt_debugger;
our $opt_client_debugger;

my $config; # The currently running config
my $current_config_name; # The currently running config file template

our @opt_experimentals;
our $experimental_test_cases= [];

282
our $baseport;
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331
# $opt_build_thread may later be set from $opt_port_base
my $opt_build_thread= $ENV{'MTR_BUILD_THREAD'} || "auto";
my $opt_port_base= $ENV{'MTR_PORT_BASE'} || "auto";
my $build_thread= 0;

my $opt_record;

our $opt_resfile= $ENV{'MTR_RESULT_FILE'} || 0;

my $opt_skip_core;

our $opt_check_testcases= 1;
my $opt_mark_progress;
my $opt_max_connections;
our $opt_report_times= 0;

my $opt_sleep;

my $opt_testcase_timeout= $ENV{MTR_TESTCASE_TIMEOUT} ||  15; # minutes
my $opt_suite_timeout   = $ENV{MTR_SUITE_TIMEOUT}    || 360; # minutes
my $opt_shutdown_timeout= $ENV{MTR_SHUTDOWN_TIMEOUT} ||  10; # seconds
my $opt_start_timeout   = $ENV{MTR_START_TIMEOUT}    || 180; # seconds

sub suite_timeout { return $opt_suite_timeout * 60; };

my $opt_wait_all;
my $opt_user_args;
my $opt_repeat= 1;
my $opt_retry= 1;
my $opt_retry_failure= env_or_val(MTR_RETRY_FAILURE => 2);
my $opt_reorder= 1;
my $opt_force_restart= 0;

our $opt_user = "root";

our $opt_valgrind= 0;
my $opt_valgrind_mysqld= 0;
my $opt_valgrind_mysqltest= 0;
my @valgrind_args;
my $opt_strace= 0;
my $opt_strace_client;
my @strace_args;
my $opt_valgrind_path;
my $valgrind_reports= 0;
my $opt_callgrind;
my %mysqld_logs;
my $opt_debug_sync_timeout= 300; # Default timeout for WAIT_FOR actions.
my $warn_seconds = 60;

332 333
my $rebootstrap_re= '--innodb[-_](?:page[-_]size|checksum[-_]algorithm|undo[-_]tablespaces|log[-_]group[-_]home[-_]dir|data[-_]home[-_]dir)|data[-_]file[-_]path|force_rebootstrap';

334 335 336 337 338 339 340 341 342 343 344
sub testcase_timeout ($) {
  my ($tinfo)= @_;
  if (exists $tinfo->{'case-timeout'}) {
    # Return test specific timeout if *longer* that the general timeout
    my $test_to= $tinfo->{'case-timeout'};
    $test_to*= 10 if $opt_valgrind;
    return $test_to * 60 if $test_to > $opt_testcase_timeout;
  }
  return $opt_testcase_timeout * 60;
}

345
sub check_timeout ($) { return testcase_timeout($_[0]); }
346 347 348 349 350 351 352 353 354 355 356

our $opt_warnings= 1;

our %mysqld_variables;
our @optional_plugins;

my $source_dist=  -d "../sql";

my $opt_max_save_core= env_or_val(MTR_MAX_SAVE_CORE => 5);
my $opt_max_save_datadir= env_or_val(MTR_MAX_SAVE_DATADIR => 20);
my $opt_max_test_fail= env_or_val(MTR_MAX_TEST_FAIL => 10);
357
my $opt_core_on_failure= 0;
358 359

my $opt_parallel= $ENV{MTR_PARALLEL} || 1;
360
my $opt_port_group_size = $ENV{MTR_PORT_GROUP_SIZE} || 20;
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390

# lock file to stop tests
my $opt_stop_file= $ENV{MTR_STOP_FILE};
# print messages when test suite is stopped (for buildbot)
my $opt_stop_keep_alive= $ENV{MTR_STOP_KEEP_ALIVE};

select(STDOUT);
$| = 1; # Automatically flush STDOUT

main();


sub main {
  # Default, verbosity on
  report_option('verbose', 0);

  # This is needed for test log evaluation in "gen-build-status-page"
  # in all cases where the calling tool does not log the commands
  # directly before it executes them, like "make test-force-pl" in RPM builds.
  mtr_report("Logging: $0 ", join(" ", @ARGV));

  command_line_setup();

  # --help will not reach here, so now it's safe to assume we have binaries
  My::SafeProcess::find_bin();

  print "vardir: $opt_vardir\n";
  initialize_servers();
  init_timers();

391 392 393 394 395
  unless (IS_WINDOWS) {
    binmode(STDOUT,":via(My::Tee)") or die "binmode(STDOUT, :via(My::Tee)):$!";
    binmode(STDERR,":via(My::Tee)") or die "binmode(STDERR, :via(My::Tee)):$!";
  }

396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
  mtr_report("Checking supported features...");

  executable_setup();

  # --debug[-common] implies we run debug server
  $opt_debug_server= 1 if $opt_debug || $opt_debug_common;

  if (using_extern())
  {
    # Connect to the running mysqld and find out what it supports
    collect_mysqld_features_from_running_server();
  }
  else
  {
    # Run the mysqld to find out what features are available
    collect_mysqld_features();
  }
  check_ssl_support();
  check_debug_support();

  if (!$opt_suites) {
    $opt_suites= join ',', collect_default_suites(@DEFAULT_SUITES);
  }
  mtr_report("Using suites: $opt_suites") unless @opt_cases;

  mtr_report("Collecting tests...");
  my $tests= collect_test_cases($opt_reorder, $opt_suites, \@opt_cases, \@opt_skip_test_list);
  mark_time_used('collect');

  mysql_install_db(default_mysqld(), "$opt_vardir/install.db") unless using_extern();

  if ($opt_dry_run)
  {
    for (@$tests) {
      print $_->fullname(), "\n";
    }
    exit 0;
  }

435 436 437 438
  if ($opt_gcov) {
    system './dgcov.pl --purge';
  }
  
439 440 441 442
  #######################################################################
  my $num_tests= @$tests;
  if ( $opt_parallel eq "auto" ) {
    # Try to find a suitable value for number of workers
443 444 445 446 447 448 449 450 451 452 453
    if (IS_WINDOWS)
    {
      $opt_parallel= $ENV{NUMBER_OF_PROCESSORS} || 1;
    }
    else
    {
      my $sys_info= My::SysInfo->new();
      $opt_parallel= $sys_info->num_cpus();
      for my $limit (2000, 1500, 1000, 500){
        $opt_parallel-- if ($sys_info->min_bogomips() < $limit);
      }
454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520
    }
    my $max_par= $ENV{MTR_MAX_PARALLEL} || 8;
    $opt_parallel= $max_par if ($opt_parallel > $max_par);
    $opt_parallel= $num_tests if ($opt_parallel > $num_tests);
    $opt_parallel= 1 if ($opt_parallel < 1);
    mtr_report("Using parallel: $opt_parallel");
  }
  $ENV{MTR_PARALLEL} = $opt_parallel;

  if ($opt_parallel > 1 && ($opt_start_exit || $opt_stress)) {
    mtr_warning("Parallel cannot be used with --start-and-exit or --stress\n" .
               "Setting parallel to 1");
    $opt_parallel= 1;
  }

  # Create server socket on any free port
  my $server = new IO::Socket::INET
    (
     LocalAddr => 'localhost',
     Proto => 'tcp',
     Listen => $opt_parallel,
    );
  mtr_error("Could not create testcase server port: $!") unless $server;
  my $server_port = $server->sockport();

  if ($opt_resfile) {
    resfile_init("$opt_vardir/mtr-results.txt");
    print_global_resfile();
  }

  # Create child processes
  my %children;
  for my $child_num (1..$opt_parallel){
    my $child_pid= My::SafeProcess::Base::_safe_fork();
    if ($child_pid == 0){
      $server= undef; # Close the server port in child
      $tests= {}; # Don't need the tests list in child

      # Use subdir of var and tmp unless only one worker
      if ($opt_parallel > 1) {
	set_vardir("$opt_vardir/$child_num");
	$opt_tmpdir= "$opt_tmpdir/$child_num";
      }

      init_timers();
      run_worker($server_port, $child_num);
      exit(1);
    }

    $children{$child_pid}= 1;
  }
  #######################################################################

  mtr_report();
  mtr_print_thick_line();
  mtr_print_header($opt_parallel > 1);

  mark_time_used('init');

  my ($prefix, $fail, $completed, $extra_warnings)=
    run_test_server($server, $tests, $opt_parallel);

  exit(0) if $opt_start_exit;

  # Send Ctrl-C to any children still running
  kill("INT", keys(%children));

521 522 523 524 525 526 527 528 529 530 531
  if (!IS_WINDOWS) { 
    # Wait for children to exit
    foreach my $pid (keys %children)
    {
      my $ret_pid= waitpid($pid, 0);
      if ($ret_pid != $pid){
        mtr_report("Unknown process $ret_pid exited");
      }
      else {
        delete $children{$ret_pid};
      }
532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571
    }
  }

  if ( not @$completed ) {
    mtr_error("Test suite aborted");
  }

  if ( @$completed != $num_tests){

    # Not all tests completed, failure
    mtr_report();
    mtr_report("Only ", int(@$completed), " of $num_tests completed.");
  }

  if ($opt_valgrind) {
    # Create minimalistic "test" for the reporting
    my $tinfo = My::Test->new
      (
       name           => 'valgrind_report',
      );
    # Set dummy worker id to align report with normal tests
    $tinfo->{worker} = 0 if $opt_parallel > 1;
    if ($valgrind_reports) {
      $tinfo->{result}= 'MTR_RES_FAILED';
      $tinfo->{comment}= "Valgrind reported failures at shutdown, see above";
      $tinfo->{failures}= 1;
    } else {
      $tinfo->{result}= 'MTR_RES_PASSED';
    }
    mtr_report_test($tinfo);
    push @$completed, $tinfo;
    ++$num_tests
  }

  mtr_print_line();

  print_total_times($opt_parallel) if $opt_report_times;

  mtr_report_stats($prefix, $fail, $completed, $extra_warnings);

572 573 574 575 576
  if ($opt_gcov) {
    mtr_report("Running dgcov");
    system "./dgcov.pl --generate > $opt_vardir/last_changes.dgcov";
  }

577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653
  if ( @$completed != $num_tests)
  {
    mtr_error("Not all tests completed (only ". scalar(@$completed) .
              " of $num_tests)");
  }

  remove_vardir_subs() if $opt_clean_vardir;

  exit(0);
}


sub run_test_server ($$$) {
  my ($server, $tests, $childs) = @_;

  my $num_saved_cores= 0;  # Number of core files saved in vardir/log/ so far.
  my $num_saved_datadir= 0;  # Number of datadirs saved in vardir/log/ so far.
  my $num_failed_test= 0; # Number of tests failed so far
  my $test_failure= 0;    # Set true if test suite failed
  my $extra_warnings= []; # Warnings found during server shutdowns

  my $completed= [];
  my %running;
  my $result;
  my $exe_mysqld= find_mysqld($bindir) || ""; # Used as hint to CoreDump

  my $suite_timeout= start_timer(suite_timeout());

  my $s= IO::Select->new();
  $s->add($server);
  while (1) {
    if ($opt_stop_file)
    {
      if (mtr_wait_lock_file($opt_stop_file, $opt_stop_keep_alive))
      {
        # We were waiting so restart timer process
        my $suite_timeout= start_timer(suite_timeout());
      }
    }

    mark_time_used('admin');
    my @ready = $s->can_read(1); # Wake up once every second
    mark_time_idle();
    foreach my $sock (@ready) {
      if ($sock == $server) {
	# New client connected
	my $child= $sock->accept();
	mtr_verbose("Client connected");
	$s->add($child);
	print $child "HELLO\n";
      }
      else {
	my $line= <$sock>;
	if (!defined $line) {
	  # Client disconnected
	  mtr_verbose("Child closed socket");
	  $s->remove($sock);
	  if (--$childs == 0){
	    return ("Completed", $test_failure, $completed, $extra_warnings);
	  }
	  next;
	}
	chomp($line);

	if ($line eq 'TESTRESULT'){
	  $result= My::Test::read_test($sock);

	  # Report test status
	  mtr_report_test($result);

	  if ( $result->is_failed() ) {

	    # Save the workers "savedir" in var/log
	    my $worker_savedir= $result->{savedir};
	    my $worker_savename= basename($worker_savedir);
	    my $savedir= "$opt_vardir/log/$worker_savename";

654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696
            # Move any core files from e.g. mysqltest
            foreach my $coref (glob("core*"), glob("*.dmp"))
            {
              mtr_report(" - found '$coref', moving it to '$worker_savedir'");
              move($coref, $worker_savedir);
            }

            find(
            {
              no_chdir => 1,
              wanted => sub
              {
                my $core_file= $File::Find::name;
                my $core_name= basename($core_file);

                # Name beginning with core, not ending in .gz
                if (($core_name =~ /^core/ and $core_name !~ /\.gz$/)
                    or (IS_WINDOWS and $core_name =~ /\.dmp$/))
                {
                  # Ending with .dmp
                  mtr_report(" - found '$core_name'",
                             "($num_saved_cores/$opt_max_save_core)");

                  My::CoreDump->show($core_file, $exe_mysqld, $opt_parallel);

                  # Limit number of core files saved
                  if ($opt_max_save_core > 0 &&
                      $num_saved_cores >= $opt_max_save_core)
                  {
                    mtr_report(" - deleting it, already saved",
                               "$opt_max_save_core");
                    unlink("$core_file");
                  }
                  else
                  {
                    mtr_compress_file($core_file) unless @opt_cases;
                    ++$num_saved_cores;
                  }
                }
              }
            },
            $worker_savedir);

697 698 699 700 701 702
	    if ($opt_max_save_datadir > 0 &&
		$num_saved_datadir >= $opt_max_save_datadir)
	    {
	      mtr_report(" - skipping '$worker_savedir/'");
	      rmtree($worker_savedir);
	    }
703 704
            else
            {
705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763
	      mtr_report(" - saving '$worker_savedir/' to '$savedir/'");
	      rename($worker_savedir, $savedir);
	    }
	    resfile_print_test();
	    $num_saved_datadir++;
	    $num_failed_test++ unless ($result->{retries} ||
                                       $result->{exp_fail});

            $test_failure= 1;
	    if ( !$opt_force ) {
	      # Test has failed, force is off
	      push(@$completed, $result);
	      if ($result->{'dont_kill_server'})
              {
	        print $sock "BYE\n";
	        next;
              }
	      return ("Failure", 1, $completed, $extra_warnings);
	    }
	    elsif ($opt_max_test_fail > 0 and
		   $num_failed_test >= $opt_max_test_fail) {
	      push(@$completed, $result);
	      mtr_report("Too many tests($num_failed_test) failed!",
			 "Terminating...");
	      return ("Too many failed", 1, $completed, $extra_warnings);
	    }
	  }

	  resfile_print_test();
	  # Retry test run after test failure
	  my $retries= $result->{retries} || 2;
	  my $test_has_failed= $result->{failures} || 0;
	  if ($test_has_failed and $retries <= $opt_retry){
	    # Test should be run one more time unless it has failed
	    # too many times already
	    my $tname= $result->{name};
	    my $failures= $result->{failures};
	    if ($opt_retry > 1 and $failures >= $opt_retry_failure){
	      mtr_report("\nTest $tname has failed $failures times,",
			 "no more retries!\n");
	    }
	    else {
	      mtr_report("\nRetrying test $tname, ".
			 "attempt($retries/$opt_retry)...\n");
              #saving the log file as filename.failed in case of retry
              if ( $result->is_failed() ) {
                my $worker_logdir= $result->{savedir};
                my $log_file_name=dirname($worker_logdir)."/".$result->{shortname}.".log";
                rename $log_file_name,$log_file_name.".failed";
              }
	      delete($result->{result});
	      $result->{retries}= $retries+1;
	      $result->write_test($sock, 'TESTCASE');
	      next;
	    }
	  }

	  # Repeat test $opt_repeat number of times
	  my $repeat= $result->{repeat} || 1;
764
	  if ($repeat < $opt_repeat)
765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906
	  {
	    $result->{retries}= 0;
	    $result->{rep_failures}++ if $result->{failures};
	    $result->{failures}= 0;
	    delete($result->{result});
	    $result->{repeat}= $repeat+1;
	    $result->write_test($sock, 'TESTCASE');
	    next;
	  }

	  # Remove from list of running
	  mtr_error("'", $result->{name},"' is not known to be running")
	    unless delete $running{$result->key()};

	  # Save result in completed list
	  push(@$completed, $result);

	}
	elsif ($line eq 'START'){
	  ; # Send first test
	}
	elsif ($line eq 'WARNINGS'){
          my $fake_test= My::Test::read_test($sock);
          my $test_list= join (" ", @{$fake_test->{testnames}});
          push @$extra_warnings, $test_list;
          my $report= $fake_test->{'warnings'};
          mtr_report("***Warnings generated in error logs during shutdown ".
                     "after running tests: $test_list\n\n$report");
          $test_failure= 1;
          if ( !$opt_force ) {
            # Test failure due to warnings, force is off
            return ("Warnings in log", 1, $completed, $extra_warnings);
          }
        }
	elsif ($line =~ /^SPENT/) {
	  add_total_times($line);
	}
	elsif ($line eq 'VALGREP' && $opt_valgrind) {
	  $valgrind_reports= 1;
	}
	else {
	  mtr_error("Unknown response: '$line' from client");
	}

	# Find next test to schedule
	# - Try to use same configuration as worker used last time

	my $next;
	my $second_best;
	for(my $i= 0; $i <= @$tests; $i++)
	{
	  my $t= $tests->[$i];

	  last unless defined $t;

	  if (run_testcase_check_skip_test($t)){
	    # Move the test to completed list
	    #mtr_report("skip - Moving test $i to completed");
	    push(@$completed, splice(@$tests, $i, 1));

	    # Since the test at pos $i was taken away, next
	    # test will also be at $i -> redo
	    redo;
	  }

	  # From secondary choices, we prefer to pick a 'long-running' test if
          # possible; this helps avoid getting stuck with a few of those at the
          # end of high --parallel runs, with most workers being idle.
	  if (!defined $second_best ||
              ($t->{'long_test'} && !($tests->[$second_best]{'long_test'}))){
	    #mtr_report("Setting second_best to $i");
	    $second_best= $i;
	  }

	  # Smart allocation of next test within this thread.

	  if ($opt_reorder and $opt_parallel > 1 and defined $result)
	  {
	    my $wid= $result->{worker};
	    # Reserved for other thread, try next
	    next if (defined $t->{reserved} and $t->{reserved} != $wid);
	    if (! defined $t->{reserved})
	    {
	      my $criteria= $t->{criteria};
	      # Reserve similar tests for this worker, but not too many
	      my $maxres= (@$tests - $i) / $opt_parallel + 1;
	      for (my $j= $i+1; $j <= $i + $maxres; $j++)
	      {
		my $tt= $tests->[$j];
		last unless defined $tt;
		last if $tt->{criteria} ne $criteria;
		$tt->{reserved}= $wid;
	      }
	    }
	  }

	  # At this point we have found next suitable test
	  $next= splice(@$tests, $i, 1);
	  last;
	}

	# Use second best choice if no other test has been found
	if (!$next and defined $second_best){
	  #mtr_report("Take second best choice $second_best");
	  mtr_error("Internal error, second best too large($second_best)")
	    if $second_best >  $#$tests;
	  $next= splice(@$tests, $second_best, 1);
	  delete $next->{reserved};
	}

        xterm_stat(scalar(@$tests));

	if ($next) {
	  # We don't need this any more
	  delete $next->{criteria};
	  $next->write_test($sock, 'TESTCASE');
	  $running{$next->key()}= $next;
	}
	else {
	  # No more test, tell child to exit
	  #mtr_report("Saying BYE to child");
	  print $sock "BYE\n";
	}
      }
    }

    # ----------------------------------------------------
    # Check if test suite timer expired
    # ----------------------------------------------------
    if ( has_expired($suite_timeout) )
    {
      mtr_report("Test suite timeout! Terminating...");
      return ("Timeout", 1, $completed, $extra_warnings);
    }
  }
}


sub run_worker ($) {
  my ($server_port, $thread_num)= @_;

  $SIG{INT}= sub { exit(1); };
907
  $SIG{HUP}= sub { exit(1); };
908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021

  # Connect to server
  my $server = new IO::Socket::INET
    (
     PeerAddr => 'localhost',
     PeerPort => $server_port,
     Proto    => 'tcp'
    );
  mtr_error("Could not connect to server at port $server_port: $!")
    unless $server;

  # --------------------------------------------------------------------------
  # Set worker name
  # --------------------------------------------------------------------------
  report_option('name',"worker[$thread_num]");

  # --------------------------------------------------------------------------
  # Set different ports per thread
  # --------------------------------------------------------------------------
  set_build_thread_ports($thread_num);

  # --------------------------------------------------------------------------
  # Turn off verbosity in workers, unless explicitly specified
  # --------------------------------------------------------------------------
  report_option('verbose', undef) if ($opt_verbose == 0);

  environment_setup();

  # Read hello from server which it will send when shared
  # resources have been setup
  my $hello= <$server>;

  setup_vardir();
  check_running_as_root();

  if ( using_extern() ) {
    create_config_file_for_extern(%opts_extern);
  }

  # Ask server for first test
  print $server "START\n";

  mark_time_used('init');

  while (my $line= <$server>){
    chomp($line);
    if ($line eq 'TESTCASE'){
      my $test= My::Test::read_test($server);

      # Clear comment and logfile, to avoid
      # reusing them from previous test
      delete($test->{'comment'});
      delete($test->{'logfile'});

      # A sanity check. Should this happen often we need to look at it.
      if (defined $test->{reserved} && $test->{reserved} != $thread_num) {
	my $tres= $test->{reserved};
	mtr_warning("Test reserved for w$tres picked up by w$thread_num");
      }
      $test->{worker} = $thread_num if $opt_parallel > 1;

      run_testcase($test, $server);
      #$test->{result}= 'MTR_RES_PASSED';
      # Send it back, now with results set
      $test->write_test($server, 'TESTRESULT');
      mark_time_used('restart');
    }
    elsif ($line eq 'BYE'){
      mtr_report("Server said BYE");
      # We need to gracefully shut down the servers to see any
      # Valgrind memory leak errors etc. since last server restart.
      if ($opt_warnings) {
        stop_servers(reverse all_servers());
        if(check_warnings_post_shutdown($server)) {
          # Warnings appeared in log file(s) during final server shutdown.
          exit(1);
        }
      }
      else {
        stop_all_servers($opt_shutdown_timeout);
      }
      mark_time_used('restart');
      my $valgrind_reports= 0;
      if ($opt_valgrind_mysqld) {
        $valgrind_reports= valgrind_exit_reports();
	print $server "VALGREP\n" if $valgrind_reports;
      }
      if ( $opt_gprof ) {
	gprof_collect (find_mysqld($bindir), keys %gprof_dirs);
      }
      mark_time_used('admin');
      print_times_used($server, $thread_num);
      exit($valgrind_reports);
    }
    else {
      mtr_error("Could not understand server, '$line'");
    }
  }

  stop_all_servers();

  exit(1);
}


sub ignore_option {
  my ($opt, $value)= @_;
  mtr_report("Ignoring option '$opt'");
}



# Setup any paths that are $opt_vardir related
sub set_vardir {
1022
  ($opt_vardir)= @_;
1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054

  $path_vardir_trace= $opt_vardir;
  # Chop off any "c:", DBUG likes a unix path ex: c:/src/... => /src/...
  $path_vardir_trace=~ s/^\w://;

  # Location of my.cnf that all clients use
  $path_config_file= "$opt_vardir/my.cnf";

  $path_testlog=         "$opt_vardir/log/mysqltest.log";
  $path_current_testlog= "$opt_vardir/log/current_test";

}


sub print_global_resfile {
  resfile_global("start_time", isotime $^T);
  resfile_global("user_id", $<);
  resfile_global("embedded-server", $opt_embedded_server ? 1 : 0);
  resfile_global("ps-protocol", $opt_ps_protocol ? 1 : 0);
  resfile_global("sp-protocol", $opt_sp_protocol ? 1 : 0);
  resfile_global("view-protocol", $opt_view_protocol ? 1 : 0);
  resfile_global("cursor-protocol", $opt_cursor_protocol ? 1 : 0);
  resfile_global("ssl", $opt_ssl ? 1 : 0);
  resfile_global("compress", $opt_compress ? 1 : 0);
  resfile_global("parallel", $opt_parallel);
  resfile_global("check-testcases", $opt_check_testcases ? 1 : 0);
  resfile_global("mysqld", \@opt_extra_mysqld_opt);
  resfile_global("debug", $opt_debug ? 1 : 0);
  resfile_global("gcov", $opt_gcov ? 1 : 0);
  resfile_global("gprof", $opt_gprof ? 1 : 0);
  resfile_global("valgrind", $opt_valgrind ? 1 : 0);
  resfile_global("callgrind", $opt_callgrind ? 1 : 0);
1055
  resfile_global("mem", $opt_mem);
1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124
  resfile_global("tmpdir", $opt_tmpdir);
  resfile_global("vardir", $opt_vardir);
  resfile_global("fast", $opt_fast ? 1 : 0);
  resfile_global("force-restart", $opt_force_restart ? 1 : 0);
  resfile_global("reorder", $opt_reorder ? 1 : 0);
  resfile_global("sleep", $opt_sleep);
  resfile_global("repeat", $opt_repeat);
  resfile_global("user", $opt_user);
  resfile_global("testcase-timeout", $opt_testcase_timeout);
  resfile_global("suite-timeout", $opt_suite_timeout);
  resfile_global("shutdown-timeout", $opt_shutdown_timeout ? 1 : 0);
  resfile_global("warnings", $opt_warnings ? 1 : 0);
  resfile_global("max-connections", $opt_max_connections);
  resfile_global("product", "MySQL");
  # Somewhat hacky code to convert numeric version back to dot notation
  my $v1= int($mysql_version_id / 10000);
  my $v2= int(($mysql_version_id % 10000)/100);
  my $v3= $mysql_version_id % 100;
  resfile_global("version", "$v1.$v2.$v3");
}



sub command_line_setup {
  my $opt_comment;
  my $opt_usage;
  my $opt_list_options;

  # Read the command line options
  # Note: Keep list in sync with usage at end of this file
  Getopt::Long::Configure("pass_through");
  my %options=(
             # Control what engine/variation to run
             'embedded-server'          => \$opt_embedded_server,
             'ps-protocol'              => \$opt_ps_protocol,
             'sp-protocol'              => \$opt_sp_protocol,
             'view-protocol'            => \$opt_view_protocol,
             'cursor-protocol'          => \$opt_cursor_protocol,
             'non-blocking-api'         => \$opt_non_blocking_api,
             'ssl|with-openssl'         => \$opt_ssl,
             'skip-ssl'                 => \$opt_skip_ssl,
             'compress'                 => \$opt_compress,
             'vs-config=s'              => \$opt_vs_config,

	     # Max number of parallel threads to use
	     'parallel=s'               => \$opt_parallel,

             # Config file to use as template for all tests
	     'defaults-file=s'          => \&collect_option,
	     # Extra config file to append to all generated configs
	     'defaults-extra-file=s'    => \&collect_option,

             # Control what test suites or cases to run
             'force+'                   => \$opt_force,
             'suite|suites=s'           => \$opt_suites,
             'skip-rpl'                 => \&collect_option,
             'skip-test=s'              => \&collect_option,
             'do-test=s'                => \&collect_option,
             'start-from=s'             => \&collect_option,
             'big-test+'                => \$opt_big_test,
	     'combination=s'            => \@opt_combinations,
             'experimental=s'           => \@opt_experimentals,
	     # skip-im is deprecated and silently ignored
	     'skip-im'                  => \&ignore_option,
             'staging-run'              => \$opt_staging_run,

             # Specify ports
	     'build-thread|mtr-build-thread=i' => \$opt_build_thread,
	     'port-base|mtr-port-base=i'       => \$opt_port_base,
1125
	     'port-group-size=s'        => \$opt_port_group_size,
1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142

             # Test case authoring
             'record'                   => \$opt_record,
             'check-testcases!'         => \$opt_check_testcases,
             'mark-progress'            => \$opt_mark_progress,

             # Extra options used when starting mysqld
             'mysqld=s'                 => \@opt_extra_mysqld_opt,
             'mysqld-env=s'             => \@opt_mysqld_envs,

             # Run test on running server
             'extern=s'                  => \%opts_extern, # Append to hash

             # Debugging
             'debug'                    => \$opt_debug,
             'debug-common'             => \$opt_debug_common,
             'debug-server'             => \$opt_debug_server,
1143
             'gdb=s'                    => \$opt_gdb,
1144 1145
             'client-gdb'               => \$opt_client_gdb,
             'manual-gdb'               => \$opt_manual_gdb,
1146
             'manual-lldb'              => \$opt_manual_lldb,
1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164
	     'boot-gdb'                 => \$opt_boot_gdb,
             'manual-debug'             => \$opt_manual_debug,
             'ddd'                      => \$opt_ddd,
             'client-ddd'               => \$opt_client_ddd,
             'manual-ddd'               => \$opt_manual_ddd,
	     'boot-ddd'                 => \$opt_boot_ddd,
             'dbx'                      => \$opt_dbx,
	     'client-dbx'               => \$opt_client_dbx,
	     'manual-dbx'               => \$opt_manual_dbx,
	     'debugger=s'               => \$opt_debugger,
	     'boot-dbx'                 => \$opt_boot_dbx,
	     'client-debugger=s'        => \$opt_client_debugger,
             'strace'			=> \$opt_strace,
             'strace-client'            => \$opt_strace_client,
             'strace-option=s'          => \@strace_args,
             'max-save-core=i'          => \$opt_max_save_core,
             'max-save-datadir=i'       => \$opt_max_save_datadir,
             'max-test-fail=i'          => \$opt_max_test_fail,
1165
             'core-on-failure'          => \$opt_core_on_failure,
1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228

             # Coverage, profiling etc
             'gcov'                     => \$opt_gcov,
             'gprof'                    => \$opt_gprof,
             'valgrind|valgrind-all'    => \$opt_valgrind,
             'valgrind-mysqltest'       => \$opt_valgrind_mysqltest,
             'valgrind-mysqld'          => \$opt_valgrind_mysqld,
             'valgrind-options=s'       => sub {
	       my ($opt, $value)= @_;
	       # Deprecated option unless it's what we know pushbuild uses
	       if ($value eq "--gen-suppressions=all --show-reachable=yes") {
		 push(@valgrind_args, $_) for (split(' ', $value));
		 return;
	       }
	       die("--valgrind-options=s is deprecated. Use ",
		   "--valgrind-option=s, to be specified several",
		   " times if necessary");
	     },
             'valgrind-option=s'        => \@valgrind_args,
             'valgrind-path=s'          => \$opt_valgrind_path,
	     'callgrind'                => \$opt_callgrind,
	     'debug-sync-timeout=i'     => \$opt_debug_sync_timeout,

	     # Directories
             'tmpdir=s'                 => \$opt_tmpdir,
             'vardir=s'                 => \$opt_vardir,
             'mem'                      => \$opt_mem,
	     'clean-vardir'             => \$opt_clean_vardir,
             'client-bindir=s'          => \$path_client_bindir,
             'client-libdir=s'          => \$path_client_libdir,

             # Misc
             'comment=s'                => \$opt_comment,
             'fast'                     => \$opt_fast,
	     'force-restart'            => \$opt_force_restart,
             'reorder!'                 => \$opt_reorder,
             'enable-disabled'          => \&collect_option,
             'verbose+'                 => \$opt_verbose,
             'verbose-restart'          => \&report_option,
             'sleep=i'                  => \$opt_sleep,
             'start-dirty'              => \$opt_start_dirty,
             'start-and-exit'           => \$opt_start_exit,
             'start'                    => \$opt_start,
	     'user-args'                => \$opt_user_args,
             'wait-all'                 => \$opt_wait_all,
	     'print-testcases'          => \&collect_option,
	     'repeat=i'                 => \$opt_repeat,
	     'retry=i'                  => \$opt_retry,
	     'retry-failure=i'          => \$opt_retry_failure,
             'timer!'                   => \&report_option,
             'user=s'                   => \$opt_user,
             'testcase-timeout=i'       => \$opt_testcase_timeout,
             'suite-timeout=i'          => \$opt_suite_timeout,
             'shutdown-timeout=i'       => \$opt_shutdown_timeout,
             'warnings!'                => \$opt_warnings,
	     'timestamp'                => \&report_option,
	     'timediff'                 => \&report_option,
             'stop-file=s'              => \$opt_stop_file,
             'stop-keep-alive=i'        => \$opt_stop_keep_alive,
	     'max-connections=i'        => \$opt_max_connections,
	     'report-times'             => \$opt_report_times,
	     'result-file'              => \$opt_resfile,
	     'stress=s'                 => \$opt_stress,
1229
	     'tail-lines=i'             => \$opt_tail_lines,
1230 1231 1232 1233 1234 1235 1236 1237
             'dry-run'                  => \$opt_dry_run,

             'help|h'                   => \$opt_usage,
	     # list-options is internal, not listed in help
	     'list-options'             => \$opt_list_options,
             'skip-test-list=s'         => \@opt_skip_test_list
           );

1238 1239 1240
  # fix options (that take an optional argument and *only* after = sign
  my %fixopt = ( '--gdb' => '--gdb=#' );
  @ARGV = map { $fixopt{$_} or $_ } @ARGV;
1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391
  GetOptions(%options) or usage("Can't read options");
  usage("") if $opt_usage;
  list_options(\%options) if $opt_list_options;

  # --------------------------------------------------------------------------
  # Setup verbosity
  # --------------------------------------------------------------------------
  if ($opt_verbose != 0){
    report_option('verbose', $opt_verbose);
  }

  # Find the absolute path to the test directory
  $glob_mysql_test_dir= cwd();
  if ($glob_mysql_test_dir =~ / /)
  {
    die("Working directory \"$glob_mysql_test_dir\" contains space\n".
	"Bailing out, cannot function properly with space in path");
  }
  if (IS_CYGWIN)
  {
    # Use mixed path format i.e c:/path/to/
    $glob_mysql_test_dir= mixed_path($glob_mysql_test_dir);
  }

  # In most cases, the base directory we find everything relative to,
  # is the parent directory of the "mysql-test" directory. For source
  # distributions, TAR binary distributions and some other packages.
  $basedir= dirname($glob_mysql_test_dir);

  # In the RPM case, binaries and libraries are installed in the
  # default system locations, instead of having our own private base
  # directory. And we install "/usr/share/mysql-test". Moving up one
  # more directory relative to "mysql-test" gives us a usable base
  # directory for RPM installs.
  if ( ! $source_dist and ! -d "$basedir/bin" )
  {
    $basedir= dirname($basedir);
  }
  # For .deb, it's like RPM, but installed in /usr/share/mysql/mysql-test.
  # So move up one more directory level yet.
  if ( ! $source_dist and ! -d "$basedir/bin" )
  {
    $basedir= dirname($basedir);
  }

  # Respect MTR_BINDIR variable, which is typically set in to the 
  # build directory in out-of-source builds.
  $bindir=$ENV{MTR_BINDIR}||$basedir;
  
  fix_vs_config_dir();

  # Look for the client binaries directory
  if ($path_client_bindir)
  {
    # --client-bindir=path set on command line, check that the path exists
    $path_client_bindir= mtr_path_exists($path_client_bindir);
  }
  else
  {
    $path_client_bindir= mtr_path_exists("$bindir/client_release",
					 "$bindir/client_debug",
					 "$bindir/client$opt_vs_config",
					 "$bindir/client",
					 "$bindir/bin");
  }

  # Look for language files and charsetsdir, use same share
  $path_language=   mtr_path_exists("$bindir/share/mariadb",
                                    "$bindir/share/mysql",
                                    "$bindir/sql/share",
                                    "$bindir/share");
  my $path_share= $path_language;
  $path_charsetsdir =   mtr_path_exists("$basedir/share/mariadb/charsets",
                                    "$basedir/share/mysql/charsets",
                                    "$basedir/sql/share/charsets",
                                    "$basedir/share/charsets");
  if ( $opt_comment )
  {
    mtr_report();
    mtr_print_thick_line('#');
    mtr_report("# $opt_comment");
    mtr_print_thick_line('#');
  }

  if ( @opt_experimentals )
  {
    # $^O on Windows considered not generic enough
    my $plat= (IS_WINDOWS) ? 'windows' : $^O;

    # read the list of experimental test cases from the files specified on
    # the command line
    $experimental_test_cases = [];
    foreach my $exp_file (@opt_experimentals)
    {
      open(FILE, "<", $exp_file)
	or mtr_error("Can't read experimental file: $exp_file");
      mtr_report("Using experimental file: $exp_file");
      while(<FILE>) {
	chomp;
	# remove comments (# foo) at the beginning of the line, or after a 
	# blank at the end of the line
	s/(\s+|^)#.*$//;
	# If @ platform specifier given, use this entry only if it contains
	# @<platform> or @!<xxx> where xxx != platform
	if (/\@.*/)
	{
	  next if (/\@!$plat/);
	  next unless (/\@$plat/ or /\@!/);
	  # Then remove @ and everything after it
	  s/\@.*$//;
	}
	# remove whitespace
	s/^\s+//;
	s/\s+$//;
	# if nothing left, don't need to remember this line
	if ( $_ eq "" ) {
	  next;
	}
	# remember what is left as the name of another test case that should be
	# treated as experimental
	print " - $_\n";
	push @$experimental_test_cases, $_;
      }
      close FILE;
    }
  }

  foreach my $arg ( @ARGV )
  {
    if ( $arg =~ /^--skip-/ )
    {
      push(@opt_extra_mysqld_opt, $arg);
    }
    elsif ( $arg =~ /^--$/ )
    {
      # It is an effect of setting 'pass_through' in option processing
      # that the lone '--' separating options from arguments survives,
      # simply ignore it.
    }
    elsif ( $arg =~ /^-/ )
    {
      usage("Invalid option \"$arg\"");
    }
    else
    {
      push(@opt_cases, $arg);
    }
  }

  if ( @opt_cases )
  {
1392
    # Run big tests if explicitly specified on command line
1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449
    $opt_big_test= 1;
  }

  # --------------------------------------------------------------------------
  # Find out type of logging that are being used
  # --------------------------------------------------------------------------
  foreach my $arg ( @opt_extra_mysqld_opt )
  {
    if ( $arg =~ /binlog[-_]format=(\S+)/ )
    {
      # Save this for collect phase
      collect_option('binlog-format', $1);
      mtr_report("Using binlog format '$1'");
    }
  }


  # --------------------------------------------------------------------------
  # Find out default storage engine being used(if any)
  # --------------------------------------------------------------------------
  foreach my $arg ( @opt_extra_mysqld_opt )
  {
    if ( $arg =~ /default-storage-engine=(\S+)/ )
    {
      # Save this for collect phase
      collect_option('default-storage-engine', $1);
      mtr_report("Using default engine '$1'")
    }
  }

  if (IS_WINDOWS and defined $opt_mem) {
    mtr_report("--mem not supported on Windows, ignored");
    $opt_mem= undef;
  }

  if ($opt_port_base ne "auto")
  {
    if (my $rem= $opt_port_base % 10)
    {
      mtr_warning ("Port base $opt_port_base rounded down to multiple of 10");
      $opt_port_base-= $rem;
    }
    $opt_build_thread= $opt_port_base / 10 - 1000;
  }

  # --------------------------------------------------------------------------
  # Check if we should speed up tests by trying to run on tmpfs
  # --------------------------------------------------------------------------
  if ( defined $opt_mem)
  {
    mtr_error("Can't use --mem and --vardir at the same time ")
      if $opt_vardir;
    mtr_error("Can't use --mem and --tmpdir at the same time ")
      if $opt_tmpdir;

    # Search through list of locations that are known
    # to be "fast disks" to find a suitable location
1450 1451 1452 1453
    my @tmpfs_locations= ("/run/shm", "/dev/shm", "/tmp");

    # Use $ENV{'MTR_MEM'} as first location to look (if defined)
    unshift(@tmpfs_locations, $ENV{'MTR_MEM'}) if defined $ENV{'MTR_MEM'};
1454 1455 1456

    foreach my $fs (@tmpfs_locations)
    {
1457
      if ( -d $fs && ! -l $fs  && -w $fs )
1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468
      {
	my $template= "var_${opt_build_thread}_XXXX";
	$opt_mem= tempdir( $template, DIR => $fs, CLEANUP => 0);
	last;
      }
    }
  }

  # --------------------------------------------------------------------------
  # Set the "var/" directory, the base for everything else
  # --------------------------------------------------------------------------
1469 1470 1471 1472 1473
  my $vardir_location= (defined $ENV{MTR_BINDIR} 
                          ? "$ENV{MTR_BINDIR}/mysql-test" 
                          : $glob_mysql_test_dir);
  $vardir_location= realpath $vardir_location unless IS_WINDOWS;
  $default_vardir= "$vardir_location/var";
1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579

  if ( ! $opt_vardir )
  {
    $opt_vardir= $default_vardir;
  }

  # We make the path absolute, as the server will do a chdir() before usage
  unless ( $opt_vardir =~ m,^/, or
           (IS_WINDOWS and $opt_vardir =~ m,^[a-z]:[/\\],i) )
  {
    # Make absolute path, relative test dir
    $opt_vardir= "$glob_mysql_test_dir/$opt_vardir";
  }

  set_vardir($opt_vardir);

  # --------------------------------------------------------------------------
  # Set the "tmp" directory
  # --------------------------------------------------------------------------
  if ( ! $opt_tmpdir )
  {
    $opt_tmpdir=       "$opt_vardir/tmp" unless $opt_tmpdir;

    if (check_socket_path_length("$opt_tmpdir/mysql_testsocket.sock"))
    {
      mtr_report("Too long tmpdir path '$opt_tmpdir'",
		 " creating a shorter one...");

      # Create temporary directory in standard location for temporary files
      $opt_tmpdir= tempdir( TMPDIR => 1, CLEANUP => 0 );
      mtr_report(" - using tmpdir: '$opt_tmpdir'\n");

      # Remember pid that created dir so it's removed by correct process
      $opt_tmpdir_pid= $$;
    }
  }
  $opt_tmpdir =~ s,/+$,,;       # Remove ending slash if any

  # --------------------------------------------------------------------------
  # fast option
  # --------------------------------------------------------------------------
  if ($opt_fast){
    $opt_shutdown_timeout= 0; # Kill processes instead of nice shutdown
  }

  # --------------------------------------------------------------------------
  # Check parallel value
  # --------------------------------------------------------------------------
  if ($opt_parallel ne "auto" && $opt_parallel < 1)
  {
    mtr_error("0 or negative parallel value makes no sense, use 'auto' or positive number");
  }

  # --------------------------------------------------------------------------
  # Record flag
  # --------------------------------------------------------------------------
  if ( $opt_record and ! @opt_cases )
  {
    mtr_error("Will not run in record mode without a specific test case");
  }

  if ( $opt_record ) {
    # Use only one worker with --record
    $opt_parallel= 1;
  }

  # --------------------------------------------------------------------------
  # Embedded server flag
  # --------------------------------------------------------------------------
  if ( $opt_embedded_server )
  {
    $opt_skip_ssl= 1;              # Turn off use of SSL

    # Turn off use of bin log
    push(@opt_extra_mysqld_opt, "--skip-log-bin");

    if ( using_extern() )
    {
      mtr_error("Can't use --extern with --embedded-server");
    }


    if ($opt_gdb)
    {
      $opt_client_gdb= $opt_gdb;
      $opt_gdb= undef;
    }

    if ($opt_ddd)
    {
      $opt_client_ddd= $opt_ddd;
      $opt_ddd= undef;
    }

    if ($opt_dbx) {
      mtr_warning("Silently converting --dbx to --client-dbx in embedded mode");
      $opt_client_dbx= $opt_dbx;
      $opt_dbx= undef;
    }

    if ($opt_debugger)
    {
      $opt_client_debugger= $opt_debugger;
      $opt_debugger= undef;
    }

1580 1581 1582
    if ( $opt_gdb || $opt_ddd || $opt_manual_gdb || $opt_manual_lldb || 
         $opt_manual_ddd || $opt_manual_debug || $opt_debugger || $opt_dbx || 
         $opt_manual_dbx)
1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608
    {
      mtr_error("You need to use the client debug options for the",
		"embedded server. Ex: --client-gdb");
    }
  }

  # --------------------------------------------------------------------------
  # Big test and staging_run flags
  # --------------------------------------------------------------------------
   if ( $opt_big_test )
   {
     $ENV{'BIG_TEST'}= 1;
   }
  $ENV{'STAGING_RUN'}= $opt_staging_run;

  # --------------------------------------------------------------------------
  # Gcov flag
  # --------------------------------------------------------------------------
  if ( ($opt_gcov or $opt_gprof) and ! $source_dist )
  {
    mtr_error("Coverage test needs the source - please use source dist");
  }

  # --------------------------------------------------------------------------
  # Check debug related options
  # --------------------------------------------------------------------------
1609 1610 1611
  if ( $opt_gdb || $opt_client_gdb || $opt_ddd || $opt_client_ddd || 
       $opt_manual_gdb || $opt_manual_lldb || $opt_manual_ddd || 
       $opt_manual_debug || $opt_dbx || $opt_client_dbx || $opt_manual_dbx || 
1612 1613
       $opt_debugger || $opt_client_debugger )
  {
1614
    $ENV{ASAN_OPTIONS}= 'abort_on_error=1:'.($ENV{ASAN_OPTIONS} || '');
1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731
    if ( using_extern() )
    {
      mtr_error("Can't use --extern when using debugger");
    }
    # Indicate that we are using debugger
    $glob_debugger= 1;
    $opt_retry= 1;
    $opt_retry_failure= 1;
    # Set one week timeout (check-testcase timeout will be 1/10th)
    $opt_testcase_timeout= 7 * 24 * 60;
    $opt_suite_timeout= 7 * 24 * 60;
    # One day to shutdown
    $opt_shutdown_timeout= 24 * 60;
    # One day for PID file creation (this is given in seconds not minutes)
    $opt_start_timeout= 24 * 60 * 60;
  }

  # --------------------------------------------------------------------------
  # Modified behavior with --start options
  # --------------------------------------------------------------------------
  if ($opt_start or $opt_start_dirty or $opt_start_exit) {
    collect_option ('quick-collect', 1);
    $start_only= 1;
  }
  if ($opt_debug)
  {
    $opt_testcase_timeout= 7 * 24 * 60;
    $opt_suite_timeout= 7 * 24 * 60;
    $opt_retry= 1;
    $opt_retry_failure= 1;
  }

  # --------------------------------------------------------------------------
  # Check use of user-args
  # --------------------------------------------------------------------------

  if ($opt_user_args) {
    mtr_error("--user-args only valid with --start options")
      unless $start_only;
    mtr_error("--user-args cannot be combined with named suites or tests")
      if $opt_suites || @opt_cases;
  }

  # --------------------------------------------------------------------------
  # Check use of wait-all
  # --------------------------------------------------------------------------

  if ($opt_wait_all && ! $start_only)
  {
    mtr_error("--wait-all can only be used with --start options");
  }

  # --------------------------------------------------------------------------
  # Gather stress-test options and modify behavior
  # --------------------------------------------------------------------------

  if ($opt_stress)
  {
    $opt_stress=~ s/,/ /g;
    $opt_user_args= 1;
    mtr_error("--stress cannot be combined with named ordinary suites or tests")
      if $opt_suites || @opt_cases;
    $opt_suites="stress";
    @opt_cases= ("wrapper");
    $ENV{MST_OPTIONS}= $opt_stress;
  }

  # --------------------------------------------------------------------------
  # Check timeout arguments
  # --------------------------------------------------------------------------

  mtr_error("Invalid value '$opt_testcase_timeout' supplied ".
	    "for option --testcase-timeout")
    if ($opt_testcase_timeout <= 0);
  mtr_error("Invalid value '$opt_suite_timeout' supplied ".
	    "for option --testsuite-timeout")
    if ($opt_suite_timeout <= 0);

  # --------------------------------------------------------------------------
  # Check valgrind arguments
  # --------------------------------------------------------------------------
  if ( $opt_valgrind or $opt_valgrind_path or @valgrind_args)
  {
    mtr_report("Turning on valgrind for all executables");
    $opt_valgrind= 1;
    $opt_valgrind_mysqld= 1;
    $opt_valgrind_mysqltest= 1;
  }
  elsif ( $opt_valgrind_mysqld )
  {
    mtr_report("Turning on valgrind for mysqld(s) only");
    $opt_valgrind= 1;
  }
  elsif ( $opt_valgrind_mysqltest )
  {
    mtr_report("Turning on valgrind for mysqltest and mysql_client_test only");
    $opt_valgrind= 1;
  }

  if ($opt_valgrind)
  {
    # Increase the timeouts when running with valgrind
    $opt_testcase_timeout*= 10;
    $opt_suite_timeout*= 6;
    $opt_start_timeout*= 10;
    $warn_seconds*= 10;
  }

  if ( $opt_callgrind )
  {
    mtr_report("Turning on valgrind with callgrind for mysqld(s)");
    $opt_valgrind= 1;
    $opt_valgrind_mysqld= 1;

    # Set special valgrind options unless options passed on command line
    push(@valgrind_args, "--trace-children=yes")
      unless @valgrind_args;
1732
    unshift(@valgrind_args, "--tool=callgrind");
1733 1734
  }

1735 1736
  # default to --tool=memcheck
  if ($opt_valgrind && ! grep(/^--tool=/i, @valgrind_args))
1737
  {
1738 1739 1740
    # Set valgrind_option unless already defined
    push(@valgrind_args, ("--show-reachable=yes", "--leak-check=yes",
                          "--num-callers=16"))
1741
      unless @valgrind_args;
1742 1743
    unshift(@valgrind_args, "--tool=memcheck");
  }
1744

1745 1746
  if ( $opt_valgrind )
  {
1747 1748 1749
    # Make valgrind run in quiet mode so it only print errors
    push(@valgrind_args, "--quiet" );

1750 1751 1752
    push(@valgrind_args, "--suppressions=${glob_mysql_test_dir}/valgrind.supp")
      if -f "$glob_mysql_test_dir/valgrind.supp";

1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790
    mtr_report("Running valgrind with options \"",
	       join(" ", @valgrind_args), "\"");
  }

  if (@strace_args)
  {
    $opt_strace=1;
  }

  if ($opt_debug_common)
  {
    $opt_debug= 1;
    $debug_d= "d,query,info,error,enter,exit";
  }
}


#
# To make it easier for different devs to work on the same host,
# an environment variable can be used to control all ports. A small
# number is to be used, 0 - 16 or similar.
#
# Note the MASTER_MYPORT has to be set the same in all 4.x and 5.x
# versions of this script, else a 4.0 test run might conflict with a
# 5.1 test run, even if different MTR_BUILD_THREAD is used. This means
# all port numbers might not be used in this version of the script.
#
# Also note the limitation of ports we are allowed to hand out. This
# differs between operating systems and configuration, see
# http://www.ncftp.com/ncftpd/doc/misc/ephemeral_ports.html
# But a fairly safe range seems to be 5001 - 32767
#
sub set_build_thread_ports($) {
  my $thread= shift || 0;

  if ( lc($opt_build_thread) eq 'auto' ) {
    my $found_free = 0;
    $build_thread = 300;	# Start attempts from here
1791 1792 1793
    my $build_thread_upper = $build_thread + ($opt_parallel > 1500
                                              ? 3000
                                              : 2 * $opt_parallel) + 300;
1794 1795
    while (! $found_free)
    {
1796
      $build_thread= mtr_get_unique_id($build_thread, $build_thread_upper);
1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818
      if ( !defined $build_thread ) {
        mtr_error("Could not get a unique build thread id");
      }
      $found_free= check_ports_free($build_thread);
      # If not free, release and try from next number
      if (! $found_free) {
        mtr_release_unique_id();
        $build_thread++;
      }
    }
  }
  else
  {
    $build_thread = $opt_build_thread + $thread - 1;
    if (! check_ports_free($build_thread)) {
      # Some port was not free(which one has already been printed)
      mtr_error("Some port(s) was not free")
    }
  }
  $ENV{MTR_BUILD_THREAD}= $build_thread;

  # Calculate baseport
1819 1820
  $baseport= $build_thread * $opt_port_group_size + 10000;
  if ( $baseport < 5001 or $baseport + $opt_port_group_size >= 32767 )
1821 1822 1823
  {
    mtr_error("MTR_BUILD_THREAD number results in a port",
              "outside 5001 - 32767",
1824
              "($baseport - $baseport + $opt_port_group_size)");
1825 1826 1827
  }

  mtr_report("Using MTR_BUILD_THREAD $build_thread,",
1828
	     "with reserved ports $baseport..".($baseport+($opt_port_group_size-1)));
1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850

}


sub collect_mysqld_features {
  #
  # Execute "mysqld --no-defaults --help --verbose" to get a
  # list of all features and settings
  #
  # --no-defaults and --skip-grant-tables are to avoid loading
  # system-wide configs and plugins
  #
  # --datadir must exist, mysqld will chdir into it
  #
  my $args;
  mtr_init_args(\$args);
  mtr_add_arg($args, "--no-defaults");
  mtr_add_arg($args, "--datadir=.");
  mtr_add_arg($args, "--basedir=%s", $basedir);
  mtr_add_arg($args, "--lc-messages-dir=%s", $path_language);
  mtr_add_arg($args, "--skip-grant-tables");
  mtr_add_arg($args, "--log-warnings=0");
1851 1852 1853
  mtr_add_arg($args, "--log-slow-admin-statements=0");
  mtr_add_arg($args, "--log-queries-not-using-indexes=0");
  mtr_add_arg($args, "--log-slow-slave-statements=0");
1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867
  mtr_add_arg($args, "--verbose");
  mtr_add_arg($args, "--help");

  my $exe_mysqld= find_mysqld($bindir);
  my $cmd= join(" ", $exe_mysqld, @$args);

  mtr_verbose("cmd: $cmd");

  my $list= `$cmd`;

  # to simplify the parsing, we'll merge all nicely formatted --help texts
  $list =~ s/\n {22}(\S)/ $1/g;

  my @list= split '\n', $list;
1868 1869 1870 1871 1872 1873 1874 1875 1876

  $mysql_version_id= 0;
  while (defined(my $line = shift @list)){
     if ($line =~ /^\Q$exe_mysqld\E\s+Ver\s(\d+)\.(\d+)\.(\d+)(\S*)/ ) {
      $mysql_version_id= $1*10000 + $2*100 + $3;
      mtr_report("MariaDB Version $1.$2.$3$4");
      last;
    }
  }
1877
  mtr_error("Could not find version of MariaDB")
1878
     unless $mysql_version_id > 0;
1879 1880 1881 1882 1883 1884 1885 1886 1887

  for (@list)
  {
    # first part of the help - command-line options.
    if (/Copyright/ .. /^-{30,}/) {
      # here we want to detect all not mandatory plugins
      # they are listed in the --help output as
      #  --archive[=name]    Enable or disable ARCHIVE plugin. Possible values are ON, OFF, FORCE (don't start if the plugin fails to load).
      push @optional_plugins, $1
1888
        if /^  --([-a-z0-9]+)\[=name\] +Enable or disable \w+ plugin. One of: ON, OFF, FORCE/;
1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943
      next;
    }

    last if /^$/; # then goes a list of variables, it ends with an empty line

    # Put a variable into hash
    /^([\S]+)[ \t]+(.*?)\r?$/ or die "Could not parse mysqld --help: $_\n";
    $mysqld_variables{$1}= $2;
  }
  mtr_error("Could not find variabes list") unless %mysqld_variables;
}



sub collect_mysqld_features_from_running_server ()
{
  my $mysql= mtr_exe_exists("$path_client_bindir/mysql");

  my $args;
  mtr_init_args(\$args);

  mtr_add_arg($args, "--no-defaults");
  mtr_add_arg($args, "--user=%s", $opt_user);

  while (my ($option, $value)= each( %opts_extern )) {
    mtr_add_arg($args, "--$option=$value");
  }

  mtr_add_arg($args, "--silent"); # Tab separated output
  mtr_add_arg($args, "-e '%s'", "use mysql; SHOW VARIABLES");
  my $cmd= "$mysql " . join(' ', @$args);
  mtr_verbose("cmd: $cmd");

  my $list = `$cmd` or
    mtr_error("Could not connect to extern server using command: '$cmd'");
  foreach my $line (split('\n', $list ))
  {
    # Put variables into hash
    if ( $line =~ /^([\S]+)[ \t]+(.*?)\r?$/ )
    {
      my $name= $1;
      my $value=$2;
      $name =~ s/_/-/g;
      # print "$name=\"$value\"\n";
      $mysqld_variables{$name}= $value;
    }
  }

  # Parse version
  my $version_str= $mysqld_variables{'version'};
  if ( $version_str =~ /^([0-9]*)\.([0-9]*)\.([0-9]*)([^\s]*)/ )
  {
    #print "Major: $1 Minor: $2 Build: $3\n";
    $mysql_version_id= $1*10000 + $2*100 + $3;
    #print "mysql_version_id: $mysql_version_id\n";
1944
    mtr_report("MariaDB Version $1.$2.$3");
1945 1946
    $mysql_version_extra= $4;
  }
1947
  mtr_error("Could not find version of MariaDBL") unless $mysql_version_id;
1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150
}

sub find_mysqld {

  my ($mysqld_basedir)= $ENV{MTR_BINDIR}|| @_;

  my @mysqld_names= ("mysqld", "mysqld-max-nt", "mysqld-max",
		     "mysqld-nt");

  if ( $opt_debug_server ){
    # Put mysqld-debug first in the list of binaries to look for
    mtr_verbose("Adding mysqld-debug first in list of binaries to look for");
    unshift(@mysqld_names, "mysqld-debug");
  }

  return my_find_bin($bindir,
		     ["sql", "libexec", "sbin", "bin"],
		     [@mysqld_names]);
}


sub executable_setup () {

  $exe_patch='patch' if `patch -v`;

  #
  # Check if libtool is available in this distribution/clone
  # we need it when valgrinding or debugging non installed binary
  # Otherwise valgrind will valgrind the libtool wrapper or bash
  # and gdb will not find the real executable to debug
  #
  if ( -x "../libtool")
  {
    $exe_libtool= "../libtool";
    if ($opt_valgrind or $glob_debugger or $opt_strace)
    {
      mtr_report("Using \"$exe_libtool\" when running valgrind, strace or debugger");
    }
  }

  # Look for the client binaries
  $exe_mysqladmin=     mtr_exe_exists("$path_client_bindir/mysqladmin");
  $exe_mysql=          mtr_exe_exists("$path_client_bindir/mysql");
  $exe_mysql_plugin=   mtr_exe_exists("$path_client_bindir/mysql_plugin");

  $exe_mysql_embedded= mtr_exe_maybe_exists("$basedir/libmysqld/examples/mysql_embedded");

  # Look for mysqltest executable
  if ( $opt_embedded_server )
  {
    $exe_mysqltest=
      mtr_exe_exists("$bindir/libmysqld/examples$opt_vs_config/mysqltest_embedded",
                     "$path_client_bindir/mysqltest_embedded");
  }
  else
  {
    if ( defined $ENV{'MYSQL_TEST'} )
    {
      $exe_mysqltest=$ENV{'MYSQL_TEST'};
      print "===========================================================\n";
      print "WARNING:The mysqltest binary is fetched from $exe_mysqltest\n";
      print "===========================================================\n";
    }
    else
    {
      $exe_mysqltest= mtr_exe_exists("$path_client_bindir/mysqltest");
    }
  }

}


sub client_debug_arg($$) {
  my ($args, $client_name)= @_;

  # Workaround for Bug #50627: drop any debug opt
  return if $client_name =~ /^mysqlbinlog/;

  if ( $opt_debug ) {
    mtr_add_arg($args,
		"--loose-debug=$debug_d:t:A,%s/log/%s.trace",
		$path_vardir_trace, $client_name)
  }
}


sub client_arguments ($;$) {
 my $client_name= shift;
  my $group_suffix= shift;
  my $client_exe= mtr_exe_exists("$path_client_bindir/$client_name");

  my $args;
  mtr_init_args(\$args);
  mtr_add_arg($args, "--defaults-file=%s", $path_config_file);
  if (defined($group_suffix)) {
    mtr_add_arg($args, "--defaults-group-suffix=%s", $group_suffix);
    client_debug_arg($args, "$client_name-$group_suffix");
  }
  else
  {
    client_debug_arg($args, $client_name);
  }
  return mtr_args2str($client_exe, @$args);
}


sub mysqlbinlog_arguments () {
  my $exe= mtr_exe_exists("$path_client_bindir/mysqlbinlog");

  my $args;
  mtr_init_args(\$args);
  mtr_add_arg($args, "--defaults-file=%s", $path_config_file);
  mtr_add_arg($args, "--local-load=%s", $opt_tmpdir);
  client_debug_arg($args, "mysqlbinlog");
  return mtr_args2str($exe, @$args);
}


sub mysqlslap_arguments () {
  my $exe= mtr_exe_maybe_exists("$path_client_bindir/mysqlslap");
  if ( $exe eq "" ) {
    # mysqlap was not found

    if (defined $mysql_version_id and $mysql_version_id >= 50100 ) {
      mtr_error("Could not find the mysqlslap binary");
    }
    return ""; # Don't care about mysqlslap
  }

  my $args;
  mtr_init_args(\$args);
  mtr_add_arg($args, "--defaults-file=%s", $path_config_file);
  client_debug_arg($args, "mysqlslap");
  return mtr_args2str($exe, @$args);
}


sub mysqldump_arguments ($) {
  my($group_suffix) = @_;
  my $exe= mtr_exe_exists("$path_client_bindir/mysqldump");

  my $args;
  mtr_init_args(\$args);
  mtr_add_arg($args, "--defaults-file=%s", $path_config_file);
  mtr_add_arg($args, "--defaults-group-suffix=%s", $group_suffix);
  client_debug_arg($args, "mysqldump-$group_suffix");
  return mtr_args2str($exe, @$args);
}


sub mysql_client_test_arguments(){
  my $exe;
  # mysql_client_test executable may _not_ exist
  if ( $opt_embedded_server ) {
    $exe= mtr_exe_maybe_exists(
            "$bindir/libmysqld/examples$opt_vs_config/mysql_client_test_embedded",
		"$bindir/bin/mysql_client_test_embedded");
  } else {
    $exe= mtr_exe_maybe_exists("$bindir/tests$opt_vs_config/mysql_client_test",
			       "$bindir/bin/mysql_client_test");
  }

  my $args;
  mtr_init_args(\$args);
  if ( $opt_valgrind_mysqltest ) {
    valgrind_arguments($args, \$exe);
  }
  mtr_add_arg($args, "--defaults-file=%s", $path_config_file);
  mtr_add_arg($args, "--testcase");
  mtr_add_arg($args, "--vardir=$opt_vardir");
  client_debug_arg($args,"mysql_client_test");
  my $ret=mtr_args2str($exe, @$args);
  return $ret;
}

sub tool_arguments ($$) {
  my($sedir, $tool_name) = @_;
  my $exe= my_find_bin($bindir,
		       [$sedir, "bin"],
		       $tool_name);

  my $args;
  mtr_init_args(\$args);
  client_debug_arg($args, $tool_name);
  return mtr_args2str($exe, @$args);
}

# This is not used to actually start a mysqld server, just to allow test
# scripts to run the mysqld binary to test invalid server startup options.
sub mysqld_client_arguments () {
  my $default_mysqld= default_mysqld();
  my $exe = find_mysqld($bindir);
  my $args;
  mtr_init_args(\$args);
  mtr_add_arg($args, "--no-defaults");
  mtr_add_arg($args, "--basedir=%s", $basedir);
  mtr_add_arg($args, "--character-sets-dir=%s", $default_mysqld->value("character-sets-dir"));
  mtr_add_arg($args, "--language=%s", $default_mysqld->value("language"));
  return mtr_args2str($exe, @$args);
}


sub have_maria_support () {
2151
  my $maria_var= $mysqld_variables{'aria-recover-options'};
2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236
  return defined $maria_var;
}


sub environment_setup {

  umask(022);

  my @ld_library_paths;

  if ($path_client_libdir)
  {
    # Use the --client-libdir passed on commandline
    push(@ld_library_paths, "$path_client_libdir");
  }
  else
  {
    # Setup LD_LIBRARY_PATH so the libraries from this distro/clone
    # are used in favor of the system installed ones
    if ( $source_dist )
    {
      push(@ld_library_paths, "$basedir/libmysql/.libs/",
	   "$basedir/libmysql_r/.libs/",
	   "$basedir/zlib/.libs/");
      if ($^O eq "darwin")
      {
        # it is MAC OS and we have to add dynamic libraries paths
        push @ld_library_paths, grep {<$_/*.dylib>} 
          (<$bindir/storage/*/.libs/>,<$bindir/plugin/*/.libs/>,
          <$bindir/plugin/*/*/.libs/>,<$bindir/storage/*/*/.libs>);
      }
    }
    else
    {
      push(@ld_library_paths, "$basedir/lib", "$basedir/lib/mysql");
    }
  }

  # --------------------------------------------------------------------------
  # Valgrind need to be run with debug libraries otherwise it's almost
  # impossible to add correct supressions, that means if "/usr/lib/debug"
  # is available, it should be added to
  # LD_LIBRARY_PATH
  #
  # But pthread is broken in libc6-dbg on Debian <= 3.1 (see Debian
  # bug 399035, http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=399035),
  # so don't change LD_LIBRARY_PATH on that platform.
  # --------------------------------------------------------------------------
  my $debug_libraries_path= "/usr/lib/debug";
  my $deb_version;
  if (  $opt_valgrind and -d $debug_libraries_path and
        (! -e '/etc/debian_version' or
	 ($deb_version=
	    mtr_grab_file('/etc/debian_version')) !~ /^[0-9]+\.[0-9]$/ or
         $deb_version > 3.1 ) )
  {
    push(@ld_library_paths, $debug_libraries_path);
  }

  $ENV{'LD_LIBRARY_PATH'}= join(":", @ld_library_paths,
				$ENV{'LD_LIBRARY_PATH'} ?
				split(':', $ENV{'LD_LIBRARY_PATH'}) : ());
  mtr_debug("LD_LIBRARY_PATH: $ENV{'LD_LIBRARY_PATH'}");

  $ENV{'DYLD_LIBRARY_PATH'}= join(":", @ld_library_paths,
				  $ENV{'DYLD_LIBRARY_PATH'} ?
				  split(':', $ENV{'DYLD_LIBRARY_PATH'}) : ());
  mtr_debug("DYLD_LIBRARY_PATH: $ENV{'DYLD_LIBRARY_PATH'}");

  # The environment variable used for shared libs on AIX
  $ENV{'SHLIB_PATH'}= join(":", @ld_library_paths,
                           $ENV{'SHLIB_PATH'} ?
                           split(':', $ENV{'SHLIB_PATH'}) : ());
  mtr_debug("SHLIB_PATH: $ENV{'SHLIB_PATH'}");

  # The environment variable used for shared libs on hp-ux
  $ENV{'LIBPATH'}= join(":", @ld_library_paths,
                        $ENV{'LIBPATH'} ?
                        split(':', $ENV{'LIBPATH'}) : ());
  mtr_debug("LIBPATH: $ENV{'LIBPATH'}");

  $ENV{'UMASK'}=              "0660"; # The octal *string*
  $ENV{'UMASK_DIR'}=          "0770"; # The octal *string*

  #
2237
  # MariaDB tests can produce output in various character sets
2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293
  # (especially, ctype_xxx.test). To avoid confusing Perl
  # with output which is incompatible with the current locale
  # settings, we reset the current values of LC_ALL and LC_CTYPE to "C".
  # For details, please see
  # Bug#27636 tests fails if LC_* variables set to *_*.UTF-8
  #
  $ENV{'LC_ALL'}=             "C";
  $ENV{'LC_CTYPE'}=           "C";

  $ENV{'LC_COLLATE'}=         "C";
  $ENV{'USE_RUNNING_SERVER'}= using_extern();
  $ENV{'MYSQL_TEST_DIR'}=     $glob_mysql_test_dir;
  $ENV{'DEFAULT_MASTER_PORT'}= $mysqld_variables{'port'};
  $ENV{'MYSQL_TMP_DIR'}=      $opt_tmpdir;
  $ENV{'MYSQLTEST_VARDIR'}=   $opt_vardir;
  $ENV{'MYSQL_BINDIR'}=       $bindir;
  $ENV{'MYSQL_SHAREDIR'}=     $path_language;
  $ENV{'MYSQL_CHARSETSDIR'}=  $path_charsetsdir;
  
  if (IS_WINDOWS)
  {
    $ENV{'SECURE_LOAD_PATH'}= $glob_mysql_test_dir."\\std_data";
  }
  else
  {
    $ENV{'SECURE_LOAD_PATH'}= $glob_mysql_test_dir."/std_data";
  }

  #
  # Some stupid^H^H^H^H^H^Hignorant network providers set up "wildcard DNS"
  # servers that return some given web server address for any lookup of a
  # non-existent host name. This confuses test cases that want to test the
  # behaviour when connecting to a non-existing host, so we need to be able
  # to disable those tests when DNS is broken.
  #
  $ENV{HAVE_BROKEN_DNS}= defined(gethostbyname('invalid_hostname'));

  # ----------------------------------------------------
  # mysql clients
  # ----------------------------------------------------
  $ENV{'MYSQL_CHECK'}=              client_arguments("mysqlcheck");
  $ENV{'MYSQL_DUMP'}=               mysqldump_arguments(".1");
  $ENV{'MYSQL_DUMP_SLAVE'}=         mysqldump_arguments(".2");
  $ENV{'MYSQL_SLAP'}=               mysqlslap_arguments();
  $ENV{'MYSQL_IMPORT'}=             client_arguments("mysqlimport");
  $ENV{'MYSQL_SHOW'}=               client_arguments("mysqlshow");
  $ENV{'MYSQL_BINLOG'}=             mysqlbinlog_arguments();
  $ENV{'MYSQL'}=                    client_arguments("mysql");
  $ENV{'MYSQL_SLAVE'}=              client_arguments("mysql", ".2");
  $ENV{'MYSQL_UPGRADE'}=            client_arguments("mysql_upgrade");
  $ENV{'MYSQLADMIN'}=               client_arguments("mysqladmin");
  $ENV{'MYSQL_CLIENT_TEST'}=        mysql_client_test_arguments();
  $ENV{'EXE_MYSQL'}=                $exe_mysql;
  $ENV{'MYSQL_PLUGIN'}=             $exe_mysql_plugin;
  $ENV{'MYSQL_EMBEDDED'}=           $exe_mysql_embedded;

2294 2295 2296 2297 2298 2299 2300 2301 2302 2303
  my $client_config_exe=
    mtr_exe_maybe_exists(
        "$bindir/libmariadb/mariadb_config$opt_vs_config/mariadb_config",
               "$bindir/bin/mariadb_config");
  if ($client_config_exe)
  {
    my $tls_info= `$client_config_exe --tlsinfo`;
    ($ENV{CLIENT_TLS_LIBRARY},$ENV{CLIENT_TLS_LIBRARY_VERSION})=
      split(/ /, $tls_info, 2);
  }
2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378
  my $exe_mysqld= find_mysqld($basedir);
  $ENV{'MYSQLD'}= $exe_mysqld;
  my $extra_opts= join (" ", @opt_extra_mysqld_opt);
  $ENV{'MYSQLD_CMD'}= "$exe_mysqld --defaults-group-suffix=.1 ".
    "--defaults-file=$path_config_file $extra_opts";

  # ----------------------------------------------------
  # bug25714 executable may _not_ exist in
  # some versions, test using it should be skipped
  # ----------------------------------------------------
  my $exe_bug25714=
      mtr_exe_maybe_exists("$bindir/tests$opt_vs_config/bug25714");
  $ENV{'MYSQL_BUG25714'}=  native_path($exe_bug25714);

  # ----------------------------------------------------
  # mysql_fix_privilege_tables.sql
  # ----------------------------------------------------
  my $file_mysql_fix_privilege_tables=
    mtr_file_exists("$bindir/scripts/mysql_fix_privilege_tables.sql",
		    "$bindir/share/mysql_fix_privilege_tables.sql",
		    "$bindir/share/mariadb/mysql_fix_privilege_tables.sql",
		    "$bindir/share/mysql/mysql_fix_privilege_tables.sql");
  $ENV{'MYSQL_FIX_PRIVILEGE_TABLES'}=  $file_mysql_fix_privilege_tables;

  # ----------------------------------------------------
  # my_print_defaults
  # ----------------------------------------------------
  my $exe_my_print_defaults=
    mtr_exe_exists("$bindir/extra$opt_vs_config/my_print_defaults",
		   "$path_client_bindir/my_print_defaults");
  $ENV{'MYSQL_MY_PRINT_DEFAULTS'}= native_path($exe_my_print_defaults);

  # ----------------------------------------------------
  # myisam tools
  # ----------------------------------------------------
  $ENV{'MYISAMLOG'}= tool_arguments("storage/myisam", "myisamlog", );
  $ENV{'MYISAMCHK'}= tool_arguments("storage/myisam", "myisamchk");
  $ENV{'MYISAMPACK'}= tool_arguments("storage/myisam", "myisampack");
  $ENV{'MYISAM_FTDUMP'}= tool_arguments("storage/myisam", "myisam_ftdump");

  # ----------------------------------------------------
  # aria tools
  # ----------------------------------------------------
  if (have_maria_support())
  {
    $ENV{'MARIA_CHK'}= tool_arguments("storage/maria", "aria_chk");
    $ENV{'MARIA_PACK'}= tool_arguments("storage/maria", "aria_pack");
  }

  # ----------------------------------------------------
  # mysqlhotcopy
  # ----------------------------------------------------
  my $mysqlhotcopy=
    mtr_pl_maybe_exists("$bindir/scripts/mysqlhotcopy") ||
    mtr_pl_maybe_exists("$path_client_bindir/mysqlhotcopy");
  if ($mysqlhotcopy)
  {
    $ENV{'MYSQLHOTCOPY'}= $mysqlhotcopy;
  }

  # ----------------------------------------------------
  # perror
  # ----------------------------------------------------
  my $exe_perror= mtr_exe_exists("$bindir/extra$opt_vs_config/perror",
				 "$path_client_bindir/perror");
  $ENV{'MY_PERROR'}= native_path($exe_perror);

  # ----------------------------------------------------
  # mysql_tzinfo_to_sql
  # ----------------------------------------------------
  my $exe_mysql_tzinfo_to_sql= mtr_exe_exists("$basedir/sql$opt_vs_config/mysql_tzinfo_to_sql",
                                 "$path_client_bindir/mysql_tzinfo_to_sql",
                                 "$bindir/sql$opt_vs_config/mysql_tzinfo_to_sql");
  $ENV{'MYSQL_TZINFO_TO_SQL'}= native_path($exe_mysql_tzinfo_to_sql);

2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398
  # ----------------------------------------------------
  # replace
  # ----------------------------------------------------
  my $exe_replace= mtr_exe_exists(vs_config_dirs('extra', 'replace'),
                                 "$basedir/extra/replace",
                                 "$bindir/extra$opt_vs_config/replace",
                                 "$path_client_bindir/replace");
  $ENV{'REPLACE'}= native_path($exe_replace);

  # ----------------------------------------------------
  # innochecksum
  # ----------------------------------------------------
  my $exe_innochecksum=
    mtr_exe_maybe_exists("$bindir/extra$opt_vs_config/innochecksum",
		         "$path_client_bindir/innochecksum");
  if ($exe_innochecksum)
  {
    $ENV{'INNOCHECKSUM'}= native_path($exe_innochecksum);
  }

2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567
  # Create an environment variable to make it possible
  # to detect that valgrind is being used from test cases
  $ENV{'VALGRIND_TEST'}= $opt_valgrind;

  # Add dir of this perl to aid mysqltest in finding perl
  my $perldir= dirname($^X);
  my $pathsep= ":";
  $pathsep= ";" if IS_WINDOWS && ! IS_CYGWIN;
  $ENV{'PATH'}= "$ENV{'PATH'}".$pathsep.$perldir;
}


sub remove_vardir_subs() {
  foreach my $sdir ( glob("$opt_vardir/*") ) {
    mtr_verbose("Removing subdir $sdir");
    rmtree($sdir);
  }
}

#
# Remove var and any directories in var/ created by previous
# tests
#
sub remove_stale_vardir () {

  mtr_report("Removing old var directory...");

  # Safety!
  mtr_error("No, don't remove the vardir when running with --extern")
    if using_extern();

  mtr_verbose("opt_vardir: $opt_vardir");
  if ( $opt_vardir eq $default_vardir )
  {
    #
    # Running with "var" in mysql-test dir
    #
    if ( -l $opt_vardir)
    {
      # var is a symlink

      if ( $opt_mem )
      {
	# Remove the directory which the link points at
	mtr_verbose("Removing " . readlink($opt_vardir));
	rmtree(readlink($opt_vardir));

	# Remove the "var" symlink
	mtr_verbose("unlink($opt_vardir)");
	unlink($opt_vardir);
      }
      else
      {
	# Some users creates a soft link in mysql-test/var to another area
	# - allow it, but remove all files in it

	mtr_report(" - WARNING: Using the 'mysql-test/var' symlink");

	# Make sure the directory where it points exist
        if (! -d readlink($opt_vardir))
        {
          mtr_report("The destination for symlink $opt_vardir does not exist; Removing it and creating a new var directory");
          unlink($opt_vardir);
        }
	remove_vardir_subs();
      }
    }
    else
    {
      # Remove the entire "var" dir
      mtr_verbose("Removing $opt_vardir/");
      rmtree("$opt_vardir/");
    }

    if ( $opt_mem )
    {
      # A symlink from var/ to $opt_mem will be set up
      # remove the $opt_mem dir to assure the symlink
      # won't point at an old directory
      mtr_verbose("Removing $opt_mem");
      rmtree($opt_mem);
    }

  }
  else
  {
    #
    # Running with "var" in some other place
    #

    # Don't remove the var/ dir in mysql-test dir as it may be in
    # use by another mysql-test-run run with --vardir
    # mtr_verbose("Removing $default_vardir");
    # rmtree($default_vardir);

    # Remove the "var" dir
    mtr_verbose("Removing $opt_vardir/");
    rmtree("$opt_vardir/");
  }
  # Remove the "tmp" dir
  mtr_verbose("Removing $opt_tmpdir/");
  rmtree("$opt_tmpdir/");
}

sub set_plugin_var($) {
  local $_ = $_[0];
  s/\.\w+$//;
  $ENV{"\U${_}_SO"} = $_[0];
}

#
# Create var and the directories needed in var
#
sub setup_vardir() {
  mtr_report("Creating var directory '$opt_vardir'...");

  if ( $opt_vardir eq $default_vardir )
  {
    #
    # Running with "var" in mysql-test dir
    #
    if ( -l $opt_vardir )
    {
      #  it's a symlink

      # Make sure the directory where it points exist
      if (! -d readlink($opt_vardir))
      {
        mtr_report("The destination for symlink $opt_vardir does not exist; Removing it and creating a new var directory");
        unlink($opt_vardir);
      }
    }
    elsif ( $opt_mem )
    {
      # Runinng with "var" as a link to some "memory" location, normally tmpfs
      mtr_verbose("Creating $opt_mem");
      mkpath($opt_mem);

      mtr_report(" - symlinking 'var' to '$opt_mem'");
      symlink($opt_mem, $opt_vardir);
    }
  }

  if ( ! -d $opt_vardir )
  {
    mtr_verbose("Creating $opt_vardir");
    mkpath($opt_vardir);
  }

  # Ensure a proper error message if vardir couldn't be created
  unless ( -d $opt_vardir and -w $opt_vardir )
  {
    mtr_error("Writable 'var' directory is needed, use the " .
	      "'--vardir=<path>' option");
  }

  mkpath("$opt_vardir/log");
  mkpath("$opt_vardir/run");

  # Create var/tmp and tmp - they might be different
  mkpath("$opt_vardir/tmp");
  mkpath($opt_tmpdir) if ($opt_tmpdir ne "$opt_vardir/tmp");

  # On some operating systems, there is a limit to the length of a
  # UNIX domain socket's path far below PATH_MAX.
  # Don't allow that to happen
  if (check_socket_path_length("$opt_tmpdir/testsocket.sock")){
    mtr_error("Socket path '$opt_tmpdir' too long, it would be ",
	      "truncated and thus not possible to use for connection to ",
2568
	      "MariaDB Server. Set a shorter with --tmpdir=<path> option");
2569 2570 2571 2572 2573 2574
  }

  # copy all files from std_data into var/std_data
  # and make them world readable
  copytree("$glob_mysql_test_dir/std_data", "$opt_vardir/std_data", "0022");

2575
  # create a plugin dir and copy or symlink plugins into it
2576 2577 2578 2579
  if ($source_dist)
  {
    $plugindir="$opt_vardir/plugins";
    mkpath($plugindir);
2580
    if (IS_WINDOWS)
2581
    {
2582
      if (!$opt_embedded_server)
2583
      {
2584 2585
        for (<$bindir/storage/*$opt_vs_config/*.dll>,
             <$bindir/plugin/*$opt_vs_config/*.dll>,
2586
             <$bindir/libmariadb$opt_vs_config/*.dll>,
2587 2588 2589 2590 2591 2592
             <$bindir/sql$opt_vs_config/*.dll>)
        {
          my $pname=basename($_);
          copy rel2abs($_), "$plugindir/$pname";
          set_plugin_var($pname);
        }
2593 2594 2595 2596
      }
    }
    else
    {
2597 2598 2599 2600 2601 2602 2603
      my $opt_use_copy= 1;
      if (symlink "$opt_vardir/run", "$plugindir/symlink_test")
      {
        $opt_use_copy= 0;
        unlink "$plugindir/symlink_test";
      }

2604
      for (<$bindir/storage/*/*.so>,
2605
           <$bindir/plugin/*/*.so>,
2606 2607
           <$bindir/libmariadb/plugins/*/*.so>,
           <$bindir/libmariadb/*.so>,
2608 2609 2610
           <$bindir/sql/*.so>)
      {
        my $pname=basename($_);
2611 2612 2613 2614 2615 2616 2617 2618
        if ($opt_use_copy)
        {
          copy rel2abs($_), "$plugindir/$pname";
        }
        else
        {
          symlink rel2abs($_), "$plugindir/$pname";
        }
2619 2620 2621 2622 2623 2624 2625 2626 2627 2628
        set_plugin_var($pname);
      }
    }
  }
  else
  {
    $plugindir= $mysqld_variables{'plugin-dir'} || '.';
    # hm, what paths work for debs and for rpms ?
    for (<$bindir/lib64/mysql/plugin/*.so>,
         <$bindir/lib/mysql/plugin/*.so>,
2629 2630
         <$bindir/lib64/mariadb/plugin/*.so>,
         <$bindir/lib/mariadb/plugin/*.so>,
2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703