Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Merge branch 'master' of scm.gforge.inria.fr:/gitroot/simgrid/simgrid
[simgrid.git] / buildtools / Cmake / Scripts / tesh.pl
1 #! /usr/bin/perl
2
3 # Copyright (c) 2012-2014. 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
9 eval 'exec perl -S $0 ${1+"$@"}'
10   if $running_under_some_shell;
11
12 =encoding UTF-8
13
14 =head1 NAME
15
16 tesh -- testing shell
17
18 =head1 SYNOPSIS
19
20 B<tesh> [I<options>] I<tesh_file>
21
22 =cut
23 my($bindir)=".";
24 my($srcdir)=".";
25 my($timeout)=0;
26 my($time_to_wait)=0;
27 my $path = $0;
28 my $OS;
29 my $enable_coverage=0;
30 my $sort_prefix = 19;
31 my $tesh_file;
32 my $tesh_name;
33 my $error=0;
34 my $exitcode=0;
35 my @bg_cmds;
36 my (%environ);
37
38 $path =~ s|[^/]*$||;
39 push @INC,$path;
40
41 use Getopt::Long qw(GetOptions);
42 use strict;
43 use Term::ANSIColor;
44 use Text::ParseWords;
45 use IPC::Open3;
46 use IO::File;
47
48 if($^O eq "linux"){
49     $OS = "UNIX";
50 }
51 else{
52     $OS = "WIN";
53     $ENV{"PRINTF_EXPONENT_DIGITS"} = "2"; 
54 }
55
56 ##
57 ## Command line option handling
58 ##
59
60 sub var_subst {
61     my ($text, $name, $value) = @_;
62     if ($value) {
63         $text =~ s/\${$name(?::[=-][^}]*)?}/$value/g;
64         $text =~ s/\$$name(\W|$)/$value$1/g;
65     }
66     else {
67         $text =~ s/\${$name:=([^}]*)}/$1/g;
68         $text =~ s/\${$name}//g;
69         $text =~ s/\$$name(\W|$)/$1/g;
70     }
71     return $text;
72 }
73
74 # option handling helper subs
75 sub cd_cmd {
76   my $directory=$_[1];
77   my $failure=1;
78   if (-e $directory && -d $directory) {
79     chdir("$directory");
80     print "[Tesh/INFO] change directory to $directory\n";
81   $failure=0;
82   } elsif (-e $directory) {
83     print "Cannot change directory to '$directory': it is not a directory\n";
84   } else {
85     print "Chdir to $directory failed: No such file or directory\n";
86   }
87   if($failure==1){
88   $error=1;
89   $exitcode=4;
90   print "Test suite `$tesh_file': NOK (system error)\n";
91   exit 4;
92   }
93 }
94
95 sub setenv_cmd {
96   my($var,$ctn);
97   if ($_[0] =~ /^(.*)=(.*)$/) {
98     ($var,$ctn)=($1,$2);
99   }elsif ($_[1] =~ /^(.*)=(.*)$/) {
100     ($var,$ctn)=($1,$2);
101   } else { 
102       die "[Tesh/CRITICAL] Malformed argument to setenv: expected 'name=value' but got '$_[1]'\n";
103   }
104     
105   print "[Tesh/INFO] setenv $var=$ctn\n";
106   $environ{$var} = $ctn;
107 }
108
109 # Main option parsing sub
110
111 sub get_options {
112   # remove the tesh file from the ARGV used
113   my @ARGV = @_;
114   $tesh_file = pop @ARGV;
115
116   # temporary arrays for GetOption
117   my @verbose = ();
118   my @cfg;
119   my $log; # ignored
120
121
122   my %opt = (
123     "help"  => 0,
124     "debug"   => 0,
125     "verbose" => 0
126     );
127
128   Getopt::Long::config('bundling', 'no_getopt_compat', 'no_auto_abbrev');
129   
130   GetOptions(
131     'help|h'   => \$opt{'help'},
132
133     'verbose|v'  => \@verbose,
134     'debug|d'  => \$opt{"debug"},
135
136     'cd=s'     => \&cd_cmd,
137     'timeout=s'  => \$opt{'timeout'},    
138     'setenv=s'   => \&setenv_cmd,
139     'cfg=s'    => \@cfg,
140     'log=s'    => \$log,
141     'enable-coverage+'  => \$enable_coverage,    
142     );
143
144   if($enable_coverage){
145     print "Enable coverage\n";
146   }
147
148   unless($tesh_file=~/(.*)\.tesh/){
149     $tesh_file="(stdin)";
150     $tesh_name="(stdin)";
151     print "Test suite from stdin\n";
152   }else{
153     $tesh_name=$1;
154     print "Test suite `$tesh_name'\n";
155   }
156
157   $opt{'verbose'} = scalar @verbose;
158   foreach (@cfg) {
159     $opt{'cfg'} .= " --cfg=$_";
160   }
161   return %opt;
162 }
163
164 my %opts = get_options(@ARGV);
165
166 ##
167 ## File parsing
168 ##
169 my($nb_arg)=0;
170 my($old_buffer);
171 my($linebis);
172 my($SIGABRT)=0;
173 my($verbose)=0;
174 my($return)=-1;
175 my($pid);
176 my($result);
177 my($result_err);
178 my($forked);
179 my($config)="";
180 my($tesh_command)=0;
181 my(@buffer_tesh)=();
182
183 #eval {
184   use POSIX;
185
186   sub exit_status {
187     my $status = shift;
188     if (POSIX::WIFEXITED($status)) {
189       $exitcode=POSIX::WEXITSTATUS($status)+40;
190       return "returned code ".POSIX::WEXITSTATUS($status);
191     } elsif (POSIX::WIFSIGNALED($status)) {
192       my $code;
193       if (POSIX::WTERMSIG($status) == SIGINT){$code="SIGINT"; }
194       elsif  (POSIX::WTERMSIG($status) == SIGTERM) {$code="SIGTERM"; }
195       elsif  (POSIX::WTERMSIG($status) == SIGKILL) {$code= "SIGKILL"; }
196       elsif  (POSIX::WTERMSIG($status) == SIGABRT) {$code="SIGABRT"; }
197       elsif  (POSIX::WTERMSIG($status) == SIGSEGV) {$code="SIGSEGV" ;}
198       $exitcode=POSIX::WTERMSIG($status)+4;
199       return "got signal $code";
200     }
201     return "Unparsable status. Is the process stopped?";
202   }
203 #};
204 #if ($@) { # no POSIX available?
205 #  warn "POSIX not usable to parse the return value of forked child: $@\n";
206 #  sub exit_status {
207 #    return "returned code -1 $@ ";
208 #  }
209 #}
210
211 sub exec_cmd { 
212   my %cmd = %{$_[0]};
213   if ($opts{'debug'}) {
214     print "IN BEGIN\n";
215     map {print "  $_"} @{$cmd{'in'}};
216     print "IN END\n";
217     print "OUT BEGIN\n";
218     map {print "  $_"} @{$cmd{'out'}};
219     print "OUT END\n";
220     print "CMD: $cmd{'cmd'}\n";
221   }
222
223   # cleanup the command line
224   if($OS eq "WIN") {
225       var_subst($cmd{'cmd'}, "EXEEXT", ".exe");
226   } else {
227       var_subst($cmd{'cmd'}, "EXEEXT", "");
228   }
229
230   # substitute environ variables
231   foreach my $key (keys %environ) {
232       $cmd{'cmd'} = var_subst($cmd{'cmd'}, $key, $environ{$key});
233   }
234   # substitute remaining variables, if any
235   while ($cmd{'cmd'} =~ /\${(\w+)(?::[=-][^}]*)?}/) {
236       $cmd{'cmd'} = var_subst($cmd{'cmd'}, $1, "");
237   }
238   while ($cmd{'cmd'} =~ /\$(\w+)/) {
239       $cmd{'cmd'} = var_subst($cmd{'cmd'}, $1, "");
240   }
241
242   # add cfg options
243   $cmd{'cmd'} .= " $opts{'cfg'}" if (defined($opts{'cfg'}) && length($opts{'cfg'}));
244
245   # final cleanup
246   $cmd{'cmd'} =~ s/^\s+//;
247   $cmd{'cmd'} =~ s/\s+$//;
248
249   print "[$tesh_name:$cmd{'line'}] $cmd{'cmd'}\n" ;
250
251   ###
252   # exec the command line
253   ###  $line =~ s/\r//g;
254
255   $cmd{'got'} = IO::File->new_tmpfile;
256   $cmd{'got'}->autoflush(1);
257   local *E = $cmd{'got'}; 
258   $cmd{'pid'} = open3(\*CHILD_IN,  ">&E",  ">&E",
259                       quotewords('\s+', 0, $cmd{'cmd'}));
260
261   # push all provided input to executing child
262   map { print CHILD_IN "$_\n"; }  @{$cmd{'in'}};
263   close CHILD_IN;
264
265   # if timeout specified, fork and kill executing child at the end of timeout
266   if (defined($cmd{'timeout'}) or defined($opts{'timeout'})){
267     $time_to_wait= defined($cmd{'timeout'}) ? $cmd{'timeout'} : $opts{'timeout'};
268     $forked = fork();
269     $timeout=-1;
270     die "fork() failed: $!" unless defined $forked;
271     if ( $forked == 0 ) { # child
272       sleep $time_to_wait;
273       kill(SIGKILL, $cmd{'pid'});
274       exit $time_to_wait;
275     }
276   }
277
278   
279   # Cleanup the executing child, and kill the timeouter brother on need
280   $cmd{'return'} = 0 unless defined($cmd{'return'});
281   if($cmd{'background'} != 1){
282     waitpid ($cmd{'pid'}, 0);
283     $cmd{'gotret'} = exit_status($?);
284     parse_out(\%cmd);
285   }else{
286     # & commands, which will be handled at the end
287     push @bg_cmds, \%cmd;
288     # no timeout for background commands
289     if($forked){
290        kill(SIGKILL, $forked);
291        $timeout=0;
292        $forked=0;
293     }
294   }
295 }
296
297
298 sub parse_out { 
299   my %cmd = %{$_[0]};
300   my $gotret=$cmd{'gotret'};
301
302   my $wantret;
303
304   if(defined($cmd{'expect'}) and ($cmd{'expect'} ne "")){
305     $wantret = "got signal $cmd{'expect'}";
306   }else{
307     $wantret = "returned code ".(defined($cmd{'return'})? $cmd{'return'} : 0);
308   }
309
310   local *got = $cmd{'got'};
311   seek(got,0,0);
312   # pop all output from executing child
313   my @got;
314   while(defined(my $got=<got>)) {
315     $got =~ s/\r//g;
316     chomp $got;
317     if (!($enable_coverage and $got=~ /^profiling:/)){
318       push @got, $got;
319     }
320   }    
321
322   if ($cmd{'sort'}){   
323     sub mysort{
324         substr($a, 0, $sort_prefix) cmp substr($b, 0, $sort_prefix)
325     }
326     use sort 'stable';
327     @got = sort mysort @got;
328     while (@got and $got[0] eq "") {
329       shift @got;
330     }
331
332     #also resort the other one, as perl sort is not the same as the C one used to generate teshes
333     if(defined($cmd{'out'})){
334       @{$cmd{'out'}}=sort mysort @{$cmd{'out'}};
335       while (@{$cmd{'out'}} and ${$cmd{'out'}}[0] eq "") {
336         shift @{$cmd{'out'}};
337       }
338     }
339   }
340
341   #Did we timeout ? If yes, handle it. If not, kill the forked process.
342
343   if($timeout==-1 and $gotret eq "got signal SIGKILL"){
344     $gotret="return code 0";
345     $timeout=1;
346     $gotret= "timeout after $time_to_wait sec";
347     $error=1;
348     $exitcode=3;
349     print STDERR "<$cmd{'file'}:$cmd{'line'}> timeouted. Kill the process.\n";
350   }else{
351     $timeout=0;  
352   }
353   if($gotret ne $wantret) {
354     $error=1;
355     my $msg = "Test suite `$cmd{'file'}': NOK (<$cmd{'file'}:$cmd{'line'}> $gotret)\n";
356     if ($timeout!=1) {
357         $msg=$msg."Output of <$cmd{'file'}:$cmd{'line'}> so far:\n";    
358     }
359     map {$msg .=  "|| $_\n"} @got;
360     if(!@got) {
361         if($timeout==1){
362         print STDERR "<$cmd{'file'}:$cmd{'line'}> No output before timeout\n";
363         }else{
364         $msg .= "||\n";
365         }
366     }
367     $timeout = 0;
368     print STDERR "$msg";
369   }
370
371       
372   ###
373   # Check the result of execution 
374   ###
375   my $diff;
376   if (defined($cmd{'output display'})){
377     print "[Tesh/INFO] Here is the (ignored) command output:\n";
378     map { print "||$_\n" } \@got;
379   }
380   elsif (!defined($cmd{'output ignore'})){
381     $diff = build_diff(\@{$cmd{'out'}}, \@got);
382   }else{
383     print "(ignoring the output of <$cmd{'file'}:$cmd{'line'}> as requested)\n"
384   }
385   if (length $diff) {
386     print "Output of <$cmd{'file'}:$cmd{'line'}> mismatch:\n";
387     map { print "$_\n" } split(/\n/,$diff);
388
389     print "Test suite `$cmd{'file'}': NOK (<$cmd{'file'}:$cmd{'line'}> output mismatch)\n";
390     $error=1;
391     $exitcode=2;
392   }
393 }
394
395 sub mkfile_cmd {
396   my %cmd = %{$_[0]};
397   my $file = $cmd{'arg'};
398   print "[Tesh/INFO] mkfile $file\n";
399
400   unlink($file);
401   open(FILE,">$file") or die "[Tesh/CRITICAL] Unable to create file $file: $!\n";
402   print FILE join("\n", @{$cmd{'in'}});
403   print FILE "\n" if (scalar @{$cmd{'in'}} > 0);
404   close(FILE);
405 }
406
407 # parse tesh file
408 #my $teshfile=$tesh_file;
409 #$teshfile=~ s{\.[^.]+$}{};
410
411 unless($tesh_file eq "(stdin)"){
412   open TESH_FILE, $tesh_file or die "[Tesh/CRITICAL] Unable to open $tesh_file $!\n";
413 }
414
415 my %cmd; # everything about the next command to run
416 my $line_num=0;
417 my $finished =0;
418 LINE: while (not $finished and not $error) {
419   my $line;
420
421
422   if ($tesh_file ne "(stdin)" and !defined($line=<TESH_FILE>)){
423     $finished=1;
424     next LINE;
425   }elsif ($tesh_file eq "(stdin)" and !defined($line=<>)){
426     $finished=1;
427     next LINE;
428   }
429
430
431   $line_num++;
432   chomp $line;
433   $line =~ s/\r//g;
434   print "[TESH/debug] $line_num: $line\n" if $opts{'debug'};
435   my $next;
436   # deal with line continuations
437   while ($line =~ /^(.*?)\\$/) {
438     $next=<TESH_FILE>;
439     die "[TESH/CRITICAL] Continued line at end of file\n"
440       unless defined($next);
441     $line_num++;
442     chomp $next;
443     print "[TESH/debug] $line_num: $next\n" if $opts{'debug'};
444     $line = $1.$next;
445   }
446
447   # Push delayed commands on empty lines
448   unless ($line =~ m/^(.)(.*)$/) {
449     if (defined($cmd{'cmd'}))  {
450       exec_cmd(\%cmd);
451       %cmd = ();
452     }
453     next LINE;
454   }     
455  
456   my ($cmd,$arg) = ($1,$2);
457   $arg =~ s/^ //g;
458   $arg =~ s/\r//g;
459   $arg =~ s/\\\\/\\/g;
460   # handle the commands
461   if ($cmd =~ /^#/) {    #comment
462   } elsif ($cmd eq '>'){    #expected result line
463     print "[TESH/debug] push expected result\n" if $opts{'debug'};
464     push @{$cmd{'out'}}, $arg;
465
466   } elsif ($cmd eq '<') {    # provided input
467     print "[TESH/debug] push provided input\n" if $opts{'debug'};
468     push @{$cmd{'in'}}, $arg;
469
470   } elsif ($cmd eq 'p') {    # comment
471     print "[$tesh_name:$line_num] $arg\n";
472
473   } elsif ($cmd eq '$') {  # Command
474     # if we have something buffered, run it now
475     if (defined($cmd{'cmd'})) {
476       exec_cmd(\%cmd);
477       %cmd = ();
478     }
479     if ($arg =~ /^\s*mkfile /){      # "mkfile" command line
480       die "[TESH/CRITICAL] Output expected from mkfile command!\n" if scalar @{cmd{'out'}};
481
482       $cmd{'arg'} = $arg;
483       $cmd{'arg'} =~ s/\s*mkfile //;
484       mkfile_cmd(\%cmd);
485       %cmd = ();
486
487     } elsif ($arg =~ /^\s*cd /) {
488       die "[TESH/CRITICAL] Input provided to cd command!\n" if scalar @{cmd{'in'}};
489       die "[TESH/CRITICAL] Output expected from cd command!\n" if scalar @{cmd{'out'}};
490
491       $arg =~ s/^ *cd //;
492       cd_cmd("",$arg);
493       %cmd = ();
494
495     } else { # regular command
496       $cmd{'cmd'} = $arg;
497       $cmd{'file'} = $tesh_file;
498       $cmd{'line'} = $line_num;
499     }
500   }
501   elsif($cmd eq '&'){      # parallel command line
502
503     if (defined($cmd{'cmd'})) {
504       exec_cmd(\%cmd);
505       %cmd = ();
506     }
507     $cmd{'background'} = 1;
508     $cmd{'cmd'} = $arg;
509     $cmd{'file'} = $tesh_file;
510     $cmd{'line'} = $line_num;
511   }    
512   elsif($line =~ /^!\s*output sort/){    #output sort
513     if (defined($cmd{'cmd'})) {
514       exec_cmd(\%cmd);
515       %cmd = ();
516     }
517     $cmd{'sort'} = 1;
518     if ($line =~ /^!\s*output sort\s+(\d+)/) {
519         $sort_prefix = $1;
520     }
521   }
522   elsif($line =~ /^!\s*output ignore/){    #output ignore
523     if (defined($cmd{'cmd'})) {
524       exec_cmd(\%cmd);
525       %cmd = ();
526     }
527     $cmd{'output ignore'} = 1;
528   }
529   elsif($line =~ /^!\s*output display/){    #output display
530     if (defined($cmd{'cmd'})) {
531       exec_cmd(\%cmd);
532       %cmd = ();
533     }
534     $cmd{'output display'} = 1;
535   }
536   elsif($line =~ /^!\s*expect signal (\w*)/) {#expect signal SIGABRT
537     if (defined($cmd{'cmd'})) {
538       exec_cmd(\%cmd);
539       %cmd = ();
540     }
541 print "hey\n";
542     $cmd{'expect'} = "$1";
543   }
544   elsif($line =~ /^!\s*expect return/){    #expect return
545     if (defined($cmd{'cmd'})) {
546       exec_cmd(\%cmd);
547       %cmd = ();
548     }
549     $line =~ s/^! expect return //g;
550     $line =~ s/\r//g;
551     $cmd{'return'} = $line;
552   }
553   elsif($line =~ /^!\s*setenv/){    #setenv
554     if (defined($cmd{'cmd'})) {
555       exec_cmd(\%cmd);
556       %cmd = ();
557     }
558     $line =~ s/^! setenv //g;
559     $line =~ s/\r//g;
560     setenv_cmd($line);
561   }
562   elsif($line =~ /^!\s*include/){    #include
563     if (defined($cmd{'cmd'})) {
564       exec_cmd(\%cmd);
565       %cmd = ();
566     }
567     print color("red"), "[Tesh/CRITICAL] need include";
568     print color("reset"), "\n";
569     die;
570   }
571   elsif($line =~ /^!\s*timeout/){    #timeout
572     if (defined($cmd{'cmd'})) {
573       exec_cmd(\%cmd);
574       %cmd = ();
575     }
576     $line =~ s/^! timeout //;
577     $line =~ s/\r//g;
578     $cmd{'timeout'} = $line;
579   } else {
580     die "[TESH/CRITICAL] parse error: $line\n";
581   }
582   if($forked){
583    kill(SIGKILL, $forked);
584    $timeout=0;
585   }
586
587 }
588
589
590
591 # Deal with last command
592 if (defined($cmd{'cmd'})) {
593   exec_cmd(\%cmd);
594   %cmd = ();
595 }
596
597
598 if($forked){
599    kill(SIGKILL, $forked);
600    $timeout=0;
601 }
602
603 foreach(@bg_cmds){
604   my %test=%{$_};
605   waitpid ($test{'pid'}, 0);
606   $test{'gotret'} = exit_status($?);
607   parse_out(\%test);
608 }
609
610 @bg_cmds=();
611
612
613 if($error !=0){
614     exit $exitcode;
615 }elsif($tesh_file eq "(stdin)"){
616     print "Test suite from stdin OK\n";
617 }else{
618     print "Test suite `$tesh_name' OK\n";
619 }
620
621 #my (@a,@b);
622 #push @a,"bl1";   push @b,"bl1";
623 #push @a,"bl2";   push @b,"bl2";
624 #push @a,"bl3";   push @b,"bl3";
625 #push @a,"bl4";   push @b,"bl4";
626 #push @a,"bl5";   push @b,"bl5";
627 #push @a,"bl6";   push @b,"bl6";
628 #push @a,"bl7";   push @b,"bl7";
629 ##push @a,"Perl";  push @b,"ruby";
630 #push @a,"END1";   push @b,"END1";
631 #push @a,"END2";   push @b,"END2";
632 #push @a,"END3";   push @b,"END3";
633 #push @a,"END4";   push @b,"END4";
634 #push @a,"END5";   push @b,"END5";
635 #push @a,"END6";   push @b,"END6";
636 #push @a,"END7";   push @b,"END7";
637 #print "Identical:\n". build_diff(\@a,\@b);
638
639 #@a = (); @b =();
640 #push @a,"AZE"; push @b,"EZA";
641 #print "Different:\n".build_diff(\@a,\@b);
642
643 use lib "@CMAKE_BINARY_DIR@/bin" ;
644
645 use Diff qw(diff); # postpone a bit to have time to change INC
646
647 sub build_diff {
648   my $res;
649   my $diff = Diff->new(@_);
650   
651   $diff->Base( 1 );   # Return line numbers, not indices
652   my $chunk_count = $diff->Next(-1); # Compute the amount of chuncks
653   return ""   if ($chunk_count == 1 && $diff->Same());
654   $diff->Reset();
655   while(  $diff->Next()  ) {
656     my @same = $diff->Same();
657     if ($diff->Same() ) {
658       if ($diff->Next(0) > 1) { # not first chunk: print 2 first lines
659         $res .= '  '.$same[0]."\n" ;
660         $res .= '  '.$same[1]."\n" if (scalar @same>1);
661       }     
662       $res .= "...\n"  if (scalar @same>2);
663 #    $res .= $diff->Next(0)."/$chunk_count\n";
664       if ($diff->Next(0) < $chunk_count) { # not last chunk: print 2 last lines
665         $res .= '  '.$same[scalar @same -2]."\n" if (scalar @same>1);
666         $res .= '  '.$same[scalar @same -1]."\n";
667       } 
668     } 
669     next if  $diff->Same();
670     map { $res .= "- $_\n" } $diff->Items(1);
671     map { $res .= "+ $_\n" } $diff->Items(2);
672   }
673   return $res;
674 }
675
676