Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Add option -wrapper to mpich3 runtests.
[simgrid.git] / teshsuite / smpi / mpich3-test / runtests
1 #! /usr/bin/env perl
2 # -*- Mode: perl; -*-
3 #
4 # This script is the beginnings of a script to run a sequence of test
5 # programs.  See the MPICH document for a description of the test
6 # strategy and requirements.
7 #
8 # Description
9 #   Tests are controlled by a file listing test programs; if the file is
10 #   a directory, then all of the programs in the directory and subdirectories
11 #   are run
12 #
13 #   To run a test, the following steps are executed
14 #   Build the executable:
15 #      make programname
16 #   Run the executable
17 #      mpiexec -n <np> ./programname >out 2>err
18 #   Check the return code (non zero is failure)
19 #   Check the stderr output (non empty is failure)
20 #   Check the stdout output (No Errors or Test passed are the only valid
21 #      output)
22 #   Remove executable, out, err files
23 #
24 # The format of a list file is
25 # programname number-of-processes
26 # If number-of-processes is missing, $np_default is used (this is 2 but can
27 # be overridden with -np=new-value)
28 #
29 # Special feature:
30 # Because these tests can take a long time to run, there is an
31 # option to cause the tests to stop is a "stopfile" is found.
32 # The stopfile can be created by a separate, watchdog process, to ensure that
33 # tests end at a certain time.
34 # The name of this file is (by default) .stoptest
35 # in the  top-level run directory.  The environment variable
36 #    MPITEST_STOPTEST
37 # can specify a different file name.
38 #
39 # Import the mkpath command
40 use File::Path;
41
42 # Global variables
43 $MPIMajorVersion = "2";
44 $MPIMinorVersion = "2";
45 $mpiexec = "smpirun";    # Name of mpiexec program (including path, if necessary)
46 $testIsStrict = "true";
47 $MPIhasMPIX   = "no";
48 $np_arg  = "-np";         # Name of argument to specify the number of processes
49 $err_count = 0;          # Number of programs that failed.
50 $total_run = 0;          # Number of programs tested
51 $total_seen = 0;         # Number of programs considered for testing
52 $np_default = 2;         # Default number of processes to use
53 $np_max     = -1;        # Maximum number of processes to use (overrides any
54                          # value in the test list files.  -1 is Infinity
55 $defaultTimeLimit = 180; # default timeout
56
57 $srcdir = ".";           # Used to set the source dir for testlist files
58
59 $curdir = ".";           # used to track the relative current directory
60
61 # Output forms
62 $xmloutput = 0;          # Set to true to get xml output (also specify file)
63 $closeXMLOutput = 1;     # Set to false to leave XML output file open to
64                          # accept additional data
65 $verbose = 1;            # Set to true to get more output
66 $showProgress = 0;       # Set to true to get a "." with each run program.
67 $newline = "\r\n";       # Set to \r\n for Windows-friendly, \n for Unix only
68 $batchRun = 0;           # Set to true to batch the execution of the tests
69                          # (i.e., run them together, then test output,
70                          # rather than build/run/check for each test)
71 $testCount = 0;          # Used with batchRun to count tests.
72 $batrundir = ".";        # Set to the directory into which to run the examples
73
74 $execarg="";
75 $wrapparg="";
76
77 $enabled_privatization = 1; # disable tests that need SMPI privatization to run
78 # TAP (Test Anything Protocol) output
79 my $tapoutput = 0;
80 my $tapfile = '';
81 my $tapfullfile = '';
82
83 $debug = 1;
84
85 $depth = 0;              # This is used to manage multiple open list files
86
87 # Build flags
88 $remove_this_pgm = 0;
89 $clean_pgms      = 0;
90
91 my $program_wrapper = '';
92
93 #---------------------------------------------------------------------------
94 # Get some arguments from the environment
95 #   Currently, only the following are understood:
96 #   VERBOSE
97 #   RUNTESTS_VERBOSE  (an alias for VERBOSE in case you want to
98 #                      reserve VERBOSE)
99 #   RUNTESTS_SHOWPROGRESS
100 #   MPITEST_STOPTEST
101 #   MPITEST_TIMEOUT
102 #   MPITEST_PROGRAM_WRAPPER (Value is added after -np but before test
103 #                            executable.  Tools like valgrind may be inserted
104 #                            this way.)
105 #---------------------------------------------------------------------------
106 if ( defined($ENV{"VERBOSE"}) || defined($ENV{"V"}) || defined($ENV{"RUNTESTS_VERBOSE"}) ) {
107     $verbose = 1;
108 }
109 if ( defined($ENV{"RUNTESTS_SHOWPROGRESS"} ) ) {
110     $showProgress = 1;
111 }
112 if (defined($ENV{"MPITEST_STOPTEST"})) {
113     $stopfile = $ENV{"MPITEST_STOPTEST"};
114 }
115 else {
116     $stopfile = `pwd` . "/.stoptest";
117     $stopfile =~ s/\r*\n*//g;    # Remove any newlines (from pwd)
118 }
119
120 if (defined($ENV{"MPITEST_TIMEOUT"})) {
121     $defaultTimeLimit = $ENV{"MPITEST_TIMEOUT"};
122 }
123
124 # Define this to leave the XML output file open to receive additional data
125 if (defined($ENV{'NOXMLCLOSE'}) && $ENV{'NOXMLCLOSE'} eq 'YES') {
126     $closeXMLOutput = 0;
127 }
128
129 if (defined($ENV{'MPITEST_PROGRAM_WRAPPER'})) {
130     $program_wrapper = $ENV{'MPITEST_PROGRAM_WRAPPER'};
131 }
132
133 if (defined($ENV{'MPITEST_BATCH'})) {
134     if ($ENV{'MPITEST_BATCH'} eq 'YES' || $ENV{'MPITEST_BATCH'} eq 'yes') {
135         $batchRun = 1;
136     } elsif ($ENV{'MPITEST_BATCH'} eq 'NO' || $ENV{'MPITEST_BATCH'} eq 'no') {
137         $batchRun = 0;
138     }
139     else {
140         print STDERR "Unrecognized value for MPITEST_BATCH = $ENV{'MPITEST_BATCH'}\n";
141     }
142 }
143 if (defined($ENV{'MPITEST_BATCHDIR'})) {
144     $batrundir = $ENV{'MPITEST_BATCHDIR'};
145 }
146
147 #---------------------------------------------------------------------------
148 # Process arguments and override any defaults
149 #---------------------------------------------------------------------------
150 foreach $_ (@ARGV) {
151     if (/--?mpiexec=(.*)/) {
152         # Use mpiexec as given - it may be in the path, and
153         # we don't want to bother to try and find it.
154         $mpiexec = $1;
155     }
156     elsif (/--?np=(.*)/)   { $np_default = $1; }
157     elsif (/--?maxnp=(.*)/) { $np_max = $1; }
158     elsif (/--?tests=(.*)/) { $listfiles = $1; }
159     elsif (/--?srcdir=(.*)/) { $srcdir = $1;
160         $mpiexec="$mpiexec  -platform ${srcdir}/../../../../examples/platforms/small_platform_with_routers.xml -hostfile ${srcdir}/../../hostfile_coll --log=root.thr:critical --cfg=smpi/host-speed:1e9  --cfg=smpi/async-small-thresh:65536"; }
161     elsif (/--?verbose/) { $verbose = 1; }
162     elsif (/--?showprogress/) { $showProgress = 1; }
163     elsif (/--?debug/) { $debug = 1; }
164     elsif (/--?batch/) { $batchRun = 1; }
165     elsif (/--?batchdir=(.*)/) { $batrundir = $1; }
166     elsif (/--?timeoutarg=(.*)/) { $timeoutArgPattern = $1; }
167     elsif (/--?execarg=(.*)/) { $execarg = "$execarg $1"; }
168     elsif (/--?privatization=(.*)/) { 
169 print STDERR "privatization called\n";
170 $enabled_privatization = $1; }
171     elsif (/--?wrapper=(.*)/) {
172          $wrapparg = "-wrapper \"$1\"" if $1 ne "";
173     }
174     elsif (/--?xmlfile=(.*)/) {
175         $xmlfile   = $1;
176         if (! ($xmlfile =~ /^\//)) {
177             $thisdir = `pwd`;
178             chop $thisdir;
179             $xmlfullfile = $thisdir . "/" . $xmlfile ;
180         }
181         else {
182             $xmlfullfile = $xmlfile;
183         }
184         $xmloutput = 1;
185         open( XMLOUT, ">$xmlfile" ) || die "Cannot open $xmlfile\n";
186         my $date = `date "+%Y-%m-%d-%H-%M"`;
187         $date =~ s/\r?\n//;
188         # MPISOURCE can be used to describe the source of MPI for this
189         # test.
190         print XMLOUT "<?xml version='1.0' ?>$newline";
191         print XMLOUT "<?xml-stylesheet href=\"TestResults.xsl\" type=\"text/xsl\" ?>$newline";
192         print XMLOUT "<MPITESTRESULTS>$newline";
193         print XMLOUT "<DATE>$date</DATE>$newline";
194         print XMLOUT "<MPISOURCE></MPISOURCE>$newline";
195     }
196     elsif (/--?noxmlclose/) {
197         $closeXMLOutput = 0;
198     }
199     elsif (/--?tapfile=(.*)/) {
200         $tapfile = $1;
201         if ($tapfile !~ m|^/|) {
202             $thisdir = `pwd`;
203             chomp $thisdir;
204             $tapfullfile = $thisdir . "/" . $tapfile ;
205         }
206         else {
207             $tapfullfile = $tapfile;
208         }
209         $tapoutput = 1;
210         open( TAPOUT, ">$tapfile" ) || die "Cannot open $tapfile\n";
211         my $date = `date "+%Y-%m-%d-%H-%M"`;
212         $date =~ s/\r?\n//;
213         print TAPOUT "TAP version 13\n";
214         print TAPOUT "# MPICH test suite results (TAP format)\n";
215         print TAPOUT "# date ${date}\n";
216         # we do not know at this point how many tests will be run, so do
217         # not print a test plan line like "1..450" until the very end
218     }
219 }
220
221 # Perform any post argument processing
222 if ($batchRun) {
223     if (! -d $batrundir) {
224         mkpath $batrundir || die "Could not create $batrundir\n";
225     }
226     open( BATOUT, ">$batrundir/runtests.batch" ) || die "Could not open $batrundir/runtests.batch\n";
227 }
228 else {
229     # We must have mpiexec
230     if ("$mpiexec" eq "") {
231         print STDERR "No mpiexec found!\n";
232         exit(1);
233     }
234 }
235
236 #
237 # Process any files
238 if ($listfiles eq "") {
239     if ($batchRun) {
240         print STDERR "An implicit list of tests is not permitted in batch mode\n";
241         exit(1);
242     }
243     else {
244         &ProcessImplicitList;
245     }
246 }
247 elsif (-d $listfiles) {
248     print STDERR "Testing by directories not yet supported\n";
249 }
250 else {
251     &RunList( $listfiles );
252 }
253
254 if ($xmloutput && $closeXMLOutput) {
255     print XMLOUT "</MPITESTRESULTS>$newline";
256     close XMLOUT;
257 }
258
259 if ($tapoutput) {
260     print TAPOUT "1..$total_seen\n";
261     close TAPOUT;
262 }
263
264 # Output a summary:
265 if ($batchRun) {
266     print "Programs created along with a runtest.batch file in $batrundir\n";
267     print "Run that script and then use checktests to summarize the results\n";
268 }
269 else {
270     if ($err_count) {
271         print "$err_count tests failed out of $total_run\n";
272         print "Failing tests : $failed_tests\n";
273         if ($xmloutput) {
274             print "Details in $xmlfullfile\n";
275         }
276     }
277     else {
278         print " All $total_run tests passed!\n";
279     }
280     if ($tapoutput) {
281         print "TAP formatted results in $tapfullfile\n";
282     }
283 }
284 exit ($err_count > 0);
285 #\f
286 # ---------------------------------------------------------------------------
287 # Routines
288 #
289 # Enter a new directory and process a list file.
290 #  ProcessDir( directory-name, list-file-name )
291 sub ProcessDir {
292     my $dir = $_[0]; $dir =~ s/\/$//;
293     my $listfile = $_[1];
294     my $savedir = `pwd`;
295     my $savecurdir = $curdir;
296     my $savesrcdir = $srcdir;
297
298     chop $savedir;
299     if (substr($srcdir,0,3) eq "../") {
300       $srcdir = "../$srcdir";
301     }
302
303     print "Processing directory $dir\n" if ($verbose || $debug);
304     chdir $dir;
305     if ($dir =~ /\//) {
306         print STDERR "only direct subdirectories allowed in list files";
307     }
308     $curdir .= "/$dir";
309
310     &RunList( $listfile );
311     print "\n" if $showProgress; # Terminate line from progress output
312     chdir $savedir;
313     $curdir = $savecurdir;
314     $srcdir = $savesrcdir;
315 }
316 # ---------------------------------------------------------------------------
317 # Run the programs listed in the file given as the argument.
318 # This file describes the tests in the format
319 #  programname number-of-processes [ key=value ... ]
320 # If the second value is not given, the default value is used.
321 #
322 sub RunList {
323     my $LIST = "LIST$depth"; $depth++;
324     my $listfile = $_[0];
325     my $ResultTest = "";
326     my $InitForRun = "";
327     my $listfileSource = $listfile;
328
329     print "Looking in $curdir/$listfile\n" if $debug;
330     if (! -s "$listfile" && -s "$srcdir/$curdir/$listfile" ) {
331         $listfileSource = "$srcdir/$curdir/$listfile";
332     }
333     open( $LIST, "<$listfileSource" ) ||
334         die "Could not open $listfileSource\n";
335     while (<$LIST>) {
336         # Check for stop file
337         if (-s $stopfile) {
338             # Exit because we found a stopfile
339             print STDERR "Terminating test because stopfile $stopfile found\n";
340             last;
341         }
342         # Skip comments
343         s/#.*//g;
344         # Remove any trailing newlines/returns
345         s/\r?\n//;
346         # Remove any leading whitespace
347         s/^\s*//;
348         # Some tests require that support routines are built first
349         # This is specified with !<dir>:<target>
350         if (/^\s*\!([^:]*):(.*)/) {
351             # Hack: just execute in a subshell.  This discards any
352             # output.
353             `cd $1 && make $2`;
354             next;
355         }
356         # List file entries have the form:
357         # program [ np [ name=value ... ] ]
358         # See files errhan/testlist, init/testlist, and spawn/testlist
359         # for examples of using the key=value form
360         my @args = split(/\s+/,$_);
361         my $programname = $args[0];
362         my $np = "";
363         my $ResultTest = "";
364         my $InitForRun = "";
365         my $timeLimit  = "";
366         my $progArgs   = "";
367         my $mpiexecArgs = "$execarg";
368         my $requiresStrict = "";
369         my $requiresMPIX   = "";
370         my $progEnv    = "";
371         my $mpiVersion = "";
372         my $needs_privatization = 0;
373         my $xfail = "";
374         if ($#args >= 1) { $np = $args[1]; }
375         # Process the key=value arguments
376         for (my $i=2; $i <= $#args; $i++) {
377             if ($args[$i] =~ /([^=]+)=(.*)/) {
378                 my $key = $1;
379                 my $value = $2;
380                 if ($key eq "resultTest") {
381                     $ResultTest = $value;
382                 }
383                 elsif ($key eq "init") {
384                     $InitForRun = $value;
385                 }
386                 elsif ($key eq "timeLimit") {
387                     $timeLimit = $value;
388                 }
389                 elsif ($key eq "arg") {
390                     $progArgs = "$progArgs $value";
391                 }
392                 elsif ($key eq "mpiexecarg") {
393                     $mpiexecArgs = "$mpiexecArgs $value";
394                 }
395                 elsif ($key eq "env") {
396                     $progEnv = "$progEnv $value";
397                 }
398                 elsif ($key eq "mpiversion") {
399                     $mpiVersion = $value;
400                 }
401                 elsif ($key eq "needs_privatization") {
402                     $needs_privatization = $value;
403                 }
404                 elsif ($key eq "strict") {
405                     $requiresStrict = $value
406                 }
407                 elsif ($key eq "mpix") {
408                     $requiresMPIX = $value
409                 }
410                 elsif ($key eq "xfail") {
411                     if ($value eq "") {
412                         print STDERR "\"xfail=\" requires an argument\n";
413                     }
414                     $xfail = $value;
415                 }
416                 else {
417                     print STDERR "Unrecognized key $key in $listfileSource\n";
418                 }
419             }
420         }
421
422         # skip empty lines
423         if ($programname eq "") { next; }
424
425         # if privatization is disabled, and if the test needs it, ignore it
426         if ($needs_privatization == 1 &&
427                 $enabled_privatization != 1) {
428                 SkippedTest($programname, $np, $workdir, "requires SMPI privatization");
429                 next; 
430         }
431
432         if ($np eq "") { $np = $np_default; }
433         if ($np_max > 0 && $np > $np_max) { $np = $np_max; }
434
435         # allows us to accurately output TAP test numbers without disturbing the
436         # original totals that have traditionally been reported
437         #
438         # These "unless" blocks are ugly, but permit us to honor skipping
439         # criteria for directories as well without counting directories as tests
440         # in our XML/TAP output.
441         unless (-d $programname) {
442             $total_seen++;
443         }
444
445         # If a minimum MPI version is specified, check against the
446         # available MPI.  If the version is unknown, we ignore this
447         # test (thus, all tests will be run).
448         if ($mpiVersion ne "" && $MPIMajorVersion ne "unknown" &&
449             $MPIMinorVersion ne "unknown") {
450             my ($majorReq,$minorReq) = split(/\./,$mpiVersion);
451             if ($majorReq > $MPIMajorVersion or
452                 ($majorReq == $MPIMajorVersion && $minorReq > $MPIMinorVersion))
453             {
454                 unless (-d $programname) {
455                     SkippedTest($programname, $np, $workdir, "requires MPI version $mpiVersion");
456                 }
457                 next;
458             }
459         }
460         # Check whether strict is required by MPI but not by the
461         # test (use strict=false for tests that use non-standard extensions)
462         if (lc($requiresStrict) eq "false" && lc($testIsStrict) eq "true") {
463             unless (-d $programname) {
464                 SkippedTest($programname, $np, $workdir, "non-strict test, strict MPI mode requested");
465             }
466             next;
467         }
468
469         if (lc($testIsStrict) eq "true") {
470             # Strict MPI testing was requested, so assume that a non-MPICH MPI
471             # implementation is being tested and the "xfail" implementation
472             # assumptions do not hold.
473             $xfail = '';
474         }
475
476         if (lc($requiresMPIX) eq "true" && lc($MPIHasMPIX) eq "no") {
477             unless (-d $programname) {
478                 SkippedTest($programname, $np, $workdir, "tests MPIX extensions, MPIX testing disabled");
479             }
480             next;
481         }
482
483         if (-d $programname) {
484             # If a directory, go into the that directory and
485             # look for a new list file
486             &ProcessDir( $programname, $listfile );
487         }
488         else {
489             $total_run++;
490             if (&BuildMPIProgram( $programname, $xfail ) == 0) {
491                 if ($batchRun == 1) {
492                     &AddMPIProgram( $programname, $np, $ResultTest,
493                                     $InitForRun, $timeLimit, $progArgs,
494                                     $progEnv, $mpiexecArgs, $xfail );
495                 }
496                 else {
497                     &RunMPIProgram( $programname, $np, $ResultTest,
498                                     $InitForRun, $timeLimit, $progArgs,
499                                     $progEnv, $mpiexecArgs, $xfail );
500                 }
501             }
502             elsif ($xfail ne '') {
503                 # We expected to run this program, so failure to build
504                 # is an error
505                 $found_error = 1;
506                 $err_count++;
507             }
508             if ($batchRun == 0) {
509                 &CleanUpAfterRun( $programname );
510             }
511         }
512     }
513     close( $LIST );
514 }
515 #
516 # This routine tries to run all of the files in the current
517 # directory
518 sub ProcessImplicitList {
519     # The default is to run every file in the current directory.
520     # If there are no built programs, build and run every file
521     # WARNING: This assumes that anything executable should be run as
522     # an MPI test.
523     $found_exec = 0;
524     $found_src  = 0;
525     open (PGMS, "ls -1 |" ) || die "Cannot list directory\n";
526     while (<PGMS>) {
527         s/\r?\n//;
528         $programname = $_;
529         if (-d $programname) { next; }  # Ignore directories
530         if ($programname eq "runtests") { next; } # Ignore self
531         if ($programname eq "checktests") { next; } # Ignore helper
532         if ($programname eq "configure") { next; } # Ignore configure script
533         if ($programname eq "config.status") { next; } # Ignore configure helper
534         if (-x $programname) { $found_exec++; }
535         if ($programname =~ /\.[cf]$/) { $found_src++; }
536     }
537     close PGMS;
538
539     if ($found_exec) {
540         print "Found executables\n" if $debug;
541         open (PGMS, "ls -1 |" ) || die "Cannot list programs\n";
542         while (<PGMS>) {
543             # Check for stop file
544             if (-s $stopfile) {
545                 # Exit because we found a stopfile
546                 print STDERR "Terminating test because stopfile $stopfile found\n";
547                 last;
548             }
549             s/\r?\n//;
550             $programname = $_;
551             if (-d $programname) { next; }  # Ignore directories
552             if ($programname eq "runtests") { next; } # Ignore self
553             if (-x $programname) {
554                 $total_run++;
555                 &RunMPIProgram( $programname, $np_default, "", "", "", "", "", "", "" );
556             }
557         }
558         close PGMS;
559     }
560     elsif ($found_src) {
561         print "Found source files\n" if $debug;
562         open (PGMS, "ls -1 *.c |" ) || die "Cannot list programs\n";
563         while (<PGMS>) {
564             if (-s $stopfile) {
565                 # Exit because we found a stopfile
566                 print STDERR "Terminating test because stopfile $stopfile found\n";
567                 last;
568             }
569             s/\r?\n//;
570             $programname = $_;
571             # Skip messages from ls about no files
572             if (! -s $programname) { next; }
573             $programname =~ s/\.c//;
574             $total_run++;
575             if (&BuildMPIProgram( $programname, "") == 0) {
576                 &RunMPIProgram( $programname, $np_default, "", "", "", "", "", "", "" );
577             }
578             else {
579                 # We expected to run this program, so failure to build
580                 # is an error
581                 $found_error = 1;
582                 $err_count++;
583             }
584             &CleanUpAfterRun( $programname );
585         }
586         close PGMS;
587     }
588 }
589 # Run the program.
590 # ToDo: Add a way to limit the time that any particular program may run.
591 # The arguments are
592 #    name of program, number of processes, name of routine to check results
593 #    init for testing, timelimit, and any additional program arguments
594 # If the 3rd arg is not present, the a default that simply checks that the
595 # return status is 0 and that the output is " No Errors" is used.
596 sub RunMPIProgram {
597     my ($programname,$np,$ResultTest,$InitForTest,$timeLimit,$progArgs,$progEnv,$mpiexecArgs,$xfail) = @_;
598     my $found_error   = 0;
599     my $found_noerror = 0;
600     my $inline = "";
601
602     &RunPreMsg( $programname, $np, $curdir );
603
604     unlink "err";
605
606     # Set a default timeout on tests (3 minutes for now)
607     my $timeout = $defaultTimeLimit;
608     if (defined($timeLimit) && $timeLimit =~ /^\d+$/) {
609         $timeout = $timeLimit;
610     }
611     $ENV{"MPIEXEC_TIMEOUT"} = $timeout;
612
613     # Run the optional setup routine. For example, the timeout tests could
614     # be set to a shorter timeout.
615     if ($InitForTest ne "") {
616         &$InitForTest();
617     }
618     print STDOUT "Env includes $progEnv\n" if $verbose;
619     print STDOUT "$mpiexec $wrapparg $mpiexecArgs $np_arg $np $program_wrapper ./$programname $progArgs\n" if $verbose;
620     print STDOUT "." if $showProgress;
621     # Save and restore the environment if necessary before running mpiexec.
622     if ($progEnv ne "") {
623         %saveEnv = %ENV;
624         foreach $val (split(/\s+/, $progEnv)) {
625             if ($val =~ /([^=]+)=(.*)/) {
626                 $ENV{$1} = $2;
627             }
628             else {
629                 print STDERR "Environment variable/value $val not in a=b form\n";
630             }
631         }
632     }
633     open ( MPIOUT, "$mpiexec $wrapparg $np_arg $np $mpiexecArgs $program_wrapper ./$programname $progArgs 2>&1 |" ) ||
634         die "Could not run ./$programname\n";
635     if ($progEnv ne "") {
636         %ENV = %saveEnv;
637     }
638     if ($ResultTest ne "") {
639         # Read and process the output
640         ($found_error, $inline) = &$ResultTest( MPIOUT, $programname );
641     }
642     else {
643         if ($verbose) {
644             $inline = "$mpiexec $wrapparg $np_arg $np $program_wrapper ./$programname\n";
645         }
646         else {
647             $inline = "";
648         }
649         while (<MPIOUT>) {
650             print STDOUT $_ if $verbose;
651             # Skip FORTRAN STOP
652             if (/FORTRAN STOP/) { next; }
653             $inline .= $_;
654             if (/^==[0-9]+== ?WARNING: ASan doesn't fully support/) {
655                 next;
656             }
657             if (/^\s*No [Ee]rrors\s*$/ && $found_noerror == 0) {
658                 $found_noerror = 1;
659             }
660             if (! /^\s*No [Ee]rrors\s*$/ && !/^\s*Test Passed\s*$/) {
661                 print STDERR "Unexpected output in $programname: $_";
662                 if (!$found_error) {
663                     $found_error = 1;
664                     $failed_tests .= $programname;
665                     $failed_tests .= " ";
666                     $err_count ++;
667                 }
668             }
669         }
670         if ($found_noerror == 0) {
671             print STDERR "Program $programname exited without No Errors\n";
672             if (!$found_error) {
673                 $found_error = 1;
674                 $failed_tests .= $programname;
675                 $failed_tests .= " ";
676                 $err_count ++;
677             }
678         }
679         $rc = close ( MPIOUT );
680         if ($rc == 0) {
681             # Only generate a message if we think that the program
682             # passed the test.
683             if (!$found_error) {
684                 $run_status = $?;
685                 $signal_num = $run_status & 127;
686                 if ($run_status > 255) { $run_status >>= 8; }
687                 print STDERR "Program $programname exited with non-zero status $run_status\n";
688                 if ($signal_num != 0) {
689                     print STDERR "Program $programname exited with signal $signal_num\n";
690                 }
691                 $failed_tests .= $programname;
692                 $failed_tests .= " ";
693                 $found_error = 1;
694                 $err_count ++;
695             }
696         }
697     }
698     if ($found_error) {
699         &RunTestFailed( $programname, $np, $curdir, $inline, $xfail );
700     }
701     else {
702         &RunTestPassed( $programname, $np, $curdir, $xfail );
703     }
704     &RunPostMsg( $programname, $np, $curdir );
705 }
706
707 # This version simply writes the mpiexec command out, with the output going
708 # into a file, and recording the output status of the run.
709 sub AddMPIProgram {
710     my ($programname,$np,$ResultTest,$InitForTest,$timeLimit,$progArgs,$progEnv,$mpiexecArgs, $xfail) = @_;
711
712     if (! -x $programname) {
713         print STDERR "Could not find $programname!";
714         return;
715     }
716
717     if ($ResultTest ne "") {
718         # This test really needs to be run manually, with this test
719         # Eventually, we can update this to include handleing in checktests.
720         print STDERR "Run $curdir/$programname with $np processes and use $ResultTest to check the results\n";
721         return;
722     }
723
724     # Set a default timeout on tests (3 minutes for now)
725     my $timeout = $defaultTimeLimit;
726     if (defined($timeLimit) && $timeLimit =~ /^\d+$/) {
727         # On some systems, there is no effective time limit on
728         # individual mpi program runs.  In that case, we may
729         # want to treat these also as "run manually".
730         $timeout = $timeLimit;
731     }
732     print BATOUT "export MPIEXEC_TIMEOUT=$timeout\n";
733
734     # Run the optional setup routine. For example, the timeout tests could
735     # be set to a shorter timeout.
736     if ($InitForTest ne "") {
737         &$InitForTest();
738     }
739
740     # For non-MPICH versions of mpiexec, a timeout may require a different
741     # environment variable or command line option (e.g., for Cray aprun,
742     # the option -t <sec> must be given, there is no environment variable
743     # to set the timeout.
744     $extraArgs = "";
745     if (defined($timeoutArgPattern) && $timeoutArgPattern ne "") {
746         my $timeArg = $timeoutArgPattern;
747         $timeoutArg =~ s/<SEC>/$timeout/;
748         $extraArgs .= $timeoutArg
749     }
750
751     print STDOUT "Env includes $progEnv\n" if $verbose;
752     print STDOUT "$mpiexec $np_arg $np $extraArgs $program_wrapper ./$programname $progArgs\n" if $verbose;
753     print STDOUT "." if $showProgress;
754     # Save and restore the environment if necessary before running mpiexec.
755     if ($progEnv ne "") {
756         # Need to fix:
757         # save_NAME_is_set=is old name set
758         # save_NAME=oldValue
759         # export NAME=newvalue
760         # (run)
761         # export NAME=oldValue (if set!)
762         print STDERR "Batch output does not permit changes to environment\n";
763     }
764     # The approach here is to move the test codes to a single directory from
765     # which they can be run; this avoids complex code to change directories
766     # and ensure that the output goes "into the right place".
767     $testCount++;
768     rename $programname, "$batrundir/$programname";
769     print BATOUT "echo \"# $mpiexec $np_arg $np $extraArgs $mpiexecArgs $program_wrapper $curdir/$programname $progArgs\" > runtests.$testCount.out\n";
770     # Some programs expect to run in the same directory as the executable
771     print BATOUT "$mpiexec $np_arg $np $extraArgs $mpiexecArgs $program_wrapper ./$programname $progArgs >> runtests.$testCount.out 2>&1\n";
772     print BATOUT "echo \$? > runtests.$testCount.status\n";
773 }
774
775 #
776 # Return value is 0 on success, non zero on failure
777 sub BuildMPIProgram {
778     my $programname = shift;
779     if (! -x $programname) {
780         die "Could not find $programname. Aborting.\n";
781     }
782     return 0;
783     # THE FOLLOWING IS DISABLED.
784     my $xfail = shift;
785     my $rc = 0;
786     if ($verbose) { print STDERR "making $programname\n"; }
787     if (! -x $programname) { $remove_this_pgm = 1; }
788     else { $remove_this_pgm = 0; }
789     my $output = `make $programname 2>&1`;
790     $rc = $?;
791     if ($rc > 255) { $rc >>= 8; }
792     if (! -x $programname) {
793         print STDERR "Failed to build $programname; $output\n";
794         if ($rc == 0) {
795             $rc = 1;
796         }
797         # Add a line to the summary file describing the failure
798         # This will ensure that failures to build will end up
799         # in the summary file (which is otherwise written by the
800         # RunMPIProgram step)
801         &RunPreMsg( $programname, $np, $curdir );
802         &RunTestFailed( $programname, $np, $curdir, "Failed to build $programname; $output", $xfail );
803         &RunPostMsg( $programname, $np, $curdir );
804     }
805     return $rc;
806 }
807
808 sub CleanUpAfterRun {
809     my $programname = $_[0];
810
811     # Check for that this program has exited.  If it is still running,
812     # issue a warning and leave the application.  Of course, this
813     # check is complicated by the lack of a standard access to the
814     # running processes for this user in Unix.
815     @stillRunning = &FindRunning( $programname );
816
817     if ($#stillRunning > -1) {
818         print STDERR "Some programs ($programname) may still be running:\npids = ";
819         for (my $i=0; $i <= $#stillRunning; $i++ ) {
820             print STDERR $stillRunning[$i] . " ";
821         }
822         print STDERR "\n";
823         # Remind the user that the executable remains; we leave it around
824         # to allow the programmer to debug the running program, for which
825         # the executable is needed.
826         print STDERR "The executable ($programname) will not be removed.\n";
827     }
828     else {
829         if ($remove_this_pgm && $clean_pgms) {
830             unlink $programname, "$programname.o";
831         }
832         $remove_this_pgm = 0;
833     }
834 }
835 # ----------------------------------------------------------------------------
836 sub FindRunning {
837     my $programname = $_[0];
838     my @pids = ();
839
840     my $logname = $ENV{'USER'};
841     my $pidloc = 1;
842     my $rc = open PSFD, "ps auxw -U $logname 2>&1 |";
843
844     if ($rc == 0) {
845         $rc = open PSFD, "ps -fu $logname 2>&1 |";
846     }
847     if ($rc == 0) {
848         print STDERR "Could not execute ps command\n";
849         return @pids;
850     }
851
852     while (<PSFD>) {
853         if (/$programname/) {
854             @fields = split(/\s+/);
855             my $pid = $fields[$pidloc];
856             # Check that we've found a numeric pid
857             if ($pid =~ /^\d+$/) {
858                 $pids[$#pids + 1] = $pid;
859             }
860         }
861     }
862     close PSFD;
863
864     return @pids;
865 }
866 # ----------------------------------------------------------------------------
867 #
868 # TestStatus is a special test that reports success *only* when the
869 # status return is NONZERO
870 sub TestStatus {
871     my $MPIOUT = $_[0];
872     my $programname = $_[1];
873     my $found_error = 0;
874
875     my $inline = "";
876     while (<$MPIOUT>) {
877         #print STDOUT $_ if $verbose;
878         # Skip FORTRAN STOP
879         if (/FORTRAN STOP/) { next; }
880         $inline .= $_;
881         # ANY output is an error. We have the following output
882         # exception for the Hydra process manager.
883         if (/=*/) { last; }
884         if (! /^\s*$/) {
885             print STDERR "Unexpected output in $programname: $_";
886             if (!$found_error) {
887                 $found_error = 1;
888                 $err_count ++;
889             }
890         }
891     }
892     $rc = close ( MPIOUT );
893     if ($rc == 0) {
894         $run_status = $?;
895         $signal_num = $run_status & 127;
896         if ($run_status > 255) { $run_status >>= 8; }
897     }
898     else {
899         # This test *requires* non-zero return codes
900         if (!$found_error) {
901             $found_error = 1;
902             $err_count ++;
903         }
904         $inline .= "$mpiexec returned a zero status but the program returned a nonzero status\n";
905     }
906     return ($found_error,$inline);
907 }
908 #
909 # TestTimeout is a special test that reports success *only* when the
910 # status return is NONZERO and there are no processes left over.
911 # This test currently checks only for the return status.
912 sub TestTimeout {
913     my $MPIOUT = $_[0];
914     my $programname = $_[1];
915     my $found_error = 0;
916
917     my $inline = "";
918     while (<$MPIOUT>) {
919         #print STDOUT $_ if $verbose;
920         # Skip FORTRAN STOP
921         if (/FORTRAN STOP/) { next; }
922         $inline .= $_;
923         if (/[Tt]imeout/) { next; }
924         # Allow 'signaled with Interrupt' (see gforker mpiexec)
925         if (/signaled with Interrupt/) { next; }
926         # Allow 'job ending due to env var MPIEXEC_TIMEOUT' (mpd)
927         if (/job ending due to env var MPIEXEC_TIMEOUT/) { next; }
928         # Allow 'APPLICATION TIMED OUT' (hydra)
929         if (/\[mpiexec@.*\] APPLICATION TIMED OUT/) { last; }
930         # ANY output is an error (other than timeout)
931         if (! /^\s*$/) {
932             print STDERR "Unexpected output in $programname: $_";
933             if (!$found_error) {
934                 $found_error = 1;
935                 $err_count ++;
936             }
937         }
938     }
939     $rc = close ( MPIOUT );
940     if ($rc == 0) {
941         $run_status = $?;
942         $signal_num = $run_status & 127;
943         if ($run_status > 255) { $run_status >>= 8; }
944     }
945     else {
946         # This test *requires* non-zero return codes
947         if (!$found_error) {
948             $found_error = 1;
949             $err_count ++;
950         }
951         $inline .= "$mpiexec returned a zero status but the program returned a nonzero status\n";
952     }
953     #
954     # Here should go a check of the processes
955     # open( PFD, "ps -fu $LOGNAME | grep -v grep | grep $programname |" );
956     # while (<PFD>) {
957     #
958     # }
959     # close PFD;
960     return ($found_error,$inline);
961 }
962 #
963 # TestErrFatal is a special test that reports success *only* when the
964 # status return is NONZERO; it ignores error messages
965 sub TestErrFatal {
966     my $MPIOUT = $_[0];
967     my $programname = $_[1];
968     my $found_error = 0;
969
970     my $inline = "";
971     while (<$MPIOUT>) {
972         #print STDOUT $_ if $verbose;
973         # Skip FORTRAN STOP
974         if (/FORTRAN STOP/) { next; }
975         $inline .= $_;
976         # ALL output is allowed.
977     }
978     $rc = close ( MPIOUT );
979     if ($rc == 0) {
980         $run_status = $?;
981         $signal_num = $run_status & 127;
982         if ($run_status > 255) { $run_status >>= 8; }
983     }
984     else {
985         # This test *requires* non-zero return codes
986         if (!$found_error) {
987             $found_error = 1;
988             $err_count ++;
989         }
990         $inline .= "$mpiexec returned a zero status but the program returned a nonzero status\n";
991     }
992     return ($found_error,$inline);
993 }
994
995 # ----------------------------------------------------------------------------
996 # Output routines:
997 #  RunPreMsg( programname, np, workdir ) - Call before running a program
998 #  RunTestFailed, RunTestPassed - Call after test
999 #  RunPostMsg               - Call at end of each test
1000 #
1001 sub RunPreMsg {
1002     my ($programname,$np,$workdir) = @_;
1003     if ($xmloutput) {
1004         print XMLOUT "<MPITEST>$newline<NAME>$programname</NAME>$newline";
1005         print XMLOUT "<NP>$np</NP>$newline";
1006         print XMLOUT "<WORKDIR>$workdir</WORKDIR>$newline";
1007     }
1008 }
1009 sub RunPostMsg {
1010     my ($programname, $np, $workdir) = @_;
1011     if ($xmloutput) {
1012         print XMLOUT "</MPITEST>$newline";
1013     }
1014 }
1015 sub RunTestPassed {
1016     my ($programname, $np, $workdir, $xfail) = @_;
1017     if ($xmloutput) {
1018         print XMLOUT "<STATUS>pass</STATUS>$newline";
1019     }
1020     if ($tapoutput) {
1021         my $xfailstr = '';
1022         if ($xfail ne '') {
1023             $xfailstr = " # TODO $xfail";
1024         }
1025         print TAPOUT "ok ${total_run} - $workdir/$programname ${np}${xfailstr}\n";
1026     }
1027 }
1028 sub RunTestFailed {
1029     my $programname = shift;
1030     my $np = shift;
1031     my $workdir = shift;
1032     my $output = shift;
1033     my $xfail = shift;
1034
1035     if ($xmloutput) {
1036         my $xout = $output;
1037         # basic escapes that wreck the XML output
1038         $xout =~ s/</\*AMP\*lt;/g;
1039         $xout =~ s/>/\*AMP\*gt;/g;
1040         $xout =~ s/&/\*AMP\*amp;/g;
1041         $xout =~ s/\*AMP\*/&/g;
1042         # TODO: Also capture any non-printing characters (XML doesn't like them
1043         # either).
1044         print XMLOUT "<STATUS>fail</STATUS>$newline";
1045         print XMLOUT "<TESTDIFF>$newline$xout</TESTDIFF>$newline";
1046     }
1047
1048     if ($tapoutput) {
1049         my $xfailstr = '';
1050         if ($xfail ne '') {
1051             $xfailstr = " # TODO $xfail";
1052         }
1053         print TAPOUT "not ok ${total_run} - $workdir/$programname ${np}${xfailstr}\n";
1054         print TAPOUT "  ---\n";
1055         print TAPOUT "  Directory: $workdir\n";
1056         print TAPOUT "  File: $programname\n";
1057         print TAPOUT "  Num-procs: $np\n";
1058         print TAPOUT "  Date: \"" . localtime . "\"\n";
1059
1060         # The following would be nice, but it leads to unfortunate formatting in
1061         # the Jenkins web output for now.  Using comment lines instead, since
1062         # they are easier to read/find in a browser.
1063 ##        print TAPOUT "  Output: |\n";
1064 ##        # using block literal format, requires that all chars are printable
1065 ##        # UTF-8 (or UTF-16, but we won't encounter that)
1066 ##        foreach my $line (split m/\r?\n/, $output) {
1067 ##            chomp $line;
1068 ##            # 4 spaces, 2 for TAP indent, 2 more for YAML block indent
1069 ##            print TAPOUT "    $line\n";
1070 ##        }
1071
1072         print TAPOUT "  ...\n";
1073
1074         # Alternative to the "Output:" YAML block literal above.  Do not put any
1075         # spaces before the '#', this causes some TAP parsers (including Perl's
1076         # TAP::Parser) to treat the line as "unknown" instead of a proper
1077         # comment.
1078         print TAPOUT "## Test output (expected 'No Errors'):\n";
1079         foreach my $line (split m/\r?\n/, $output) {
1080             chomp $line;
1081             print TAPOUT "## $line\n";
1082         }
1083     }
1084 }
1085
1086 sub SkippedTest {
1087     my $programname = shift;
1088     my $np = shift;
1089     my $workdir = shift;
1090     my $reason = shift;
1091
1092     # simply omit from the XML output
1093
1094     if ($tapoutput) {
1095         print TAPOUT "ok ${total_seen} - $workdir/$programname $np  # SKIP $reason\n";
1096     }
1097 }
1098
1099 # ----------------------------------------------------------------------------
1100 # Alternate init routines
1101 sub InitQuickTimeout {
1102     $ENV{"MPIEXEC_TIMEOUT"} = 10;
1103 }