Logo AND Algorithmique Numérique Distribuée

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