Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
[tesh] cleanups now that it works with IPC::Run
[simgrid.git] / tools / tesh / tesh.pl
1 #! /usr/bin/env perl
2
3 # Copyright (c) 2012-2015. The SimGrid Team.
4 # All rights reserved.
5
6 # This program is free software; you can redistribute it and/or modify it
7 # under the terms of the license (GNU LGPL) which comes with this package.
8 eval 'exec perl -S $0 ${1+"$@"}'
9   if $running_under_some_shell;
10
11 # If you change this file, please stick to the formatting you got with:
12 # perltidy --backup-and-modify-in-place --maximum-line-length=180 --output-line-ending=unix --cuddled-else
13
14 =encoding UTF-8
15
16 =head1 NAME
17
18 tesh -- testing shell
19
20 =head1 SYNOPSIS
21
22 B<tesh> [I<options>] I<tesh_file>
23
24 =cut
25
26 BEGIN {
27     # Disabling IPC::Run::Debug saves tons of useless calls.
28     $ENV{'IPCRUNDEBUG'} = 'none'
29       unless exists $ENV{'IPCRUNDEBUG'};
30 }
31
32 my $enable_coverage        = 0;
33 my $diff_tool              = 0;
34 my $diff_tool_tmp_fh       = 0;
35 my $diff_tool_tmp_filename = 0;
36 my $sort_prefix            = -1;
37 my $tesh_file;
38 my $tesh_name;
39 my $error    = 0;
40 my $exitcode = 0;
41 my @bg_cmds;
42 my (%environ);
43 $SIG{'PIPE'} = 'IGNORE';
44
45 my $path = $0;
46 $path =~ s|[^/]*$||;
47 push @INC, $path;
48
49 use lib "@CMAKE_BINARY_DIR@/bin";
50
51 use Diff qw(diff);    # postpone a bit to have time to change INC
52
53 use Getopt::Long qw(GetOptions);
54 use strict;
55 use Text::ParseWords;
56 use IPC::Run qw(start run timeout finish);
57 use IO::File;
58 use English;
59
60 ####
61 #### Portability bits for windows
62 ####
63
64 use constant RUNNING_ON_WINDOWS => ( $OSNAME =~ /^(?:mswin|dos|os2)/oi );
65 use POSIX qw(:sys_wait_h WIFEXITED WIFSIGNALED WIFSTOPPED WEXITSTATUS WTERMSIG WSTOPSIG
66   :signal_h SIGINT SIGTERM SIGKILL SIGABRT SIGSEGV);
67
68 BEGIN {
69     if (RUNNING_ON_WINDOWS) { # Missing on windows
70         *WIFEXITED   = sub { not $_[0] & 127 };
71         *WEXITSTATUS = sub { $_[0] >> 8 };
72         *WIFSIGNALED = sub { ( $_[0] & 127 ) && ( $_[0] & 127 != 127 ) };
73         *WTERMSIG    = sub { $_[0] & 127 };
74     }
75 }
76
77
78 ####
79 #### Command line option handling
80 ####
81
82 my %opts = ( "debug" => 0,
83              "timeout" => 120, # No command should run any longer than 2 minutes by default
84            );
85
86 Getopt::Long::config( 'bundling', 'no_getopt_compat', 'no_auto_abbrev' );
87 GetOptions(
88     'debug|d' => \$opts{"debug"},
89
90     'difftool=s' => \$diff_tool,
91
92     'cd=s'      => sub { cd_cmd( $_[1] ) },
93     'timeout=s' => \$opts{'timeout'},
94     'setenv=s'  => sub { setenv_cmd( $_[1] ) },
95     'cfg=s' => sub { $opts{'cfg'} .= " --cfg=$_[1]" },
96     'enable-coverage+' => \$enable_coverage,
97 );
98
99 $tesh_file = pop @ARGV;
100
101 print "Enable coverage\n" if ($enable_coverage);
102
103 if ($diff_tool) {
104     use File::Temp qw/ tempfile /;
105     ( $diff_tool_tmp_fh, $diff_tool_tmp_filename ) = tempfile();
106     print "New tesh: $diff_tool_tmp_filename\n";
107 }
108
109 if ( $tesh_file =~ m/(.*)\.tesh/ ) {
110     $tesh_name = $1;
111     print "Test suite `$tesh_name'\n";
112 } else {
113     $tesh_file = "(stdin)";
114     $tesh_name = "(stdin)";
115     print "Test suite from stdin\n";
116 }
117
118 ###########################################################################
119
120 sub exit_status {
121     my $status = shift;
122     if ( WIFEXITED($status) ) {
123         $exitcode = WEXITSTATUS($status) + 40;
124         return "returned code " . WEXITSTATUS($status);
125     } elsif ( WIFSIGNALED($status) ) {
126         my $code;
127         if    ( WTERMSIG($status) == SIGINT )  { $code = "SIGINT"; }
128         elsif ( WTERMSIG($status) == SIGTERM ) { $code = "SIGTERM"; }
129         elsif ( WTERMSIG($status) == SIGKILL ) { $code = "SIGKILL"; }
130         elsif ( WTERMSIG($status) == SIGABRT ) { $code = "SIGABRT"; }
131         elsif ( WTERMSIG($status) == SIGSEGV ) { $code = "SIGSEGV"; }
132         $exitcode = WTERMSIG($status) + 4;
133         return "got signal $code";
134     }
135     return "Unparsable status. Is the process stopped?";
136 }
137
138 sub exec_cmd {
139     my %cmd = %{ $_[0] };
140     if ( $opts{'debug'} ) {
141         map { print "IN: $_\n" } @{ $cmd{'in'} };
142         map { print "OUT: $_\n" } @{ $cmd{'out'} };
143         print "CMD: $cmd{'cmd'}\n";
144     }
145
146     # cleanup the command line
147     if (RUNNING_ON_WINDOWS) {
148         var_subst( $cmd{'cmd'}, "EXEEXT", ".exe" );
149     } else {
150         var_subst( $cmd{'cmd'}, "EXEEXT", "" );
151     }
152
153     # substitute environ variables
154     foreach my $key ( keys %environ ) {
155         $cmd{'cmd'} = var_subst( $cmd{'cmd'}, $key, $environ{$key} );
156     }
157
158     # substitute remaining variables, if any
159     while ( $cmd{'cmd'} =~ /\${(\w+)(?::[=-][^}]*)?}/ ) {
160         $cmd{'cmd'} = var_subst( $cmd{'cmd'}, $1, "" );
161     }
162     while ( $cmd{'cmd'} =~ /\$(\w+)/ ) {
163         $cmd{'cmd'} = var_subst( $cmd{'cmd'}, $1, "" );
164     }
165
166     # add cfg options
167     $cmd{'cmd'} .= " $opts{'cfg'}"
168       if ( defined( $opts{'cfg'} ) && length( $opts{'cfg'} ) );
169
170     # finally trim any remaining space chars
171     $cmd{'cmd'} =~ s/^\s+//;
172     $cmd{'cmd'} =~ s/\s+$//;
173
174     print "[$tesh_name:$cmd{'line'}] $cmd{'cmd'}\n";
175
176     $cmd{'return'} ||= 0;
177     $cmd{'timeout'} ||= $opts{'timeout'};
178     
179
180     ###
181     # exec the command line
182
183     my @cmdline = quotewords( '\s+', 0, $cmd{'cmd'} );
184     my $input = defined($cmd{'in'})? join("\n",@{$cmd{'in'}}) : "";
185     my $output = " " x 10240; $output = ""; # Preallocate 10kB, and reset length to 0
186     $cmd{'got'} = \$output;
187     $cmd{'job'} = start \@cmdline, '<', \$input, '>&', \$output, timeout($cmd{'timeout'});
188
189     if ( $cmd{'background'} ) {
190         # Just enqueue the job. It will be dealed with at the end
191         push @bg_cmds, \%cmd;
192     } else {
193         # Deal with its ending conditions right away
194         analyze_result( \%cmd );
195     }
196 }
197
198 sub analyze_result {
199     my %cmd    = %{ $_[0] };
200     
201     eval {
202         finish( $cmd{'job'} );
203     };
204     if ($@) {
205         if ($@ =~ /timeout/) {
206             $cmd{'job'}->kill_kill;
207             $cmd{'timeouted'} = 1;
208         } elsif ($@ =~ /^ack / and $@ =~ /pipe/) {
209             print STDERR "Tesh: Broken pipe (ignored).\n";
210         } else {
211             die $@; # Don't know what it is, so let it go.
212         }
213     } 
214     $cmd{'timeouted'} ||= 0;
215     
216     my $gotret = $cmd{'gotret'} = exit_status($?); 
217
218     my $wantret;
219
220     if ( defined( $cmd{'expect'} ) and ( $cmd{'expect'} ne "" ) ) {
221         $wantret = "got signal $cmd{'expect'}";
222     } else {
223         $wantret = "returned code " . ( defined( $cmd{'return'} ) ? $cmd{'return'} : 0 );
224     }
225
226     # pop all output from executing child
227     my @got;
228     map { print "GOT: $_\n" } ${$cmd{'got'}} if $opts{'debug'};
229     foreach my $got ( split("\n", ${$cmd{'got'}}) ) {
230         $got =~ s/\r//g;
231         chomp $got;
232         print $diff_tool_tmp_fh "> $got\n" if ($diff_tool);
233
234         unless ( $enable_coverage and $got =~ /^profiling:/ ) {
235             push @got, $got;
236         }
237     }
238
239     if ( $cmd{'sort'} ) {
240
241         # Save the unsorted observed output to report it on error.
242         map { push @{ $cmd{'unsorted got'} }, $_ } @got;
243
244         sub mysort {
245             substr( $a, 0, $sort_prefix ) cmp substr( $b, 0, $sort_prefix );
246         }
247         use sort 'stable';
248         if ( $sort_prefix > 0 ) {
249             @got = sort mysort @got;
250         } else {
251             @got = sort @got;
252         }
253         while ( @got and $got[0] eq "" ) {
254             shift @got;
255         }
256
257         # Sort the expected output to make it easier to write for humans
258         if ( defined( $cmd{'out'} ) ) {
259             if ( $sort_prefix > 0 ) {
260                 @{ $cmd{'out'} } = sort mysort @{ $cmd{'out'} };
261             } else {
262                 @{ $cmd{'out'} } = sort @{ $cmd{'out'} };
263             }
264             while ( @{ $cmd{'out'} } and ${ $cmd{'out'} }[0] eq "" ) {
265                 shift @{ $cmd{'out'} };
266             }
267         }
268     }
269
270     # Did we timeout?
271
272     if ( $cmd{'timeouted'} ) {
273         $gotret   = "timeout after $cmd{'timeout'} sec";
274         $error    = 1;
275         $exitcode = 3;
276         print STDERR "<$cmd{'file'}:$cmd{'line'}> timeouted. Kill the process.\n";
277     }
278     if ( $gotret ne $wantret ) {
279         $error = 1;
280         my $msg = "Test suite `$cmd{'file'}': NOK (<$cmd{'file'}:$cmd{'line'}> $gotret)\n";
281         if ( scalar @got ) {
282             $msg = $msg . "Output of <$cmd{'file'}:$cmd{'line'}> so far:\n";
283             map { $msg .= "|| $_\n" } @got;
284         } else {
285             $msg .= "<$cmd{'file'}:$cmd{'line'}> No output so far.\n";
286         }
287         print STDERR "$msg";
288     }
289
290     # Does the output match?
291     my $diff;
292     if ( defined( $cmd{'output display'} ) ) {
293         print "[Tesh/INFO] Here is the (ignored) command output:\n";
294         map { print "||$_\n" } @got;
295     } elsif ( defined( $cmd{'output ignore'} ) ) {
296         print "(ignoring the output of <$cmd{'file'}:$cmd{'line'}> as requested)\n";
297     } else {
298         $diff = build_diff( \@{ $cmd{'out'} }, \@got );
299     }
300     if ( length $diff ) {
301         print "Output of <$cmd{'file'}:$cmd{'line'}> mismatch" . ( $cmd{'sort'} ? " (even after sorting)" : "" ) . ":\n";
302         map { print "$_\n" } split( /\n/, $diff );
303         if ( $cmd{'sort'} ) {
304             print "WARNING: Both the observed output and expected output were sorted as requested.\n";
305             print "WARNING: Output were only sorted using the $sort_prefix first chars.\n"
306               if ( $sort_prefix > 0 );
307             print "WARNING: Use <! output sort 19> to sort by simulated date and process ID only.\n";
308
309             # print "----8<---------------  Begin of unprocessed observed output (as it should appear in file):\n";
310             # map {print "> $_\n"} @{$cmd{'unsorted got'}};
311             # print "--------------->8----  End of the unprocessed observed output.\n";
312         }
313
314         print "Test suite `$cmd{'file'}': NOK (<$cmd{'file'}:$cmd{'line'}> output mismatch)\n";
315         exit 2;
316     }
317 }
318
319 # parse tesh file
320 my $infh;    # The file descriptor from which we should read the teshfile
321 if ( $tesh_file eq "(stdin)" ) {
322     $infh = *STDIN;
323 } else {
324     open $infh, $tesh_file
325       or die "[Tesh/CRITICAL] Unable to open $tesh_file: $!\n";
326 }
327
328 my %cmd;     # everything about the next command to run
329 my $line_num = 0;
330 LINE: while ( defined( my $line = <$infh> ) and not $error ) {
331     chomp $line;
332     $line =~ s/\r//g;
333
334     $line_num++;
335     print "[TESH/debug] $line_num: $line\n" if $opts{'debug'};
336
337     # deal with line continuations
338     while ( $line =~ /^(.*?)\\$/ ) {
339         my $next = <$infh>;
340         die "[TESH/CRITICAL] Continued line at end of file\n"
341           unless defined($next);
342         $line_num++;
343         chomp $next;
344         print "[TESH/debug] $line_num: $next\n" if $opts{'debug'};
345         $line = $1 . $next;
346     }
347
348     # Push delayed commands on empty lines
349     unless ( $line =~ m/^(.)(.*)$/ ) {
350         if ( defined( $cmd{'cmd'} ) ) {
351             exec_cmd( \%cmd );
352             %cmd = ();
353         }
354         print $diff_tool_tmp_fh "$line\n" if ($diff_tool);
355         next LINE;
356     }
357
358     my ( $cmd, $arg ) = ( $1, $2 );
359     print $diff_tool_tmp_fh "$line\n" if ( $diff_tool and $cmd ne '>' );
360     $arg =~ s/^ //g;
361     $arg =~ s/\r//g;
362     $arg =~ s/\\\\/\\/g;
363
364     # handle the commands
365     if ( $cmd =~ /^#/ ) {    # comment
366     } elsif ( $cmd eq '>' ) {    # expected result line
367         print "[TESH/debug] push expected result\n" if $opts{'debug'};
368         push @{ $cmd{'out'} }, $arg;
369
370     } elsif ( $cmd eq '<' ) {    # provided input
371         print "[TESH/debug] push provided input\n" if $opts{'debug'};
372         push @{ $cmd{'in'} }, $arg;
373
374     } elsif ( $cmd eq 'p' ) {    # comment
375         print "[$tesh_name:$line_num] $arg\n";
376
377     } elsif ( $cmd eq '$' ) {    # Command
378                                  # if we have something buffered, run it now
379         if ( defined( $cmd{'cmd'} ) ) {
380             exec_cmd( \%cmd );
381             %cmd = ();
382         }
383         if ( $arg =~ /^\s*mkfile / ) {    # "mkfile" command line
384             die "[TESH/CRITICAL] Output expected from mkfile command!\n"
385               if scalar @{ cmd { 'out' } };
386
387             $cmd{'arg'} = $arg;
388             $cmd{'arg'} =~ s/\s*mkfile //;
389             mkfile_cmd( \%cmd );
390             %cmd = ();
391
392         } elsif ( $arg =~ /^\s*cd / ) {
393             die "[TESH/CRITICAL] Input provided to cd command!\n"
394               if scalar @{ cmd { 'in' } };
395             die "[TESH/CRITICAL] Output expected from cd command!\n"
396               if scalar @{ cmd { 'out' } };
397
398             $arg =~ s/^ *cd //;
399             cd_cmd($arg);
400             %cmd = ();
401
402         } else {    # regular command
403             $cmd{'cmd'}  = $arg;
404             $cmd{'file'} = $tesh_file;
405             $cmd{'line'} = $line_num;
406         }
407     } elsif ( $cmd eq '&' ) {    # background command line
408
409         if ( defined( $cmd{'cmd'} ) ) {
410             exec_cmd( \%cmd );
411             %cmd = ();
412         }
413         $cmd{'background'} = 1;
414         $cmd{'cmd'}        = $arg;
415         $cmd{'file'}       = $tesh_file;
416         $cmd{'line'}       = $line_num;
417
418     } elsif ( $line =~ /^!\s*output sort/ ) {    #output sort
419         if ( defined( $cmd{'cmd'} ) ) {
420             exec_cmd( \%cmd );
421             %cmd = ();
422         }
423         $cmd{'sort'} = 1;
424         if ( $line =~ /^!\s*output sort\s+(\d+)/ ) {
425             $sort_prefix = $1;
426         }
427     } elsif ( $line =~ /^!\s*output ignore/ ) {    #output ignore
428         if ( defined( $cmd{'cmd'} ) ) {
429             exec_cmd( \%cmd );
430             %cmd = ();
431         }
432         $cmd{'output ignore'} = 1;
433     } elsif ( $line =~ /^!\s*output display/ ) {    #output display
434         if ( defined( $cmd{'cmd'} ) ) {
435             exec_cmd( \%cmd );
436             %cmd = ();
437         }
438         $cmd{'output display'} = 1;
439     } elsif ( $line =~ /^!\s*expect signal (\w*)/ ) {    #expect signal SIGABRT
440         if ( defined( $cmd{'cmd'} ) ) {
441             exec_cmd( \%cmd );
442             %cmd = ();
443         }
444         $cmd{'expect'} = "$1";
445     } elsif ( $line =~ /^!\s*expect return/ ) {          #expect return
446         if ( defined( $cmd{'cmd'} ) ) {
447             exec_cmd( \%cmd );
448             %cmd = ();
449         }
450         $line =~ s/^! expect return //g;
451         $line =~ s/\r//g;
452         $cmd{'return'} = $line;
453     } elsif ( $line =~ /^!\s*setenv/ ) {                 #setenv
454         if ( defined( $cmd{'cmd'} ) ) {
455             exec_cmd( \%cmd );
456             %cmd = ();
457         }
458         $line =~ s/^! setenv //g;
459         $line =~ s/\r//g;
460         setenv_cmd($line);
461     } elsif ( $line =~ /^!\s*timeout/ ) {                #timeout
462         if ( defined( $cmd{'cmd'} ) ) {
463             exec_cmd( \%cmd );
464             %cmd = ();
465         }
466         $line =~ s/^! timeout //;
467         $line =~ s/\r//g;
468         $cmd{'timeout'} = $line;
469     } else {
470         die "[TESH/CRITICAL] parse error: $line\n";
471     }
472 }
473
474 # We're done reading the input file
475 close $infh unless ( $tesh_file eq "(stdin)" );
476
477 # Deal with last command
478 if ( defined( $cmd{'cmd'} ) ) {
479     exec_cmd( \%cmd );
480     %cmd = ();
481 }
482
483 foreach (@bg_cmds) {
484     my %test = %{$_};
485     analyze_result( \%test );
486 }
487
488 if ($diff_tool) {
489     close $diff_tool_tmp_fh;
490     system("$diff_tool $diff_tool_tmp_filename $tesh_file");
491     unlink $diff_tool_tmp_filename;
492 }
493
494 if ( $error != 0 ) {
495     exit $exitcode;
496 } elsif ( $tesh_file eq "(stdin)" ) {
497     print "Test suite from stdin OK\n";
498 } else {
499     print "Test suite `$tesh_name' OK\n";
500 }
501
502 exit 0;
503
504 ####
505 #### Helper functions
506 ####
507
508 sub build_diff {
509     my $res;
510     my $diff = Diff->new(@_);
511
512     $diff->Base(1);    # Return line numbers, not indices
513     my $chunk_count = $diff->Next(-1);    # Compute the amount of chuncks
514     return "" if ( $chunk_count == 1 && $diff->Same() );
515     $diff->Reset();
516     while ( $diff->Next() ) {
517         my @same = $diff->Same();
518         if ( $diff->Same() ) {
519             if ( $diff->Next(0) > 1 ) {    # not first chunk: print 2 first lines
520                 $res .= '  ' . $same[0] . "\n";
521                 $res .= '  ' . $same[1] . "\n" if ( scalar @same > 1 );
522             }
523             $res .= "...\n" if ( scalar @same > 2 );
524
525             #    $res .= $diff->Next(0)."/$chunk_count\n";
526             if ( $diff->Next(0) < $chunk_count ) {    # not last chunk: print 2 last lines
527                 $res .= '  ' . $same[ scalar @same - 2 ] . "\n"
528                   if ( scalar @same > 1 );
529                 $res .= '  ' . $same[ scalar @same - 1 ] . "\n";
530             }
531         }
532         next if $diff->Same();
533         map { $res .= "- $_\n" } $diff->Items(1);
534         map { $res .= "+ $_\n" } $diff->Items(2);
535     }
536     return $res;
537 }
538
539 # Helper function replacing any occurence of variable '$name' by its '$value'
540 # As in Bash, ${$value:=BLABLA} is rewritten to $value if set or to BLABLA if $value is not set
541 sub var_subst {
542     my ( $text, $name, $value ) = @_;
543     if ($value) {
544         $text =~ s/\${$name(?::[=-][^}]*)?}/$value/g;
545         $text =~ s/\$$name(\W|$)/$value$1/g;
546     } else {
547         $text =~ s/\${$name:=([^}]*)}/$1/g;
548         $text =~ s/\${$name}//g;
549         $text =~ s/\$$name(\W|$)/$1/g;
550     }
551     return $text;
552 }
553
554 ################################  The possible commands  ################################
555
556 sub mkfile_cmd($) {
557     my %cmd  = %{ $_[0] };
558     my $file = $cmd{'arg'};
559     print STDERR "[Tesh/INFO] mkfile $file. Ctn: >>".join( '\n', @{ $cmd{'in'} })."<<\n"
560       if $opts{'debug'};
561
562     unlink($file);
563     open( FILE, ">$file" )
564       or die "[Tesh/CRITICAL] Unable to create file $file: $!\n";
565     print FILE join( "\n", @{ $cmd{'in'} } );
566     print FILE "\n" if ( scalar @{ $cmd{'in'} } > 0 );
567     close(FILE);
568 }
569
570 # Command CD. Just change to the provided directory
571 sub cd_cmd($) {
572     my $directory = shift;
573     my $failure   = 1;
574     if ( -e $directory && -d $directory ) {
575         chdir("$directory");
576         print "[Tesh/INFO] change directory to $directory\n";
577         $failure = 0;
578     } elsif ( -e $directory ) {
579         print "Cannot change directory to '$directory': it is not a directory\n";
580     } else {
581         print "Chdir to $directory failed: No such file or directory\n";
582     }
583     if ( $failure == 1 ) {
584         print "Test suite `$tesh_file': NOK (system error)\n";
585         exit 4;
586     }
587 }
588
589 # Command setenv. Gets "variable=content", and update the environment accordingly
590 sub setenv_cmd($) {
591     my $arg = shift;
592     if ( $arg =~ /^(.*)=(.*)$/ ) {
593         my ( $var, $ctn ) = ( $1, $2 );
594         print "[Tesh/INFO] setenv $var=$ctn\n";
595         $environ{$var} = $ctn;
596         $ENV{$var} = $ctn;
597     } else {
598         die "[Tesh/CRITICAL] Malformed argument to setenv: expected 'name=value' but got '$arg'\n";
599     }
600 }