Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
ea6c3041497d3d1c0d3880e6c682b2b34038697c
[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 (/VALGRIND_COMMAND=(.*)/) { 
172         $valgrind = $1; }
173     elsif (/VALGRIND_OPTIONS=(.*)/) {
174          $wrapparg = "-wrapper \"$valgrind $1\""; }
175     elsif (/--?xmlfile=(.*)/) {
176         $xmlfile   = $1;
177         if (! ($xmlfile =~ /^\//)) {
178             $thisdir = `pwd`;
179             chop $thisdir;
180             $xmlfullfile = $thisdir . "/" . $xmlfile ;
181         }
182         else {
183             $xmlfullfile = $xmlfile;
184         }
185         $xmloutput = 1;
186         open( XMLOUT, ">$xmlfile" ) || die "Cannot open $xmlfile\n";
187         my $date = `date "+%Y-%m-%d-%H-%M"`;
188         $date =~ s/\r?\n//;
189         # MPISOURCE can be used to describe the source of MPI for this
190         # test.
191         print XMLOUT "<?xml version='1.0' ?>$newline";
192         print XMLOUT "<?xml-stylesheet href=\"TestResults.xsl\" type=\"text/xsl\" ?>$newline";
193         print XMLOUT "<MPITESTRESULTS>$newline";
194         print XMLOUT "<DATE>$date</DATE>$newline";
195         print XMLOUT "<MPISOURCE></MPISOURCE>$newline";
196     }
197     elsif (/--?noxmlclose/) {
198         $closeXMLOutput = 0;
199     }
200     elsif (/--?tapfile=(.*)/) {
201         $tapfile = $1;
202         if ($tapfile !~ m|^/|) {
203             $thisdir = `pwd`;
204             chomp $thisdir;
205             $tapfullfile = $thisdir . "/" . $tapfile ;
206         }
207         else {
208             $tapfullfile = $tapfile;
209         }
210         $tapoutput = 1;
211         open( TAPOUT, ">$tapfile" ) || die "Cannot open $tapfile\n";
212         my $date = `date "+%Y-%m-%d-%H-%M"`;
213         $date =~ s/\r?\n//;
214         print TAPOUT "TAP version 13\n";
215         print TAPOUT "# MPICH test suite results (TAP format)\n";
216         print TAPOUT "# date ${date}\n";
217         # we do not know at this point how many tests will be run, so do
218         # not print a test plan line like "1..450" until the very end
219     }
220 }
221
222 # Perform any post argument processing
223 if ($batchRun) {
224     if (! -d $batrundir) {
225         mkpath $batrundir || die "Could not create $batrundir\n";
226     }
227     open( BATOUT, ">$batrundir/runtests.batch" ) || die "Could not open $batrundir/runtests.batch\n";
228 }
229 else {
230     # We must have mpiexec
231     if ("$mpiexec" eq "") {
232         print STDERR "No mpiexec found!\n";
233         exit(1);
234     }
235 }
236
237 #
238 # Process any files
239 if ($listfiles eq "") {
240     if ($batchRun) {
241         print STDERR "An implicit list of tests is not permitted in batch mode\n";
242         exit(1);
243     }
244     else {
245         &ProcessImplicitList;
246     }
247 }
248 elsif (-d $listfiles) {
249     print STDERR "Testing by directories not yet supported\n";
250 }
251 else {
252     &RunList( $listfiles );
253 }
254
255 if ($xmloutput && $closeXMLOutput) {
256     print XMLOUT "</MPITESTRESULTS>$newline";
257     close XMLOUT;
258 }
259
260 if ($tapoutput) {
261     print TAPOUT "1..$total_seen\n";
262     close TAPOUT;
263 }
264
265 # Output a summary:
266 if ($batchRun) {
267     print "Programs created along with a runtest.batch file in $batrundir\n";
268     print "Run that script and then use checktests to summarize the results\n";
269 }
270 else {
271     if ($err_count) {
272         print "$err_count tests failed out of $total_run\n";
273         print "Failing tests : $failed_tests\n";
274         if ($xmloutput) {
275             print "Details in $xmlfullfile\n";
276         }
277     }
278     else {
279         print " All $total_run tests passed!\n";
280     }
281     if ($tapoutput) {
282         print "TAP formatted results in $tapfullfile\n";
283     }
284 }
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 (/^\s*No [Ee]rrors\s*$/ && $found_noerror == 0) {
655                 $found_noerror = 1;
656             }
657             if (! /^\s*No [Ee]rrors\s*$/ && !/^\s*Test Passed\s*$/) {
658                 print STDERR "Unexpected output in $programname: $_";
659                 if (!$found_error) {
660                     $found_error = 1;
661                     $failed_tests .= $programname;
662                     $failed_tests .= " ";
663                     $err_count ++;
664                 }
665             }
666         }
667         if ($found_noerror == 0) {
668             print STDERR "Program $programname exited without No Errors\n";
669             if (!$found_error) {
670                 $found_error = 1;
671                 $failed_tests .= $programname;
672                 $failed_tests .= " ";
673                 $err_count ++;
674             }
675         }
676         $rc = close ( MPIOUT );
677         if ($rc == 0) {
678             # Only generate a message if we think that the program
679             # passed the test.
680             if (!$found_error) {
681                 $run_status = $?;
682                 $signal_num = $run_status & 127;
683                 if ($run_status > 255) { $run_status >>= 8; }
684                 print STDERR "Program $programname exited with non-zero status $run_status\n";
685                 if ($signal_num != 0) {
686                     print STDERR "Program $programname exited with signal $signal_num\n";
687                 }
688                 $failed_tests .= $programname;
689                 $failed_tests .= " ";
690                 $found_error = 1;
691                 $err_count ++;
692             }
693         }
694     }
695     if ($found_error) {
696         &RunTestFailed( $programname, $np, $curdir, $inline, $xfail );
697     }
698     else {
699         &RunTestPassed( $programname, $np, $curdir, $xfail );
700     }
701     &RunPostMsg( $programname, $np, $curdir );
702 }
703
704 # This version simply writes the mpiexec command out, with the output going
705 # into a file, and recording the output status of the run.
706 sub AddMPIProgram {
707     my ($programname,$np,$ResultTest,$InitForTest,$timeLimit,$progArgs,$progEnv,$mpiexecArgs, $xfail) = @_;
708
709     if (! -x $programname) {
710         print STDERR "Could not find $programname!";
711         return;
712     }
713
714     if ($ResultTest ne "") {
715         # This test really needs to be run manually, with this test
716         # Eventually, we can update this to include handleing in checktests.
717         print STDERR "Run $curdir/$programname with $np processes and use $ResultTest to check the results\n";
718         return;
719     }
720
721     # Set a default timeout on tests (3 minutes for now)
722     my $timeout = $defaultTimeLimit;
723     if (defined($timeLimit) && $timeLimit =~ /^\d+$/) {
724         # On some systems, there is no effective time limit on
725         # individual mpi program runs.  In that case, we may
726         # want to treat these also as "run manually".
727         $timeout = $timeLimit;
728     }
729     print BATOUT "export MPIEXEC_TIMEOUT=$timeout\n";
730
731     # Run the optional setup routine. For example, the timeout tests could
732     # be set to a shorter timeout.
733     if ($InitForTest ne "") {
734         &$InitForTest();
735     }
736
737     # For non-MPICH versions of mpiexec, a timeout may require a different
738     # environment variable or command line option (e.g., for Cray aprun,
739     # the option -t <sec> must be given, there is no environment variable
740     # to set the timeout.
741     $extraArgs = "";
742     if (defined($timeoutArgPattern) && $timeoutArgPattern ne "") {
743         my $timeArg = $timeoutArgPattern;
744         $timeoutArg =~ s/<SEC>/$timeout/;
745         $extraArgs .= $timeoutArg
746     }
747
748     print STDOUT "Env includes $progEnv\n" if $verbose;
749     print STDOUT "$mpiexec $np_arg $np $extraArgs $program_wrapper ./$programname $progArgs\n" if $verbose;
750     print STDOUT "." if $showProgress;
751     # Save and restore the environment if necessary before running mpiexec.
752     if ($progEnv ne "") {
753         # Need to fix:
754         # save_NAME_is_set=is old name set
755         # save_NAME=oldValue
756         # export NAME=newvalue
757         # (run)
758         # export NAME=oldValue (if set!)
759         print STDERR "Batch output does not permit changes to environment\n";
760     }
761     # The approach here is to move the test codes to a single directory from
762     # which they can be run; this avoids complex code to change directories
763     # and ensure that the output goes "into the right place".
764     $testCount++;
765     rename $programname, "$batrundir/$programname";
766     print BATOUT "echo \"# $mpiexec $np_arg $np $extraArgs $mpiexecArgs $program_wrapper $curdir/$programname $progArgs\" > runtests.$testCount.out\n";
767     # Some programs expect to run in the same directory as the executable
768     print BATOUT "$mpiexec $np_arg $np $extraArgs $mpiexecArgs $program_wrapper ./$programname $progArgs >> runtests.$testCount.out 2>&1\n";
769     print BATOUT "echo \$? > runtests.$testCount.status\n";
770 }
771
772 #
773 # Return value is 0 on success, non zero on failure
774 sub BuildMPIProgram {
775     my $programname = shift;
776     if (! -x $programname) {
777         die "Could not find $programname. Aborting.\n";
778     }
779     return 0;
780     # THE FOLLOWING IS DISABLED.
781     my $xfail = shift;
782     my $rc = 0;
783     if ($verbose) { print STDERR "making $programname\n"; }
784     if (! -x $programname) { $remove_this_pgm = 1; }
785     else { $remove_this_pgm = 0; }
786     my $output = `make $programname 2>&1`;
787     $rc = $?;
788     if ($rc > 255) { $rc >>= 8; }
789     if (! -x $programname) {
790         print STDERR "Failed to build $programname; $output\n";
791         if ($rc == 0) {
792             $rc = 1;
793         }
794         # Add a line to the summary file describing the failure
795         # This will ensure that failures to build will end up
796         # in the summary file (which is otherwise written by the
797         # RunMPIProgram step)
798         &RunPreMsg( $programname, $np, $curdir );
799         &RunTestFailed( $programname, $np, $curdir, "Failed to build $programname; $output", $xfail );
800         &RunPostMsg( $programname, $np, $curdir );
801     }
802     return $rc;
803 }
804
805 sub CleanUpAfterRun {
806     my $programname = $_[0];
807
808     # Check for that this program has exited.  If it is still running,
809     # issue a warning and leave the application.  Of course, this
810     # check is complicated by the lack of a standard access to the
811     # running processes for this user in Unix.
812     @stillRunning = &FindRunning( $programname );
813
814     if ($#stillRunning > -1) {
815         print STDERR "Some programs ($programname) may still be running:\npids = ";
816         for (my $i=0; $i <= $#stillRunning; $i++ ) {
817             print STDERR $stillRunning[$i] . " ";
818         }
819         print STDERR "\n";
820         # Remind the user that the executable remains; we leave it around
821         # to allow the programmer to debug the running program, for which
822         # the executable is needed.
823         print STDERR "The executable ($programname) will not be removed.\n";
824     }
825     else {
826         if ($remove_this_pgm && $clean_pgms) {
827             unlink $programname, "$programname.o";
828         }
829         $remove_this_pgm = 0;
830     }
831 }
832 # ----------------------------------------------------------------------------
833 sub FindRunning {
834     my $programname = $_[0];
835     my @pids = ();
836
837     my $logname = $ENV{'USER'};
838     my $pidloc = 1;
839     my $rc = open PSFD, "ps auxw -U $logname 2>&1 |";
840
841     if ($rc == 0) {
842         $rc = open PSFD, "ps -fu $logname 2>&1 |";
843     }
844     if ($rc == 0) {
845         print STDERR "Could not execute ps command\n";
846         return @pids;
847     }
848
849     while (<PSFD>) {
850         if (/$programname/) {
851             @fields = split(/\s+/);
852             my $pid = $fields[$pidloc];
853             # Check that we've found a numeric pid
854             if ($pid =~ /^\d+$/) {
855                 $pids[$#pids + 1] = $pid;
856             }
857         }
858     }
859     close PSFD;
860
861     return @pids;
862 }
863 # ----------------------------------------------------------------------------
864 #
865 # TestStatus is a special test that reports success *only* when the
866 # status return is NONZERO
867 sub TestStatus {
868     my $MPIOUT = $_[0];
869     my $programname = $_[1];
870     my $found_error = 0;
871
872     my $inline = "";
873     while (<$MPIOUT>) {
874         #print STDOUT $_ if $verbose;
875         # Skip FORTRAN STOP
876         if (/FORTRAN STOP/) { next; }
877         $inline .= $_;
878         # ANY output is an error. We have the following output
879         # exception for the Hydra process manager.
880         if (/=*/) { last; }
881         if (! /^\s*$/) {
882             print STDERR "Unexpected output in $programname: $_";
883             if (!$found_error) {
884                 $found_error = 1;
885                 $err_count ++;
886             }
887         }
888     }
889     $rc = close ( MPIOUT );
890     if ($rc == 0) {
891         $run_status = $?;
892         $signal_num = $run_status & 127;
893         if ($run_status > 255) { $run_status >>= 8; }
894     }
895     else {
896         # This test *requires* non-zero return codes
897         if (!$found_error) {
898             $found_error = 1;
899             $err_count ++;
900         }
901         $inline .= "$mpiexec returned a zero status but the program returned a nonzero status\n";
902     }
903     return ($found_error,$inline);
904 }
905 #
906 # TestTimeout is a special test that reports success *only* when the
907 # status return is NONZERO and there are no processes left over.
908 # This test currently checks only for the return status.
909 sub TestTimeout {
910     my $MPIOUT = $_[0];
911     my $programname = $_[1];
912     my $found_error = 0;
913
914     my $inline = "";
915     while (<$MPIOUT>) {
916         #print STDOUT $_ if $verbose;
917         # Skip FORTRAN STOP
918         if (/FORTRAN STOP/) { next; }
919         $inline .= $_;
920         if (/[Tt]imeout/) { next; }
921         # Allow 'signaled with Interrupt' (see gforker mpiexec)
922         if (/signaled with Interrupt/) { next; }
923         # Allow 'job ending due to env var MPIEXEC_TIMEOUT' (mpd)
924         if (/job ending due to env var MPIEXEC_TIMEOUT/) { next; }
925         # Allow 'APPLICATION TIMED OUT' (hydra)
926         if (/\[mpiexec@.*\] APPLICATION TIMED OUT/) { last; }
927         # ANY output is an error (other than timeout)
928         if (! /^\s*$/) {
929             print STDERR "Unexpected output in $programname: $_";
930             if (!$found_error) {
931                 $found_error = 1;
932                 $err_count ++;
933             }
934         }
935     }
936     $rc = close ( MPIOUT );
937     if ($rc == 0) {
938         $run_status = $?;
939         $signal_num = $run_status & 127;
940         if ($run_status > 255) { $run_status >>= 8; }
941     }
942     else {
943         # This test *requires* non-zero return codes
944         if (!$found_error) {
945             $found_error = 1;
946             $err_count ++;
947         }
948         $inline .= "$mpiexec returned a zero status but the program returned a nonzero status\n";
949     }
950     #
951     # Here should go a check of the processes
952     # open( PFD, "ps -fu $LOGNAME | grep -v grep | grep $programname |" );
953     # while (<PFD>) {
954     #
955     # }
956     # close PFD;
957     return ($found_error,$inline);
958 }
959 #
960 # TestErrFatal is a special test that reports success *only* when the
961 # status return is NONZERO; it ignores error messages
962 sub TestErrFatal {
963     my $MPIOUT = $_[0];
964     my $programname = $_[1];
965     my $found_error = 0;
966
967     my $inline = "";
968     while (<$MPIOUT>) {
969         #print STDOUT $_ if $verbose;
970         # Skip FORTRAN STOP
971         if (/FORTRAN STOP/) { next; }
972         $inline .= $_;
973         # ALL output is allowed.
974     }
975     $rc = close ( MPIOUT );
976     if ($rc == 0) {
977         $run_status = $?;
978         $signal_num = $run_status & 127;
979         if ($run_status > 255) { $run_status >>= 8; }
980     }
981     else {
982         # This test *requires* non-zero return codes
983         if (!$found_error) {
984             $found_error = 1;
985             $err_count ++;
986         }
987         $inline .= "$mpiexec returned a zero status but the program returned a nonzero status\n";
988     }
989     return ($found_error,$inline);
990 }
991
992 # ----------------------------------------------------------------------------
993 # Output routines:
994 #  RunPreMsg( programname, np, workdir ) - Call before running a program
995 #  RunTestFailed, RunTestPassed - Call after test
996 #  RunPostMsg               - Call at end of each test
997 #
998 sub RunPreMsg {
999     my ($programname,$np,$workdir) = @_;
1000     if ($xmloutput) {
1001         print XMLOUT "<MPITEST>$newline<NAME>$programname</NAME>$newline";
1002         print XMLOUT "<NP>$np</NP>$newline";
1003         print XMLOUT "<WORKDIR>$workdir</WORKDIR>$newline";
1004     }
1005 }
1006 sub RunPostMsg {
1007     my ($programname, $np, $workdir) = @_;
1008     if ($xmloutput) {
1009         print XMLOUT "</MPITEST>$newline";
1010     }
1011 }
1012 sub RunTestPassed {
1013     my ($programname, $np, $workdir, $xfail) = @_;
1014     if ($xmloutput) {
1015         print XMLOUT "<STATUS>pass</STATUS>$newline";
1016     }
1017     if ($tapoutput) {
1018         my $xfailstr = '';
1019         if ($xfail ne '') {
1020             $xfailstr = " # TODO $xfail";
1021         }
1022         print TAPOUT "ok ${total_run} - $workdir/$programname ${np}${xfailstr}\n";
1023     }
1024 }
1025 sub RunTestFailed {
1026     my $programname = shift;
1027     my $np = shift;
1028     my $workdir = shift;
1029     my $output = shift;
1030     my $xfail = shift;
1031
1032     if ($xmloutput) {
1033         my $xout = $output;
1034         # basic escapes that wreck the XML output
1035         $xout =~ s/</\*AMP\*lt;/g;
1036         $xout =~ s/>/\*AMP\*gt;/g;
1037         $xout =~ s/&/\*AMP\*amp;/g;
1038         $xout =~ s/\*AMP\*/&/g;
1039         # TODO: Also capture any non-printing characters (XML doesn't like them
1040         # either).
1041         print XMLOUT "<STATUS>fail</STATUS>$newline";
1042         print XMLOUT "<TESTDIFF>$newline$xout</TESTDIFF>$newline";
1043     }
1044
1045     if ($tapoutput) {
1046         my $xfailstr = '';
1047         if ($xfail ne '') {
1048             $xfailstr = " # TODO $xfail";
1049         }
1050         print TAPOUT "not ok ${total_run} - $workdir/$programname ${np}${xfailstr}\n";
1051         print TAPOUT "  ---\n";
1052         print TAPOUT "  Directory: $workdir\n";
1053         print TAPOUT "  File: $programname\n";
1054         print TAPOUT "  Num-procs: $np\n";
1055         print TAPOUT "  Date: \"" . localtime . "\"\n";
1056
1057         # The following would be nice, but it leads to unfortunate formatting in
1058         # the Jenkins web output for now.  Using comment lines instead, since
1059         # they are easier to read/find in a browser.
1060 ##        print TAPOUT "  Output: |\n";
1061 ##        # using block literal format, requires that all chars are printable
1062 ##        # UTF-8 (or UTF-16, but we won't encounter that)
1063 ##        foreach my $line (split m/\r?\n/, $output) {
1064 ##            chomp $line;
1065 ##            # 4 spaces, 2 for TAP indent, 2 more for YAML block indent
1066 ##            print TAPOUT "    $line\n";
1067 ##        }
1068
1069         print TAPOUT "  ...\n";
1070
1071         # Alternative to the "Output:" YAML block literal above.  Do not put any
1072         # spaces before the '#', this causes some TAP parsers (including Perl's
1073         # TAP::Parser) to treat the line as "unknown" instead of a proper
1074         # comment.
1075         print TAPOUT "## Test output (expected 'No Errors'):\n";
1076         foreach my $line (split m/\r?\n/, $output) {
1077             chomp $line;
1078             print TAPOUT "## $line\n";
1079         }
1080     }
1081 }
1082
1083 sub SkippedTest {
1084     my $programname = shift;
1085     my $np = shift;
1086     my $workdir = shift;
1087     my $reason = shift;
1088
1089     # simply omit from the XML output
1090
1091     if ($tapoutput) {
1092         print TAPOUT "ok ${total_seen} - $workdir/$programname $np  # SKIP $reason\n";
1093     }
1094 }
1095
1096 # ----------------------------------------------------------------------------
1097 # Alternate init routines
1098 sub InitQuickTimeout {
1099     $ENV{"MPIEXEC_TIMEOUT"} = 10;
1100 }