selftest: Remove the 'all' environment as it is just too slow to start up
[metze/samba/wip.git] / selftest / selftest.pl
1 #!/usr/bin/perl
2 # Bootstrap Samba and run a number of tests against it.
3 # Copyright (C) 2005-2010 Jelmer Vernooij <jelmer@samba.org>
4 # Copyright (C) 2007-2009 Stefan Metzmacher <metze@samba.org>
5
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 3 of the License, or
9 # (at your option) any later version.
10
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 # GNU General Public License for more details.
15
16 # You should have received a copy of the GNU General Public License
17 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
18
19 =pod
20
21 =head1 NAME
22
23 selftest - Samba test runner
24
25 =head1 SYNOPSIS
26
27 selftest --help
28
29 selftest [--srcdir=DIR] [--bindir=DIR] [--exeext=EXT][--target=samba|samba3|win|kvm] [--socket-wrapper] [--quick] [--exclude=FILE] [--include=FILE] [--one] [--prefix=prefix] [--testlist=FILE] [TESTS]
30
31 =head1 DESCRIPTION
32
33 A simple test runner. TESTS is a regular expression with tests to run.
34
35 =head1 OPTIONS
36
37 =over 4
38
39 =item I<--help>
40
41 Show list of available options.
42
43 =item I<--srcdir=DIR>
44
45 Source directory.
46
47 =item I<--bindir=DIR>
48
49 Built binaries directory.
50
51 =item I<--exeext=EXT>
52
53 Executable extention
54
55 =item I<--prefix=DIR>
56
57 Change directory to run tests in. Default is 'st'.
58
59 =item I<--target samba|samba3|win|kvm>
60
61 Specify test target against which to run. Default is 'samba4'.
62
63 =item I<--quick>
64
65 Run only a limited number of tests. Intended to run in about 30 seconds on 
66 moderately recent systems.
67                 
68 =item I<--socket-wrapper>
69
70 Use socket wrapper library for communication with server. Only works 
71 when the server is running locally.
72
73 Will prevent TCP and UDP ports being opened on the local host but 
74 (transparently) redirects these calls to use unix domain sockets.
75
76 =item I<--exclude>
77
78 Specify a file containing a list of tests that should be skipped. Possible 
79 candidates are tests that segfault the server, flip or don't end. 
80
81 =item I<--include>
82
83 Specify a file containing a list of tests that should be run. Same format 
84 as the --exclude flag.
85
86 Not includes specified means all tests will be run.
87
88 =item I<--one>
89
90 Abort as soon as one test fails.
91
92 =item I<--testlist>
93
94 Load a list of tests from the specified location.
95
96 =back
97
98 =head1 ENVIRONMENT
99
100 =over 4
101
102 =item I<SMBD_VALGRIND>
103
104 =item I<TORTURE_MAXTIME>
105
106 =item I<VALGRIND>
107
108 =item I<TLS_ENABLED>
109
110 =item I<srcdir>
111
112 =back
113
114 =head1 LICENSE
115
116 selftest is licensed under the GNU General Public License L<http://www.gnu.org/licenses/gpl.html>.
117
118 =head1 AUTHOR
119
120 Jelmer Vernooij
121
122 =cut
123
124 use strict;
125
126 use FindBin qw($RealBin $Script);
127 use File::Spec;
128 use File::Temp qw(tempfile);
129 use Getopt::Long;
130 use POSIX;
131 use Cwd qw(abs_path);
132 use lib "$RealBin";
133 use Subunit;
134 use SocketWrapper;
135
136 eval {
137 require Time::HiRes;
138 Time::HiRes->import("time");
139 };
140 if ($@) {
141         print "You don't have Time::Hires installed !\n";
142 }
143
144 my $opt_help = 0;
145 my $opt_target = "samba";
146 my $opt_quick = 0;
147 my $opt_socket_wrapper = 0;
148 my $opt_socket_wrapper_pcap = undef;
149 my $opt_socket_wrapper_keep_pcap = undef;
150 my $opt_one = 0;
151 my @opt_exclude = ();
152 my @opt_include = ();
153 my $opt_verbose = 0;
154 my $opt_image = undef;
155 my $opt_testenv = 0;
156 my $opt_list = 0;
157 my $ldap = undef;
158 my $opt_resetup_env = undef;
159 my $opt_binary_mapping = "";
160 my $opt_load_list = undef;
161 my @testlists = ();
162
163 my $srcdir = ".";
164 my $bindir = "./bin";
165 my $exeext = "";
166 my $prefix = "./st";
167
168 my @includes = ();
169 my @excludes = ();
170
171 sub pipe_handler {
172         my $sig = shift @_;
173         print STDERR "Exiting early because of SIGPIPE.\n";
174         exit(1);
175 }
176
177 $SIG{PIPE} = \&pipe_handler;
178
179 sub find_in_list($$)
180 {
181         my ($list, $fullname) = @_;
182
183         foreach (@$list) {
184                 if ($fullname =~ /$$_[0]/) {
185                          return ($$_[1]) if ($$_[1]);
186                          return "";
187                 }
188         }
189
190         return undef;
191 }
192
193 sub skip($)
194 {
195         my ($name) = @_;
196
197         return find_in_list(\@excludes, $name);
198 }
199
200 sub getlog_env($);
201
202 sub setup_pcap($)
203 {
204         my ($name) = @_;
205
206         return unless ($opt_socket_wrapper_pcap);
207         return unless defined($ENV{SOCKET_WRAPPER_PCAP_DIR});
208
209         my $fname = $name;
210         $fname =~ s%[^abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\-]%_%g;
211
212         my $pcap_file = "$ENV{SOCKET_WRAPPER_PCAP_DIR}/$fname.pcap";
213
214         SocketWrapper::setup_pcap($pcap_file);
215
216         return $pcap_file;
217 }
218
219 sub cleanup_pcap($$)
220 {
221         my ($pcap_file, $exitcode) = @_;
222
223         return unless ($opt_socket_wrapper_pcap);
224         return if ($opt_socket_wrapper_keep_pcap);
225         return unless ($exitcode == 0);
226         return unless defined($pcap_file);
227
228         unlink($pcap_file);
229 }
230
231 # expand strings from %ENV
232 sub expand_environment_strings($)
233 {
234         my $s = shift;
235         # we use a reverse sort so we do the longer ones first
236         foreach my $k (sort { $b cmp $a } keys %ENV) {
237                 $s =~ s/\$$k/$ENV{$k}/g;
238         }
239         return $s;
240 }
241
242 sub run_testsuite($$$$$)
243 {
244         my ($envname, $name, $cmd, $i, $totalsuites) = @_;
245         my $pcap_file = setup_pcap($name);
246
247         Subunit::start_testsuite($name);
248         Subunit::progress_push();
249         Subunit::report_time(time());
250         system($cmd);
251         Subunit::report_time(time());
252         Subunit::progress_pop();
253
254         if ($? == -1) {
255                 Subunit::progress_pop();
256                 Subunit::end_testsuite($name, "error", "Unable to run $cmd: $!");
257                 exit(1);
258         } elsif ($? & 127) {
259                 Subunit::end_testsuite($name, "error",
260                         sprintf("%s died with signal %d, %s coredump\n", $cmd, ($? & 127),  ($? & 128) ? 'with' : 'without'));
261                 exit(1);
262         }
263
264         my $exitcode = $? >> 8;
265
266         my $envlog = getlog_env($envname);
267         if ($envlog ne "") {
268                 print "envlog: $envlog\n";
269         }
270
271         print "command: $cmd\n";
272         printf "expanded command: %s\n", expand_environment_strings($cmd);
273
274         if ($exitcode == 0) {
275                 Subunit::end_testsuite($name, "success");
276         } else {
277                 Subunit::end_testsuite($name, "failure", "Exit code was $exitcode");
278         }
279
280         cleanup_pcap($pcap_file, $exitcode);
281
282         if (not $opt_socket_wrapper_keep_pcap and defined($pcap_file)) {
283                 print "PCAP FILE: $pcap_file\n";
284         }
285
286         if ($exitcode != 0) {
287                 exit(1) if ($opt_one);
288         }
289
290         return $exitcode;
291 }
292
293 sub ShowHelp()
294 {
295         print "Samba test runner
296 Copyright (C) Jelmer Vernooij <jelmer\@samba.org>
297 Copyright (C) Stefan Metzmacher <metze\@samba.org>
298
299 Usage: $Script [OPTIONS] TESTNAME-REGEX
300
301 Generic options:
302  --help                     this help page
303  --target=samba[3]|win|kvm Samba version to target
304  --testlist=FILE            file to read available tests from
305
306 Paths:
307  --prefix=DIR               prefix to run tests in [st]
308  --srcdir=DIR               source directory [.]
309  --bindir=DIR               binaries directory [./bin]
310  --exeext=EXT               executable extention []
311
312 Target Specific:
313  --socket-wrapper-pcap      save traffic to pcap directories
314  --socket-wrapper-keep-pcap keep all pcap files, not just those for tests that 
315                             failed
316  --socket-wrapper           enable socket wrapper
317
318 Samba4 Specific:
319  --ldap=openldap|fedora-ds  back samba onto specified ldap server
320
321 Kvm Specific:
322  --image=PATH               path to KVM image
323
324 Behaviour:
325  --quick                    run quick overall test
326  --one                      abort when the first test fails
327  --verbose                  be verbose
328  --testenv                  run a shell in the requested test environment
329  --list                     list available tests
330 ";
331         exit(0);
332 }
333
334 my $result = GetOptions (
335                 'help|h|?' => \$opt_help,
336                 'target=s' => \$opt_target,
337                 'prefix=s' => \$prefix,
338                 'socket-wrapper' => \$opt_socket_wrapper,
339                 'socket-wrapper-pcap' => \$opt_socket_wrapper_pcap,
340                 'socket-wrapper-keep-pcap' => \$opt_socket_wrapper_keep_pcap,
341                 'quick' => \$opt_quick,
342                 'one' => \$opt_one,
343                 'exclude=s' => \@opt_exclude,
344                 'include=s' => \@opt_include,
345                 'srcdir=s' => \$srcdir,
346                 'bindir=s' => \$bindir,
347                 'exeext=s' => \$exeext,
348                 'verbose' => \$opt_verbose,
349                 'testenv' => \$opt_testenv,
350                 'list' => \$opt_list,
351                 'ldap:s' => \$ldap,
352                 'resetup-environment' => \$opt_resetup_env,
353                 'image=s' => \$opt_image,
354                 'testlist=s' => \@testlists,
355                 'load-list=s' => \$opt_load_list,
356                 'binary-mapping=s' => \$opt_binary_mapping
357             );
358
359 exit(1) if (not $result);
360
361 ShowHelp() if ($opt_help);
362
363 die("--list and --testenv are mutually exclusive") if ($opt_list and $opt_testenv);
364
365 # we want unbuffered output
366 $| = 1;
367
368 my @tests = @ARGV;
369
370 # quick hack to disable rpc validation when using valgrind - its way too slow
371 unless (defined($ENV{VALGRIND})) {
372         $ENV{VALIDATE} = "validate";
373         $ENV{MALLOC_CHECK_} = 2;
374 }
375
376 # make all our python scripts unbuffered
377 $ENV{PYTHONUNBUFFERED} = 1;
378
379 my $bindir_abs = abs_path($bindir);
380
381 # Backwards compatibility:
382 if (defined($ENV{TEST_LDAP}) and $ENV{TEST_LDAP} eq "yes") {
383         if (defined($ENV{FEDORA_DS_ROOT})) {
384                 $ldap = "fedora-ds";
385         } else {
386                 $ldap = "openldap";
387         }
388 }
389
390 my $torture_maxtime = ($ENV{TORTURE_MAXTIME} or 1200);
391 if ($ldap) {
392         # LDAP is slow
393         $torture_maxtime *= 2;
394 }
395
396 $prefix =~ s+//+/+;
397 $prefix =~ s+/./+/+;
398 $prefix =~ s+/$++;
399
400 die("using an empty prefix isn't allowed") unless $prefix ne "";
401
402 # Ensure we have the test prefix around.
403 #
404 # We need restrictive
405 # permissions on this as some subdirectories in this tree will have
406 # wider permissions (ie 0777) and this would allow other users on the
407 # host to subvert the test process.
408 mkdir($prefix, 0700) unless -d $prefix;
409 chmod 0700, $prefix;
410
411 my $prefix_abs = abs_path($prefix);
412 my $tmpdir_abs = abs_path("$prefix/tmp");
413 mkdir($tmpdir_abs, 0777) unless -d $tmpdir_abs;
414
415 my $srcdir_abs = abs_path($srcdir);
416
417 die("using an empty absolute prefix isn't allowed") unless $prefix_abs ne "";
418 die("using '/' as absolute prefix isn't allowed") unless $prefix_abs ne "/";
419
420 $ENV{PREFIX} = $prefix;
421 $ENV{KRB5CCNAME} = "$prefix/krb5ticket";
422 $ENV{PREFIX_ABS} = $prefix_abs;
423 $ENV{SRCDIR} = $srcdir;
424 $ENV{SRCDIR_ABS} = $srcdir_abs;
425 $ENV{BINDIR} = $bindir_abs;
426 $ENV{EXEEXT} = $exeext;
427
428 my $tls_enabled = not $opt_quick;
429 $ENV{TLS_ENABLED} = ($tls_enabled?"yes":"no");
430
431 sub prefix_pathvar($$)
432 {
433         my ($name, $newpath) = @_;
434         if (defined($ENV{$name})) {
435                 $ENV{$name} = "$newpath:$ENV{$name}";
436         } else {
437                 $ENV{$name} = $newpath;
438         }
439 }
440 prefix_pathvar("PKG_CONFIG_PATH", "$bindir_abs/pkgconfig");
441 prefix_pathvar("PYTHONPATH", "$bindir_abs/python");
442
443 if ($opt_socket_wrapper_keep_pcap) {
444         # Socket wrapper keep pcap implies socket wrapper pcap
445         $opt_socket_wrapper_pcap = 1;
446 }
447
448 if ($opt_socket_wrapper_pcap) {
449         # Socket wrapper pcap implies socket wrapper
450         $opt_socket_wrapper = 1;
451 }
452
453 my $socket_wrapper_dir;
454 if ($opt_socket_wrapper) {
455         $socket_wrapper_dir = SocketWrapper::setup_dir("$prefix_abs/w", $opt_socket_wrapper_pcap);
456         print "SOCKET_WRAPPER_DIR=$socket_wrapper_dir\n";
457 } else {
458          unless ($< == 0) { 
459                  print "WARNING: Not using socket wrapper, but also not running as root. Will not be able to listen on proper ports\n";
460          }
461 }
462
463 my $target;
464 my $testenv_default = "none";
465
466 my %binary_mapping = ();
467 if ($opt_binary_mapping) {
468     my @binmapping_list = split(/,/, $opt_binary_mapping);
469     foreach my $mapping (@binmapping_list) {
470         my ($bin, $map) = split(/\:/, $mapping);
471         $binary_mapping{$bin} = $map;
472     }
473 }
474
475 $ENV{BINARY_MAPPING} = $opt_binary_mapping;
476
477 # After this many seconds, the server will self-terminate.  All tests
478 # must terminate in this time, and testenv will only stay alive this
479 # long
480
481 my $server_maxtime = 7500;
482 if (defined($ENV{SMBD_MAXTIME}) and $ENV{SMBD_MAXTIME} ne "") {
483     $server_maxtime = $ENV{SMBD_MAXTIME};
484 }
485
486 if ($opt_target eq "samba") {
487         if ($opt_socket_wrapper and `$bindir/smbd -b | grep SOCKET_WRAPPER` eq "") {
488                 die("You must include --enable-socket-wrapper when compiling Samba in order to execute 'make test'.  Exiting....");
489         }
490         $testenv_default = "dc";
491         require target::Samba;
492         $target = new Samba($bindir, \%binary_mapping, $ldap, $srcdir, $exeext, $server_maxtime);
493 } elsif ($opt_target eq "samba3") {
494         if ($opt_socket_wrapper and `$bindir/smbd -b | grep SOCKET_WRAPPER` eq "") {
495                 die("You must include --enable-socket-wrapper when compiling Samba in order to execute 'make test'.  Exiting....");
496         }
497         $testenv_default = "member";
498         require target::Samba3;
499         $target = new Samba3($bindir, \%binary_mapping, $srcdir_abs, $exeext, $server_maxtime);
500 } elsif ($opt_target eq "win") {
501         die("Windows tests will not run with socket wrapper enabled.") 
502                 if ($opt_socket_wrapper);
503         $testenv_default = "dc";
504         require target::Windows;
505         $target = new Windows();
506 } elsif ($opt_target eq "kvm") {
507         die("Kvm tests will not run with socket wrapper enabled.") 
508                 if ($opt_socket_wrapper);
509         require target::Kvm;
510         die("No image specified") unless ($opt_image);
511         $target = new Kvm($opt_image, undef);
512 }
513
514 #
515 # Start a Virtual Distributed Ethernet Switch
516 # Returns the pid of the switch.
517 #
518 sub start_vde_switch($)
519 {
520         my ($path) = @_;
521
522         system("vde_switch --pidfile $path/vde.pid --sock $path/vde.sock --daemon");
523
524         open(PID, "$path/vde.pid");
525         <PID> =~ /([0-9]+)/;
526         my $pid = $1;
527         close(PID);
528
529         return $pid;
530 }
531
532 # Stop a Virtual Distributed Ethernet Switch
533 sub stop_vde_switch($)
534 {
535         my ($pid) = @_;
536         kill 9, $pid;
537 }
538
539 sub read_test_regexes($)
540 {
541         my ($name) = @_;
542         my @ret = ();
543         open(LF, "<$name") or die("unable to read $name: $!");
544         while (<LF>) { 
545                 chomp; 
546                 next if (/^#/);
547                 if (/^(.*?)([ \t]+)\#([\t ]*)(.*?)$/) {
548                         push (@ret, [$1, $4]);
549                 } else {
550                         s/^(.*?)([ \t]+)\#([\t ]*)(.*?)$//;
551                         push (@ret, [$_, undef]); 
552                 }
553         }
554         close(LF);
555         return @ret;
556 }
557
558 foreach (@opt_exclude) {
559         push (@excludes, read_test_regexes($_));
560 }
561
562 foreach (@opt_include) {
563         push (@includes, read_test_regexes($_));
564 }
565
566 my $interfaces = join(',', ("127.0.0.11/8",
567                             "127.0.0.12/8",
568                             "127.0.0.13/8",
569                             "127.0.0.14/8",
570                             "127.0.0.15/8",
571                             "127.0.0.16/8"));
572
573 my $clientdir = "$prefix_abs/client";
574
575 my $conffile = "$clientdir/client.conf";
576 $ENV{SMB_CONF_PATH} = $conffile;
577
578 sub write_clientconf($$$)
579 {
580         my ($conffile, $clientdir, $vars) = @_;
581
582         mkdir("$clientdir", 0777) unless -d "$clientdir";
583
584         if ( -d "$clientdir/private" ) {
585                 unlink <$clientdir/private/*>;
586         } else {
587                 mkdir("$clientdir/private", 0777);
588         }
589
590         if ( -d "$clientdir/lockdir" ) {
591                 unlink <$clientdir/lockdir/*>;
592         } else {
593                 mkdir("$clientdir/lockdir", 0777);
594         }
595
596         if ( -d "$clientdir/statedir" ) {
597                 unlink <$clientdir/statedir/*>;
598         } else {
599                 mkdir("$clientdir/statedir", 0777);
600         }
601
602         if ( -d "$clientdir/cachedir" ) {
603                 unlink <$clientdir/cachedir/*>;
604         } else {
605                 mkdir("$clientdir/cachedir", 0777);
606         }
607
608         # this is ugly, but the ncalrpcdir needs exactly 0755
609         # otherwise tests fail.
610         my $mask = umask;
611         umask 0022;
612         if ( -d "$clientdir/ncalrpcdir/np" ) {
613                 unlink <$clientdir/ncalrpcdir/np/*>;
614                 rmdir "$clientdir/ncalrpcdir/np";
615         }
616         if ( -d "$clientdir/ncalrpcdir" ) {
617                 unlink <$clientdir/ncalrpcdir/*>;
618                 rmdir "$clientdir/ncalrpcdir";
619         }
620         mkdir("$clientdir/ncalrpcdir", 0755);
621         umask $mask;
622
623         open(CF, ">$conffile");
624         print CF "[global]\n";
625         print CF "\tnetbios name = client\n";
626         if (defined($vars->{DOMAIN})) {
627                 print CF "\tworkgroup = $vars->{DOMAIN}\n";
628         }
629         if (defined($vars->{REALM})) {
630                 print CF "\trealm = $vars->{REALM}\n";
631         }
632         if ($opt_socket_wrapper) {
633                 print CF "\tinterfaces = $interfaces\n";
634         }
635         print CF "
636         private dir = $clientdir/private
637         lock dir = $clientdir/lockdir
638         state directory = $clientdir/statedir
639         cache directory = $clientdir/cachedir
640         ncalrpc dir = $clientdir/ncalrpcdir
641         name resolve order = file bcast
642         panic action = $RealBin/gdb_backtrace \%d
643         max xmit = 32K
644         notify:inotify = false
645         ldb:nosync = true
646         system:anonymous = true
647         client lanman auth = Yes
648         log level = 1
649         torture:basedir = $clientdir
650 #We don't want to pass our self-tests if the PAC code is wrong
651         gensec:require_pac = true
652         resolv:host file = $prefix_abs/dns_host_file
653 #We don't want to run 'speed' tests for very long
654         torture:timelimit = 1
655 ";
656         close(CF);
657 }
658
659 my @todo = ();
660
661 sub should_run_test($)
662 {
663         my $name = shift;
664         if ($#tests == -1) {
665                 return 1;
666         }
667         for (my $i=0; $i <= $#tests; $i++) {
668                 if ($name =~ /$tests[$i]/i) {
669                         return 1;
670                 }
671         }
672         return 0;
673 }
674
675 sub read_testlist($)
676 {
677         my ($filename) = @_;
678
679         my @ret = ();
680         open(IN, $filename) or die("Unable to open $filename: $!");
681
682         while (<IN>) {
683                 if (/-- TEST(-LOADLIST|-IDLIST|) --\n/) {
684                         my $supports_loadlist = (defined($1) and $1 eq "-LOADLIST");
685                         my $supports_idlist = (defined($1) and $1 eq "-IDLIST");
686                         my $name = <IN>;
687                         $name =~ s/\n//g;
688                         my $env = <IN>;
689                         $env =~ s/\n//g;
690                         my $cmdline = <IN>;
691                         $cmdline =~ s/\n//g;
692                         if (should_run_test($name) == 1) {
693                                 push (@ret, [$name, $env, $cmdline, $supports_loadlist, $supports_idlist]);
694                         }
695                 } else {
696                         print;
697                 }
698         }
699         close(IN) or die("Error creating recipe");
700         return @ret;
701 }
702
703 if ($#testlists == -1) {
704         die("No testlists specified");
705 }
706
707 $ENV{SELFTEST_PREFIX} = "$prefix_abs";
708 $ENV{SELFTEST_TMPDIR} = "$tmpdir_abs";
709 $ENV{TEST_DATA_PREFIX} = "$tmpdir_abs";
710 if ($opt_socket_wrapper) {
711         $ENV{SELFTEST_INTERFACES} = $interfaces;
712 } else {
713         $ENV{SELFTEST_INTERFACES} = "";
714 }
715 if ($opt_verbose) {
716         $ENV{SELFTEST_VERBOSE} = "1";
717 } else {
718         $ENV{SELFTEST_VERBOSE} = "";
719 }
720 if ($opt_quick) {
721         $ENV{SELFTEST_QUICK} = "1";
722 } else {
723         $ENV{SELFTEST_QUICK} = "";
724 }
725 $ENV{SELFTEST_MAXTIME} = $torture_maxtime;
726
727 my @available = ();
728 foreach my $fn (@testlists) {
729         foreach (read_testlist($fn)) {
730                 my $name = $$_[0];
731                 next if (@includes and not defined(find_in_list(\@includes, $name)));
732                 push (@available, $_);
733         }
734 }
735
736 my $restricted = undef;
737 my $restricted_used = {};
738
739 if ($opt_load_list) {
740         $restricted = [];
741         open(LOAD_LIST, "<$opt_load_list") or die("Unable to open $opt_load_list");
742         while (<LOAD_LIST>) {
743                 chomp;
744                 push (@$restricted, $_);
745         }
746         close(LOAD_LIST);
747 }
748
749 my $individual_tests = undef;
750 $individual_tests = {};
751
752 foreach my $testsuite (@available) {
753         my $name = $$testsuite[0];
754         my $skipreason = skip($name);
755         if (defined($restricted)) {
756                 # Find the testsuite for this test
757                 my $match = undef;
758                 foreach my $r (@$restricted) {
759                         if ($r eq $name) {
760                                 $individual_tests->{$name} = [];
761                                 $match = $r;
762                                 $restricted_used->{$r} = 1;
763                         } elsif (substr($r, 0, length($name)+1) eq "$name.") {
764                                 push(@{$individual_tests->{$name}}, $r);
765                                 $match = $r;
766                                 $restricted_used->{$r} = 1;
767                         }
768                 }
769                 if ($match) {
770                         if (defined($skipreason)) {
771                                         Subunit::skip_testsuite($name, $skipreason);
772                         } else {
773                                 push(@todo, $testsuite);
774                         }
775                 }
776         } elsif (defined($skipreason)) {
777                 Subunit::skip_testsuite($name, $skipreason);
778         } else {
779                 push(@todo, $testsuite);
780         }
781 }
782
783 if (defined($restricted)) {
784         foreach (@$restricted) {
785                 unless (defined($restricted_used->{$_})) {
786                         print "No test or testsuite found matching $_\n";
787                 }
788         }
789 } elsif ($#todo == -1) {
790         print STDERR "No tests to run\n";
791         exit(1);
792 }
793
794 my $suitestotal = $#todo + 1;
795
796 Subunit::progress($suitestotal);
797 Subunit::report_time(time());
798
799 my $i = 0;
800 $| = 1;
801
802 my %running_envs = ();
803
804 sub get_running_env($)
805 {
806         my ($name) = @_;
807
808         my $envname = $name;
809
810         $envname =~ s/:.*//;
811
812         return $running_envs{$envname};
813 }
814
815 my @exported_envvars = (
816         # domain stuff
817         "DOMAIN",
818         "REALM",
819
820         # domain controller stuff
821         "DC_SERVER",
822         "DC_SERVER_IP",
823         "DC_NETBIOSNAME",
824         "DC_NETBIOSALIAS",
825
826         # domain member
827         "MEMBER_SERVER",
828         "MEMBER_SERVER_IP",
829         "MEMBER_NETBIOSNAME",
830         "MEMBER_NETBIOSALIAS",
831
832         # rpc proxy controller stuff
833         "RPC_PROXY_SERVER",
834         "RPC_PROXY_SERVER_IP",
835         "RPC_PROXY_NETBIOSNAME",
836         "RPC_PROXY_NETBIOSALIAS",
837
838         # domain controller stuff for Vampired DC
839         "VAMPIRE_DC_SERVER",
840         "VAMPIRE_DC_SERVER_IP",
841         "VAMPIRE_DC_NETBIOSNAME",
842         "VAMPIRE_DC_NETBIOSALIAS",
843
844         # server stuff
845         "SERVER",
846         "SERVER_IP",
847         "NETBIOSNAME",
848         "NETBIOSALIAS",
849
850         # user stuff
851         "USERNAME",
852         "USERID",
853         "PASSWORD",
854         "DC_USERNAME",
855         "DC_PASSWORD",
856
857         # misc stuff
858         "KRB5_CONFIG",
859         "WINBINDD_SOCKET_DIR",
860         "WINBINDD_PRIV_PIPE_DIR",
861         "NMBD_SOCKET_DIR",
862         "LOCAL_PATH"
863 );
864
865 $SIG{INT} = $SIG{QUIT} = $SIG{TERM} = sub { 
866         my $signame = shift;
867         teardown_env($_) foreach(keys %running_envs);
868         die("Received signal $signame");
869 };
870
871 sub setup_env($$)
872 {
873         my ($name, $prefix) = @_;
874
875         my $testenv_vars = undef;
876
877         my $envname = $name;
878         my $option = $name;
879
880         $envname =~ s/:.*//;
881         $option =~ s/^[^:]*//;
882         $option =~ s/^://;
883
884         $option = "client" if $option eq "";
885
886         if ($envname eq "none") {
887                 $testenv_vars = {};
888         } elsif (defined(get_running_env($envname))) {
889                 $testenv_vars = get_running_env($envname);
890                 if (not $testenv_vars->{target}->check_env($testenv_vars)) {
891                         print $testenv_vars->{target}->getlog_env($testenv_vars);
892                         $testenv_vars = undef;
893                 }
894         } else {
895                 $testenv_vars = $target->setup_env($envname, $prefix);
896                 if (defined($testenv_vars) && not defined($testenv_vars->{target})) {
897                         $testenv_vars->{target} = $target;
898                 }
899                 if (not defined($testenv_vars)) {
900                         warn("$opt_target can't provide environment '$envname'");
901                 }
902         }
903
904         
905         return undef unless defined($testenv_vars);
906
907         $running_envs{$envname} = $testenv_vars;
908
909         if ($option eq "local") {
910                 SocketWrapper::set_default_iface($testenv_vars->{SOCKET_WRAPPER_DEFAULT_IFACE});
911                 $ENV{SMB_CONF_PATH} = $testenv_vars->{SERVERCONFFILE};
912         } elsif ($option eq "client") {
913                 SocketWrapper::set_default_iface(11);
914                 write_clientconf($conffile, $clientdir, $testenv_vars);
915                 $ENV{SMB_CONF_PATH} = $conffile;
916         } else {
917                 die("Unknown option[$option] for envname[$envname]");
918         }
919
920         foreach (@exported_envvars) {
921                 if (defined($testenv_vars->{$_})) {
922                         $ENV{$_} = $testenv_vars->{$_};
923                 } else {
924                         delete $ENV{$_};
925                 }
926         }
927
928         return $testenv_vars;
929 }
930
931 sub exported_envvars_str($)
932 {
933         my ($testenv_vars) = @_;
934         my $out = "";
935
936         foreach (@exported_envvars) {
937                 next unless defined($testenv_vars->{$_});
938                 $out .= $_."=".$testenv_vars->{$_}."\n";
939         }
940
941         return $out;
942 }
943
944 sub getlog_env($)
945 {
946         my ($envname) = @_;
947         return "" if ($envname eq "none");
948         my $env = get_running_env($envname);
949         return $env->{target}->getlog_env($env);
950 }
951
952 sub check_env($)
953 {
954         my ($envname) = @_;
955         return 1 if ($envname eq "none");
956         my $env = get_running_env($envname);
957         return $env->{target}->check_env($env);
958 }
959
960 sub teardown_env($)
961 {
962         my ($envname) = @_;
963         return if ($envname eq "none");
964         my $env = get_running_env($envname);
965         $env->{target}->teardown_env($env);
966         delete $running_envs{$envname};
967 }
968
969 # This 'global' file needs to be empty when we start
970 unlink("$prefix_abs/dns_host_file");
971
972 if ($opt_testenv) {
973         my $testenv_name = $ENV{SELFTEST_TESTENV};
974         $testenv_name = $testenv_default unless defined($testenv_name);
975
976         my $testenv_vars = setup_env($testenv_name, $prefix);
977
978         die("Unable to setup environment $testenv_name") unless ($testenv_vars);
979
980         $ENV{PIDDIR} = $testenv_vars->{PIDDIR};
981         $ENV{ENVNAME} = $testenv_name;
982
983         my $envvarstr = exported_envvars_str($testenv_vars);
984
985         my $term = ($ENV{TERMINAL} or "xterm -e");
986         system("$term 'echo -e \"
987 Welcome to the Samba4 Test environment '$testenv_name'
988
989 This matches the client environment used in make test
990 server is pid `cat \$PIDDIR/samba.pid`
991
992 Some useful environment variables:
993 TORTURE_OPTIONS=\$TORTURE_OPTIONS
994 SMB_CONF_PATH=\$SMB_CONF_PATH
995
996 $envvarstr
997 \" && LD_LIBRARY_PATH=$ENV{LD_LIBRARY_PATH} bash'");
998         teardown_env($testenv_name);
999 } elsif ($opt_list) {
1000         foreach (@todo) {
1001                 my $cmd = $$_[2];
1002                 my $name = $$_[0];
1003                 my $envname = $$_[1];
1004
1005                 unless($cmd =~ /\$LISTOPT/) {
1006                         warn("Unable to list tests in $name");
1007                         next;
1008                 }
1009
1010                 $cmd =~ s/\$LISTOPT/--list/g;
1011
1012                 system($cmd);
1013
1014                 if ($? == -1) {
1015                         die("Unable to run $cmd: $!");
1016                 } elsif ($? & 127) {
1017                         die(snprintf("%s died with signal %d, %s coredump\n", $cmd, ($? & 127),  ($? & 128) ? 'with' : 'without'));
1018                 }
1019
1020                 my $exitcode = $? >> 8;
1021                 if ($exitcode != 0) {
1022                         die("$cmd exited with exit code $exitcode");
1023                 }
1024         }
1025 } else {
1026         foreach (@todo) {
1027                 $i++;
1028                 my $cmd = $$_[2];
1029                 my $name = $$_[0];
1030                 my $envname = $$_[1];
1031
1032                 my $envvars = setup_env($envname, $prefix);
1033                 if (not defined($envvars)) {
1034                         Subunit::start_testsuite($name);
1035                         Subunit::end_testsuite($name, "error",
1036                                 "unable to set up environment $envname - exiting");
1037                         next;
1038                 }
1039
1040                 # Generate a file with the individual tests to run, if the 
1041                 # test runner for this test suite supports it.
1042                 if ($individual_tests and $individual_tests->{$name}) {
1043                         if ($$_[3]) {
1044                                 my ($fh, $listid_file) = tempfile(UNLINK => 0);
1045                                 foreach my $test (@{$individual_tests->{$name}}) {
1046                                         print $fh substr($test, length($name)+1) . "\n";
1047                                 }
1048                                 $cmd =~ s/\$LOADLIST/--load-list=$listid_file/g;
1049                         } elsif ($$_[4]) {
1050                                 $cmd =~ s/\s+[^\s]+\s*$//;
1051                                 $cmd .= " " . join(' ', @{$individual_tests->{$name}});
1052                         }
1053                 }
1054
1055                 run_testsuite($envname, $name, $cmd, $i, $suitestotal);
1056
1057                 teardown_env($envname) if ($opt_resetup_env);
1058         }
1059 }
1060
1061 print "\n";
1062
1063 teardown_env($_) foreach (keys %running_envs);
1064
1065 my $failed = 0;
1066
1067 # if there were any valgrind failures, show them
1068 foreach (<$prefix/valgrind.log*>) {
1069         next unless (-s $_);
1070         print "VALGRIND FAILURE\n";
1071         $failed++;
1072         system("cat $_");
1073 }
1074 exit 0;