Fix uninitialized perl variable error output
[buildfarm-client.git] / run_build.pl
1 #!/usr/bin/perl
2
3 =comment
4
5 Copyright (c) 2003-2010, Andrew Dunstan
6
7 See accompanying License file for license details
8
9 =cut 
10
11 ####################################################
12
13 =comment
14
15  NAME: run_build.pl - script to run exim buildfarm
16
17  SYNOPSIS:
18
19   run_build.pl [option ...] [branchname]
20
21  AUTHOR: Andrew Dunstan
22
23  DOCUMENTATION:
24
25   See http://wiki.exim.org/wiki/PostgreSQL_Buildfarm_Howto
26
27  REPOSITORY:
28
29   https://github.com/EximBuildFarm/client-code
30
31 =cut
32
33 ###################################################
34
35 use vars qw($VERSION); $VERSION = 'REL_0.1';
36
37 use strict;
38 use warnings;
39 use Config;
40 use Fcntl qw(:flock :seek);
41 use File::Path;
42 use File::Copy;
43 use File::Basename;
44 use File::Temp;
45 use File::Spec;
46 use IO::Handle;
47 use POSIX qw(:signal_h strftime);
48 use Data::Dumper;
49 use Cwd qw(abs_path getcwd);
50 use File::Find ();
51
52 # save a copy of the original enviroment for reporting
53 # save it early to reduce the risk of prior mangling
54 use vars qw($orig_env);
55
56 BEGIN
57 {
58     $orig_env = {};
59     while (my ($k,$v) = each %ENV)
60     {
61
62         # report all the keys but only values for whitelisted settings
63         # this is to stop leaking of things like passwords
64         $orig_env->{$k} =(
65             (
66                     $k =~ /^PG(?!PASSWORD)|MAKE|CC|CPP|FLAG|LIBRAR|INCLUDE/
67                   ||$k =~/^(HOME|LOGNAME|USER|PATH|SHELL)$/
68             )
69             ? $v
70             : 'xxxxxx'
71         );
72     }
73 }
74
75 use EximBuild::SCM;
76 use EximBuild::Options;
77 use EximBuild::WebTxn;
78
79 my %module_hooks;
80 my $orig_dir = getcwd();
81 push @INC, $orig_dir;
82
83 # make sure we exit nicely on any normal interrupt
84 # so the cleanup handler gets called.
85 # that lets us stop the db if it's running and
86 # remove the inst and exim directories
87 # so the next run can start clean.
88
89 foreach my $sig (qw(INT TERM HUP QUIT))
90 {
91     $SIG{$sig}=\&interrupt_exit;
92 }
93
94 # copy command line before processing - so we can later report it
95 # unmunged
96
97 my @invocation_args = (@ARGV);
98
99 # process the command line
100 EximBuild::Options::fetch_options();
101
102 die "only one of --from-source and --from-source-clean allowed"
103   if ($from_source && $from_source_clean);
104
105 die "only one of --skip-steps and --only-steps allowed"
106   if ($skip_steps && $only_steps);
107
108 $verbose=1 if (defined($verbose) && $verbose==0);
109 $verbose ||= 0; # stop complaints about undefined var in numeric comparison
110
111 if ($testmode)
112 {
113     $verbose=1 unless $verbose;
114     $forcerun = 1;
115     $nostatus = 1;
116     $nosend = 1;
117
118 }
119
120 use vars qw(%skip_steps %only_steps);
121 $skip_steps ||= "";
122 if ($skip_steps =~ /\S/)
123 {
124     %skip_steps = map {$_ => 1} split(/\s+/,$skip_steps);
125 }
126 $only_steps ||= "";
127 if ($only_steps =~ /\S/)
128 {
129     %only_steps = map {$_ => 1} split(/(\s+|[:,])/,$only_steps);
130 }
131
132 # Currently only specifying a branch is actually used.
133 # Specifying a different repo is just a wishlist item .
134 use vars qw($branch $repo);
135 my ($arg1,$arg2) = (shift,shift);
136 $branch = $arg2 ? $arg2 :
137           $arg1 ? $arg1 :
138           'HEAD';
139 $repo = $arg2 ? $arg1 : 'exim';
140 my $explicit_branch = $branch;
141
142 print_help() if ($help);
143
144 #
145 # process config file
146 #
147 require $buildconf;
148
149 # get the config data into some local variables
150 my (
151     $buildroot,$target,$animal, $print_success,
152     $aux_path,$trigger_exclude,$trigger_include,$secret,
153     $keep_errs,$force_every, $make, $optional_steps,
154     $use_vpath,$tar_log_cmd, $using_msvc, $extra_config,
155     $make_jobs, $core_file_glob
156   )
157   =@EximBuild::conf{
158     qw(build_root target animal print_success aux_path trigger_exclude
159       trigger_include secret keep_error_builds force_every make optional_steps
160       use_vpath tar_log_cmd using_msvc extra_config make_jobs core_file_glob)
161   };
162
163 #default is no parallel build
164 $make_jobs ||= 1;
165
166 # default core file pattern is Linux, which used to be hardcoded
167 $core_file_glob ||= 'core*';
168
169 # legacy name
170 if (defined($EximBuild::conf{trigger_filter}))
171 {
172     $trigger_exclude = $EximBuild::conf{trigger_filter};
173 }
174
175 my  $scm_timeout_secs = $EximBuild::conf{scm_timeout_secs}
176   || $EximBuild::conf{cvs_timeout_secs};
177
178 print scalar(localtime()),": buildfarm run for $animal:$branch starting\n"
179   if $verbose;
180
181 # Allow commandline overrides of conf variables
182 foreach my $arg ( @{$EximBuild::Options::overrides} )
183 {
184   if (my ($key,$val) = split '=', $arg)
185   {
186     $EximBuild::conf{$key} = $val;
187     printf "Commandline override: '$key' = '%s'\n", $EximBuild::conf{$key}
188       if $verbose;
189   }
190 }
191
192 if (ref($force_every) eq 'HASH')
193 {
194     $force_every = $force_every->{$branch} || $force_every->{default};
195 }
196
197 my $scm = new EximBuild::SCM \%EximBuild::conf;
198
199 my $buildport;
200
201 if (exists $EximBuild::conf{base_port})
202 {
203     $buildport = $EximBuild::conf{base_port};
204     if ($branch =~ /REL(\d+)_(\d+)/)
205     {
206         $buildport += (10 * ($1 - 7)) + $2;
207     }
208 }
209 else
210 {
211
212     # support for legacy config style
213     $buildport = $EximBuild::conf{branch_ports}->{$branch} || 5999;
214 }
215
216 $ENV{EXTRA_REGRESS_OPTS} = "--port=$buildport";
217
218 $tar_log_cmd ||= "tar -z -cf runlogs.tgz *.log";
219
220 my $logdirname = "lastrun-logs";
221
222 if ($from_source || $from_source_clean)
223 {
224     $from_source ||= $from_source_clean;
225     die "sourceroot $from_source not absolute"
226       unless $from_source =~ m!^/!;
227
228     # we need to know where the lock should go, so unless the path
229     # contains HEAD we require it to be specified.
230     die "must specify branch explicitly with from_source"
231       unless ($explicit_branch || $from_source =~ m!/HEAD/!);
232     $verbose ||= 1;
233     $nosend=1;
234     $nostatus=1;
235     $use_vpath = undef;
236     $logdirname = "fromsource-logs";
237 }
238
239 my @locales;
240 if ($branch eq 'HEAD' || $branch ge 'REL8_4')
241 {
242
243     # non-C locales are not regression-safe before 8.4
244     @locales = @{$EximBuild::conf{locales}} if exists $EximBuild::conf{locales};
245 }
246 unshift(@locales,'C') unless grep {$_ eq "C"} @locales;
247
248 # sanity checks
249 # several people have run into these
250
251 if ( `uname -s 2>&1 ` =~ /CYGWIN/i )
252 {
253     my @procs = `ps -ef`;
254     die "cygserver not running" unless(grep {/cygserver/} @procs);
255 }
256 my $ccachedir;
257 if ( $ccachedir = $EximBuild::conf{build_env}->{CCACHE_DIR} )
258 {
259
260     # ccache is smart enough to create what you tell it is the cache dir, but
261     # not smart enough to build the whole path. mkpath croaks on error, so
262     # we just let it.
263
264     mkpath $ccachedir;
265     $ccachedir = abs_path($ccachedir);
266 }
267
268 if ($^V lt v5.8.0)
269 {
270     die "no aux_path in config file" unless $aux_path;
271 }
272
273 die "cannot run as root/Administrator" unless ($using_msvc or $> > 0);
274
275 my $devnull = $using_msvc ? "nul" : "/dev/null";
276
277 if (!$from_source)
278 {
279     $scm->check_access($using_msvc);
280 }
281
282 my $st_prefix = "$animal.";
283
284 my $exim = $from_source  || $scm->get_build_path($use_vpath);
285
286 # set environment from config
287 while (my ($envkey,$envval) = each %{$EximBuild::conf{build_env}})
288 {
289     $ENV{$envkey}=$envval;
290 }
291
292 # change to buildroot for this branch or die
293 die "no buildroot" unless $buildroot;
294
295 unless ($buildroot =~ m!^/!
296     or($using_msvc and $buildroot =~ m![a-z]:[/\\]!i ))
297 {
298     die "buildroot $buildroot not absolute";
299 }
300
301 die "$buildroot does not exist or is not a directory" unless -d $buildroot;
302
303 chdir $buildroot || die "chdir to $buildroot: $!";
304
305 mkdir $branch unless -d $branch;
306 chdir $branch || die "chdir to $buildroot/$branch";
307
308 # rename legacy status files/directories
309 foreach my $oldfile (glob("last*"))
310 {
311     move $oldfile, "$st_prefix$oldfile";
312 }
313
314 my $branch_root = getcwd();
315
316 # Normally we would require GNU Make, but allow farm
317 # configuration to override this
318 die "$make is not GNU Make - please fix config file"
319   unless check_make();
320
321 # set up modules
322 foreach my $module (@{$EximBuild::conf{modules}})
323 {
324
325     # fill in the name of the module here, so use double quotes
326     # so everything BUT the module name needs to be escaped
327     my $str = qq!
328          require EximBuild::Modules::$module; 
329          EximBuild::Modules::${module}::setup(
330               \$buildroot,
331               \$branch,
332               \\\%EximBuild::conf,
333               \$exim);
334     !;
335     eval $str;
336
337     # make errors fatal
338     die $@ if $@;
339 }
340
341 # acquire the lock
342
343 my $lockfile;
344 my $have_lock;
345
346 open($lockfile, ">builder.LCK") || die "opening lockfile: $!";
347
348 # only one builder at a time allowed per branch
349 # having another build running is not a failure, and so we do not output
350 # a failure message under this condition.
351 if ($from_source)
352 {
353     die "acquiring lock in $buildroot/$branch/builder.LCK"
354       unless flock($lockfile,LOCK_EX|LOCK_NB);
355 }
356 elsif ( !flock($lockfile,LOCK_EX|LOCK_NB) )
357 {
358     print "Another process holds the lock on "
359       ."$buildroot/$branch/builder.LCK. Exiting."
360       if ($verbose);
361     exit(0);
362 }
363
364 die "$buildroot/$branch has $exim or inst directories!"
365   if ((!$from_source && -d $exim) || -d "inst");
366
367 # we are OK to run if we get here
368 $have_lock = 1;
369
370 # check if file present for forced run
371 my $forcefile = $st_prefix . "force-one-run";
372 if (-e $forcefile)
373 {
374     $forcerun = 1;
375     unlink $forcefile;
376 }
377
378 # try to allow core files to be produced.
379 # another way would be for the calling environment
380 # to call ulimit. We do this in an eval so failure is
381 # not fatal.
382 eval{
383     require BSD::Resource;
384     BSD::Resource->import();
385
386     # explicit sub calls here. using & keeps compiler happy
387     my $coreok = setrlimit(&RLIMIT_CORE,&RLIM_INFINITY,&RLIM_INFINITY);
388     die "setrlimit" unless $coreok;
389 };
390 warn "failed to unlimit core size: $@" if $@ && $verbose > 1;
391
392 # the time we take the snapshot
393 my $now=time;
394 my $installdir = "$buildroot/$branch/inst";
395 my $dbstarted;
396
397 my $extraconf;
398
399 # cleanup handler for all exits
400 END
401 {
402
403     # clean up temp file
404     unlink $ENV{TEMP_CONFIG} if $extraconf;
405
406     # if we have the lock we must already be in the build root, so
407     # removing things there should be safe.
408     # there should only be anything to cleanup if we didn't have
409     # success.
410     if ( $have_lock && -d "$exim")
411     {
412         if ($dbstarted)
413         {
414             chdir $installdir;
415             system(qq{"bin/pg_ctl" -D data stop >$devnull 2>&1});
416             foreach my $loc (@locales)
417             {
418                 next unless -d "data-$loc";
419                 system(qq{"bin/pg_ctl" -D "data-$loc" stop >$devnull 2>&1});
420             }
421             chdir $branch_root;
422         }
423         if ( !$from_source && $keep_errs)
424         {
425             print "moving kept error trees\n" if $verbose;
426             my $timestr = strftime "%Y-%m-%d_%H-%M-%S", localtime($now);
427             unless (move("$exim", "eximkeep.$timestr"))
428             {
429                 print "error renaming '$exim' to 'eximkeep.$timestr': $!";
430             }
431             if (-d "inst")
432             {
433                 unless(move("inst", "instkeep.$timestr"))
434                 {
435                     print "error renaming 'inst' to 'instkeep.$timestr': $!";
436                 }
437             }
438         }
439         else
440         {
441             rmtree("inst") unless $keepall;
442             rmtree("$exim") unless ($from_source || $keepall);
443         }
444
445         # only keep the cache in cases of success
446         rmtree("$ccachedir") if $ccachedir;
447     }
448
449     # get the modules to clean up after themselves
450     process_module_hooks('cleanup');
451
452     if ($have_lock)
453     {
454         if ($use_vpath)
455         {
456
457             # vpath builds leave some stuff lying around in the
458             # source dir, unfortunately. This should clean it up.
459             $scm->cleanup();
460         }
461         close($lockfile);
462         unlink("builder.LCK");
463     }
464 }
465
466 # Prepend the DEFAULT settings (if any) to any settings for the
467 # branch. Since we're mangling this, deep clone $extra_config
468 # so the config object is kept as given. This is done using
469 # Dumper() because the MSys DTK perl doesn't have Storable. This
470 # is less efficient but it hardly matters here for this shallow
471 # structure.
472
473 $extra_config = eval Dumper($extra_config);
474
475 if ($extra_config &&  $extra_config->{DEFAULT})
476 {
477     if (!exists  $extra_config->{$branch})
478     {
479         $extra_config->{$branch} =      $extra_config->{DEFAULT};
480     }
481     else
482     {
483         unshift(@{$extra_config->{$branch}}, @{$extra_config->{DEFAULT}});
484     }
485 }
486
487 if ($extra_config && $extra_config->{$branch})
488 {
489     my $tmpname;
490     ($extraconf,$tmpname) =File::Temp::tempfile(
491         'buildfarm-XXXXXX',
492         DIR => File::Spec->tmpdir(),
493         UNLINK => 1
494     );
495     die 'no $tmpname!' unless $tmpname;
496     $ENV{TEMP_CONFIG} = $tmpname;
497     foreach my $line (@{$extra_config->{$branch}})
498     {
499         print $extraconf "$line\n";
500     }
501     autoflush $extraconf 1;
502 }
503
504 use vars qw($steps_completed);
505 $steps_completed = "";
506
507 my @changed_files;
508 my @changed_since_success;
509 my $last_config;
510 my $last_status;
511 my $last_run_snap;
512 my $last_success_snap;
513 my $current_config;
514 my $current_snap;
515 my @filtered_files;
516 my $savescmlog = "";
517
518 if ($from_source_clean)
519 {
520     print time_str(),"cleaning source in $exim ...\n";
521     clean_from_source();
522 }
523 elsif (!$from_source)
524 {
525
526     # see if we need to run the tests (i.e. if either something has changed or
527     # we have gone over the force_every heartbeat time)
528
529     print time_str(),"checking out source ...\n" if $verbose;
530
531     my $timeout_pid;
532
533     $timeout_pid = spawn(\&scm_timeout,$scm_timeout_secs)
534       if $scm_timeout_secs;
535
536     $savescmlog = $scm->checkout($branch);
537     $steps_completed = "SCM-checkout";
538
539     process_module_hooks('checkout',$savescmlog);
540
541     if ($timeout_pid)
542     {
543
544         # don't kill me, I finished in time
545         if (kill(SIGTERM, $timeout_pid))
546         {
547
548             # reap the zombie
549             waitpid($timeout_pid,0);
550         }
551     }
552
553     print time_str(),"checking if build run needed ...\n" if $verbose;
554
555     # transition to new time processing
556     unlink "last.success";
557
558     # get the timestamp data
559     $last_config = find_last('config') || 0;
560     $last_status = find_last('status') || 0;
561     $last_run_snap = find_last('run.snap');
562     $last_success_snap = find_last('success.snap');
563     $forcerun = 1 unless (defined($last_run_snap));
564
565     # If config file changed, force a rebuild.  This assumes that the config
566     # file is in the CWD, which may not always be true, so handle it by
567     # adding 1 to the value of last_config, which will force the rebuild.
568     ($current_config) = (stat $orig_dir.'/'.$buildconf)[9] || ($last_config+1);
569     if ($current_config > $last_config)
570     {
571       $last_status = 0;
572       set_last('config',$current_config) unless $nostatus;
573     }
574
575     # updated by find_changed to last mtime of any file in the repo
576     $current_snap=0;
577
578     # see if we need to force a build
579     $last_status = 0
580       if ( $last_status
581         && $force_every
582         &&$last_status+($force_every*3600) < $now);
583     $last_status = 0 if $forcerun;
584
585     # see what's changed since the last time we did work
586     $scm->find_changed(\$current_snap,$last_run_snap, $last_success_snap,
587         \@changed_files,\@changed_since_success);
588
589     #ignore changes to files specified by the trigger exclude filter, if any
590     if (defined($trigger_exclude))
591     {
592         @filtered_files = grep { !m[$trigger_exclude] } @changed_files;
593     }
594     else
595     {
596         @filtered_files = @changed_files;
597     }
598
599     #ignore changes to files NOT specified by the trigger include filter, if any
600     if (defined($trigger_include))
601     {
602         @filtered_files = grep { m[$trigger_include] } @filtered_files;
603     }
604
605     my $modules_need_run;
606
607     process_module_hooks('need-run',\$modules_need_run);
608
609     # if no build required do nothing
610     if ($last_status && !@filtered_files && !$modules_need_run)
611     {
612         print time_str(),
613           "No build required: last status = ",scalar(gmtime($last_status)),
614           " GMT, current snapshot = ",scalar(gmtime($current_snap))," GMT,",
615           " changed files = ",scalar(@filtered_files),"\n"
616           if $verbose;
617         rmtree("$exim");
618         exit 0;
619     }
620
621     # get version info on both changed files sets
622     # XXX modules support?
623
624     $scm->get_versions(\@changed_files);
625     $scm->get_versions(\@changed_since_success);
626
627 } # end of unless ($from_source)
628
629 cleanlogs();
630
631 writelog('SCM-checkout',$savescmlog) unless $from_source;
632 $scm->log_id() unless $from_source;
633
634 # copy/create according to vpath/scm settings
635
636 if ($use_vpath)
637 {
638     print time_str(),"creating vpath build dir $exim ...\n" if $verbose;
639     mkdir $exim || die "making $exim: $!";
640 }
641 elsif (!$from_source && $scm->copy_source_required())
642 {
643     print time_str(),"copying source to $exim ...\n" if $verbose;
644
645     $scm->copy_source($using_msvc);
646 }
647
648 process_module_hooks('setup-target');
649
650 # start working
651
652 set_last('status',$now) unless $nostatus;
653 set_last('run.snap',$current_snap) unless $nostatus;
654
655 my $started_times = 0;
656 print time_str(),"running configure ...\n" if $verbose;
657
658 # each of these routines will call send_result, which calls exit,
659 # on any error, so each step depends on success in the previous
660 # steps.
661 configure();
662
663 make();
664
665 display_features();
666
667 make_test() if (check_optional_step('test'));
668
669 make_doc() if (check_optional_step('make-doc'));
670
671 ##check_port_is_ok($buildport,'Post');
672
673 # if we get here everything went fine ...
674
675 my $saved_config = get_config_summary();
676
677 rmtree("inst"); # only keep failures
678 rmtree("$exim") unless ($from_source || $keepall);
679
680 print(time_str(),"OK\n") if $verbose;
681
682 send_result("OK");
683
684 exit;
685
686 ############## end of main program ###########################
687
688 sub print_help
689 {
690     print qq!
691 usage: $0 [options] [branch]
692
693  where options are one or more of:
694
695   --nosend                  = don't send results
696   --nostatus                = don't set status files
697   --force                   = force a build run (ignore status files)
698   --from-source=/path       = use source in path, not from SCM
699   or
700   --from-source-clean=/path = same as --from-source, run make distclean first
701   --config=/path/to/file    = alternative location for config file
702   --keepall                 = keep directories if an error occurs
703   --verbose[=n]             = verbosity (default 1) 2 or more = huge output.
704   --quiet                   = suppress normal error message 
705   --test                    = short for --nosend --nostatus --verbose --force
706   --skip-steps=list         = skip certain steps
707   --only-steps=list         = only do certain steps, not allowed with skip-steps
708                               lists can be comma, colon, or space separated
709
710 Default branch is HEAD. Usually only the --config option should be necessary.
711
712 !;
713     exit(0);
714 }
715
716 sub time_str
717 {
718     my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
719     return sprintf("[%.2d:%.2d:%.2d] ",$hour, $min, $sec);
720 }
721
722 sub step_wanted
723 {
724     my $step = shift;
725     return $only_steps{$step} if $only_steps;
726     return !$skip_steps{$step} if $skip_steps;
727     return 1; # default is everything is wanted
728 }
729
730 sub register_module_hooks
731 {
732     my $who = shift;
733     my $what = shift;
734     while (my ($hook,$func) = each %$what)
735     {
736         $module_hooks{$hook} ||= [];
737         push(@{$module_hooks{$hook}},[$func,$who]);
738     }
739 }
740
741 sub process_module_hooks
742 {
743     my $hook = shift;
744
745     # pass remaining args (if any) to module func
746     foreach my $module (@{$module_hooks{$hook}})
747     {
748         my ($func,$module_instance) = @$module;
749         &$func($module_instance, @_);
750     }
751 }
752
753 sub check_optional_step
754 {
755     my $step = shift;
756     my $oconf;
757     my $shandle;
758
759     return undef unless ref($oconf = $optional_steps->{$step});
760     if ($oconf->{branches})
761     {
762         return undef unless grep {$_ eq $branch} @{$oconf->{branches}};
763     }
764
765     my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =localtime(time);
766     return undef if (exists $oconf->{min_hour} &&  $hour < $oconf->{min_hour});
767     return undef if (exists $oconf->{max_hour} &&  $hour > $oconf->{max_hour});
768     return undef if (exists $oconf->{dow}
769         &&grep {$_ eq $wday} @{$oconf->{dow}});
770
771     my $last_step = $last_status = find_last("$step") || 0;
772     ## If made it *to* these optional steps, we just run them and reset last time
773     #return undef unless ($forcerun ||
774     #                     time >$last_step + (3600 * $oconf->{min_hours_since}));
775     set_last("$step") unless $nostatus;
776
777     return 1;
778 }
779
780 sub clean_from_source
781 {
782     if (-e "$exim/GNUmakefile")
783     {
784
785         # fixme for MSVC
786         my @makeout = `cd $exim && $make distclean 2>&1`;
787         my $status = $? >>8;
788         writelog('distclean',\@makeout);
789         print "======== distclean log ===========\n",@makeout if ($verbose > 1);
790         send_result('distclean',$status,\@makeout) if $status;
791     }
792 }
793
794 sub interrupt_exit
795 {
796     my $signame = shift;
797     print "Exiting on signal $signame\n";
798     exit(1);
799 }
800
801 sub cleanlogs
802 {
803     my $lrname = $st_prefix . $logdirname;
804     rmtree("$lrname");
805     mkdir "$lrname" || die "can't make $lrname dir: $!";
806 }
807
808 sub writelog
809 {
810     my $stage = shift;
811     my $loglines = shift;
812     my $handle;
813     my $lrname = $st_prefix . $logdirname;
814     open($handle,">$lrname/$stage.log") || die $!;
815     print $handle @$loglines;
816     close($handle);
817 }
818
819 sub display_features
820 {
821     return unless step_wanted('features');
822     my @out = `cd $exim
823                src/build-*/exim -C test/confs/0000 -bV `;
824     my $status = $? >>8;
825     writelog('features',\@out);
826     print "======== features log ===========\n",@out if ($verbose > 1);
827     send_result('Features',$status,\@out) if $status;
828     $steps_completed .= " Features";
829 }
830     
831 sub check_make
832 {
833     # Allow farm member to configure non-GNU make
834     my $non_gnu_make = $EximBuild::conf{non_gnu_make};
835     if (!defined $non_gnu_make ||
836         (defined $non_gnu_make && $non_gnu_make == 1)) {
837       return 'OK';
838     }
839     my @out = `$make -v 2>&1`;
840     return undef unless ($? == 0 && grep {/GNU Make/} @out);
841     return 'OK';
842 }
843
844 sub make
845 {
846     return unless step_wanted('make');
847     print time_str(),"running make ...\n" if $verbose;
848     my $make_args = join(' ',$EximBuild::conf{make_args});
849     my (@makeout);
850     my $make_cmd = $make;
851     $make_cmd = "$make -j $make_jobs"
852       if ($make_jobs > 1 && ($branch eq 'HEAD' || $branch ge 'REL9_1'));
853     @makeout = `cd $exim/src && $make_cmd $make_args 2>&1`;
854     my $status = $? >>8;
855     writelog('make',\@makeout);
856     print "======== make log ===========\n",@makeout if ($verbose > 1);
857     send_result('Make',$status,\@makeout) if $status;
858     $steps_completed .= " Make";
859 }
860
861 sub make_doc
862 {
863     return unless step_wanted('make-doc');
864     print time_str(),"running make doc ...\n" if $verbose;
865
866     my (@makeout);
867     @makeout = `cd $exim/doc/doc-docbook/ && \
868                 EXIM_VER="4.82" $make everything 2>&1`;
869     my $status = $? >>8;
870     writelog('make-doc',\@makeout);
871     print "======== make doc log ===========\n",@makeout if ($verbose > 1);
872     send_result('Doc',$status,\@makeout) if $status;
873     $steps_completed .= " Doc";
874 }
875
876 sub get_stack_trace
877 {
878     my $bindir = shift;
879     my $pgdata = shift;
880
881     # no core = no result
882     my @cores = glob("$pgdata/$core_file_glob");
883     return () unless @cores;
884
885     # no gdb = no result
886     system "gdb --version > $devnull 2>&1";
887     my $status = $? >>8;
888     return () if $status;
889
890     my $cmdfile = "./gdbcmd";
891     my $handle;
892     open($handle, ">$cmdfile");
893     print $handle "bt\n";
894     close($handle);
895
896     my @trace;
897
898     foreach my $core (@cores)
899     {
900         my @onetrace = `gdb -x $cmdfile --batch $bindir/exim $core 2>&1`;
901         push(@trace,
902             "\n\n================== stack trace: $core ==================\n",
903             @onetrace);
904     }
905
906     unlink $cmdfile;
907
908     return @trace;
909 }
910
911 sub make_install_check
912 {
913     my $locale = shift;
914     return unless step_wanted('install-check');
915     print time_str(),"running make installcheck ($locale)...\n" if $verbose;
916
917     my @checklog;
918     unless ($using_msvc)
919     {
920         @checklog = `cd $exim/src/test/regress && $make installcheck 2>&1`;
921     }
922     else
923     {
924         chdir "$exim/src/tools/msvc";
925         @checklog = `perl vcregress.pl installcheck 2>&1`;
926         chdir $branch_root;
927     }
928     my $status = $? >>8;
929     my @logfiles =
930       ("$exim/src/test/regress/regression.diffs","$installdir/logfile");
931     foreach my $logfile(@logfiles)
932     {
933         next unless (-e $logfile );
934         push(@checklog,"\n\n================== $logfile ==================\n");
935         my $handle;
936         open($handle,$logfile);
937         while(<$handle>)
938         {
939             push(@checklog,$_);
940         }
941         close($handle);
942     }
943     if ($status)
944     {
945         my @trace =
946           get_stack_trace("$installdir/bin","$installdir/data-$locale");
947         push(@checklog,@trace);
948     }
949     writelog("install-check-$locale",\@checklog);
950     print "======== make installcheck log ===========\n",@checklog
951       if ($verbose > 1);
952     send_result("InstallCheck-$locale",$status,\@checklog) if $status;
953     $steps_completed .= " InstallCheck-$locale";
954 }
955
956 sub make_isolation_check
957 {
958     my $locale = shift;
959     return unless step_wanted('isolation-check');
960     my @makeout;
961     unless ($using_msvc)
962     {
963         my $cmd =
964           "cd $exim/src/test/isolation && $make NO_LOCALE=1 installcheck";
965         @makeout = `$cmd 2>&1`;
966     }
967     else
968     {
969         chdir "$exim/src/tools/msvc";
970         @makeout = `perl vcregress.pl isolationcheck 2>&1`;
971         chdir $branch_root;
972     }
973
974     my $status = $? >>8;
975
976     # get the log files and the regression diffs
977     my @logs = glob("$exim/src/test/isolation/log/*.log");
978     push(@logs,"$installdir/logfile");
979     unshift(@logs,"$exim/src/test/isolation/regression.diffs")
980       if (-e "$exim/src/test/isolation/regression.diffs");
981     foreach my $logfile (@logs)
982     {
983         push(@makeout,"\n\n================== $logfile ===================\n");
984         my $handle;
985         open($handle,$logfile);
986         while(<$handle>)
987         {
988             push(@makeout,$_);
989         }
990         close($handle);
991     }
992     if ($status)
993     {
994         my @trace =
995           get_stack_trace("$installdir/bin","$installdir/data-$locale");
996         push(@makeout,@trace);
997     }
998     writelog('isolation-check',\@makeout);
999     print "======== make isolation check logs ===========\n",@makeout
1000       if ($verbose > 1);
1001
1002     send_result('IsolationCheck',$status,\@makeout) if $status;
1003     $steps_completed .= " IsolationCheck";
1004 }
1005
1006 sub make_test
1007 {
1008     return unless step_wanted('test');
1009     print time_str(),"running make test ...\n" if $verbose;
1010     my $tests_range = $EximBuild::conf{range_num_tests} || "1 4";
1011     my @makeout;
1012     @makeout =`(cd $exim/test
1013                 autoconf && ./configure && $make )2>&1 `;
1014     my $status = $? >>8;
1015     unless($status)
1016     {
1017       my @tmp = `(WORKDIR=\$PWD
1018                   cd $exim/test
1019                   ./runtest \$WORKDIR/$exim/src/build-*/exim -CONTINUE $tests_range )2>&1`;
1020       $status = $? >>8;
1021       push @makeout, @tmp;
1022       # Prepend the failed summary log outputs for ease of reading
1023       my $fail_summary = "$exim/test/failed-summary.log";
1024       if (-f $fail_summary)
1025       {
1026         @tmp = `cat $fail_summary`;
1027         push @tmp, "\n";
1028         unshift @makeout, @tmp;
1029         unshift @makeout, "Summary of failed tests:\n";
1030       }
1031     }
1032     writelog('test',\@makeout);
1033     print "======== make test logs ===========\n",@makeout
1034       if ($verbose > 1);
1035
1036     send_result('Test',$status,\@makeout) if $status;
1037     $steps_completed .= " Test";
1038 }
1039
1040 sub make_ecpg_check
1041 {
1042     return unless step_wanted('ecpg-check');
1043     my @makeout;
1044     my $ecpg_dir = "$exim/src/interfaces/ecpg";
1045     if ($using_msvc)
1046     {
1047         chdir "$exim/src/tools/msvc";
1048         @makeout = `perl vcregress.pl ecpgcheck 2>&1`;
1049         chdir $branch_root;
1050     }
1051     else
1052     {
1053         @makeout = `cd  $ecpg_dir && $make NO_LOCALE=1 check 2>&1`;
1054     }
1055     my $status = $? >>8;
1056
1057     # get the log files and the regression diffs
1058     my @logs = glob("$ecpg_dir/test/log/*.log");
1059     unshift(@logs,"$ecpg_dir/test/regression.diffs")
1060       if (-e "$ecpg_dir/test/regression.diffs");
1061     foreach my $logfile (@logs)
1062     {
1063         push(@makeout,"\n\n================== $logfile ===================\n");
1064         my $handle;
1065         open($handle,$logfile);
1066         while(<$handle>)
1067         {
1068             push(@makeout,$_);
1069         }
1070         close($handle);
1071     }
1072     if ($status)
1073     {
1074         my $base = "$ecpg_dir/test/regress/tmp_check";
1075         my @trace =
1076           get_stack_trace("$base/install$installdir/bin",       "$base/data");
1077         push(@makeout,@trace);
1078     }
1079     writelog('ecpg-check',\@makeout);
1080     print "======== make ecpg check logs ===========\n",@makeout
1081       if ($verbose > 1);
1082
1083     send_result('ECPG-Check',$status,\@makeout) if $status;
1084     $steps_completed .= " ECPG-Check";
1085 }
1086
1087 sub configure
1088 {
1089     return unless step_wanted('configure');
1090     print time_str(),"creating configuration ...\n" if $verbose;
1091
1092     my $env = $EximBuild::conf{makefile_set};
1093     my $add = $EximBuild::conf{makefile_add};
1094     my $features = $EximBuild::conf{makefile_regex};
1095
1096     my $envstr = "";
1097     while (my ($key,$val) = each %$env)
1098     {
1099         $envstr .= "$key='$val'\n";
1100     }
1101     while (my ($key,$val) = each %$add)
1102     {
1103         $envstr .= "$key+='$val'\n";
1104     }
1105
1106     my $conf_path = "src/src/EDITME";
1107     my $local_conf = "src/Local/Makefile";
1108     my @confout = `cd $exim; mkdir -p src/Local 2>&1`;
1109     my @tmp = `cd $exim && cp $conf_path $local_conf 2>&1`;
1110     my $status = $? >> 8;
1111     push @confout, @tmp;
1112     if ($status == 0)
1113     {
1114         # First, let's display some directory permissions in case
1115         # permissions are causing problems.
1116         my @dir = split('/',`pwd`);
1117         chomp(@dir);
1118         my $count = scalar @dir;
1119         my $loop = 1;
1120         my $dirs = '';
1121         while ($loop < $count)
1122         {
1123           my $dir = "";
1124           foreach my $i (0 .. $loop)
1125           {
1126             $dir .= $dir[$i].'/';
1127           }
1128           $dirs .= " $dir";
1129           $loop++;
1130         }
1131         @tmp = `echo "Verify Directory Permissions"
1132                 ls -ld $dirs`;
1133         push @confout, @tmp;
1134         # Build the config file from the EDITME template
1135         @tmp = `cd $exim && echo '$envstr' >> $local_conf`;
1136         push @confout, @tmp;
1137         my $exim_user = $EximBuild::conf{master_exim_user} || 'exim';
1138         @tmp = `echo "Hardcoded Exim user info:"; id $exim_user
1139           cd $exim && perl -pi -e 's/^EXIM_USER=.*/EXIM_USER=$exim_user/' $local_conf`;
1140         push @confout, @tmp;
1141         my $me = `whoami`; chomp $me;
1142         @tmp = `echo "Build Farm user info:"; id $me
1143           cd $exim && perl -pi -e 's/^# CONFIGURE_OWNER=\$/CONFIGURE_OWNER=$me/' $local_conf`;
1144         push @confout, @tmp;
1145         @tmp = `cd $exim && perl -pi -e 's/^# TRUSTED_CONFIG_LIST=/TRUSTED_CONFIG_LIST=/' $local_conf`;
1146         push @confout, @tmp;
1147         @tmp = `cd $exim && perl -pi -e 's/^# WHITELIST_D_MACROS=.*/WHITELIST_D_MACROS=DIR:EXIM_PATH:AA:ACL:ACLRCPT:ACL_MAIL:ACL_PREDATA:ACL_RCPT:AFFIX:ALLOW:ARG1:ARG2:AUTHF:AUTHS:AUTH_ID_DOMAIN:BAD:BANNER:BB:BR:BRB:CERT:COM:COMMAND_USER:CONNECTCOND:CONTROL:CREQCIP:CREQMAC:CRL:CSS:D6:DATA:DCF:DDF:DEFAULTDWC:DELAY:DETAILS:DRATELIMIT:DYNAMIC_OPTION:ELI:ERROR_DETAILS:ERT:FAKE:FALLBACK:FILTER:FILTER_PREPEND_HOME:FORBID:FORBID_SMTP_CODE:FUSER:HAI:HAP:HARDLIMIT:HEADER_LINE_MAXSIZE:HEADER_MAXSIZE:HELO_MSG:HL:HOSTS:HOSTS_AVOID_TLS:HOSTS_MAX_TRY:HVH:IFACE:IGNORE_QUOTA:INC:INSERT:IP1:IP2:LAST:LDAPSERVERS:LENCHECK:LIMIT:LIST:LOG_SELECTOR:LS:MAXNM:MESSAGE_LOGS:MSIZE:NOTDAEMON:ONCE:ONLY:OPT:OPTION:ORDER:PAH:PEX:PORT:PTBC:QDG:QOLL:QUOTA:QUOTA_FILECOUNT:QWM:RCPT_MSG:REMEMBER:REQUIRE:RETRY:RETRY1:RETRY2:RETURN:RETURN_ERROR_DETAILS:REWRITE:ROUTE_DATA:RRATELIMIT:RT:S:SELECTOR:SELF:SERVER:SERVERS:SREQCIP:SREQMAC:SRV:STD:STRICT:SUB:SUBMISSION_OPTIONS:TIMEOUTDEFER:TIMES:TRUSTED:TRYCLEAR:UL:USE_SENDER:UTF8:VALUE:WMF:X:Y/' $local_conf`;
1148         push @confout, @tmp;
1149         @tmp = `cd $exim && perl -pi -e 's/^EXIM_MONITOR=(.*)/# EXIM_MONITOR=\$1/' $local_conf`;
1150         push @confout, @tmp;
1151         for my $regex ( @$features )
1152         {
1153             @tmp = `cd $exim
1154                     perl -pi -e '$regex' $local_conf 2>&1
1155                     echo "Used regex: $regex" `;
1156             push @confout, @tmp;
1157         }
1158         # Add the final build file to the display output
1159         @tmp = `cd $exim
1160                 echo
1161                 echo "Contents of Local/Makefile:"
1162                 egrep '^[^#]' $local_conf `;
1163         push @confout, @tmp;
1164         # Build the config_opts array to send to the server
1165         chomp @tmp;
1166         my @config_opts = grep s/(?:LOOKUP_|EXPERIMENTAL_|USE_)(\S+)=.*/$1/,
1167                           @tmp;
1168         push @config_opts, grep s/^(?:EXIM_)(PERL|PYTHON)=.*/$1/,
1169                            @tmp;
1170         # OpenSSL doesn't have a specific USE flag
1171         push @config_opts, grep s/^(TLS_LIBS.*-l(ssl|crypto)).*/OPENSSL/,
1172                            @tmp;
1173         $EximBuild::conf{config_opts} = \@config_opts;
1174         
1175         # Does not matter what the Exim version is, as long as it is valid.
1176         my $exim_ver = $EximBuild::conf{exim_test_version} || '4.82';
1177         `cd $exim
1178          echo 'EXIM_RELEASE_VERSION="$exim_ver"' > src/src/version.sh
1179          echo 'EXIM_VARIANT_VERSION=""' >> src/src/version.sh
1180          echo 'EXIM_COMPILE_NUMBER="0"' >> src/src/version.sh`;
1181     }
1182    
1183     print "======== configure output ===========\n",@confout
1184       if ($verbose > 1);
1185
1186     writelog('configure',\@confout);
1187
1188     if ($status)
1189     {
1190         send_result('Configure',$status,\@confout);
1191     }
1192
1193     $steps_completed .= " Configure";
1194 }
1195
1196 sub find_last
1197 {
1198     my $which = shift;
1199     my $stname = $st_prefix . "last.$which";
1200     my $handle;
1201     open($handle,$stname) or return undef;
1202     my $time = <$handle>;
1203     close($handle);
1204     chomp $time;
1205     return $time + 0;
1206 }
1207
1208 sub set_last
1209 {
1210     my $which = shift;
1211     my $stname = $st_prefix . "last.$which";
1212     my $st_now = shift || time;
1213     my $handle;
1214     open($handle,">$stname") or die "opening $stname: $!";
1215     print $handle "$st_now\n";
1216     close($handle);
1217 }
1218
1219 sub send_result
1220 {
1221
1222     # clean up temp file
1223     $extraconf = undef;
1224
1225     my $stage = shift;
1226
1227     my $ts = $now || time;
1228     my $status=shift || 0;
1229     my $log = shift || [];
1230     print "======== log passed to send_result ===========\n",@$log
1231       if ($verbose > 1);
1232
1233     unshift(@$log,
1234         "Last file mtime in snapshot: ",
1235         scalar(gmtime($current_snap)),
1236         " GMT\n","===================================================\n")
1237       unless ($from_source || !$current_snap);
1238
1239     my $log_data = join("",@$log);
1240     my $confsum = "";
1241     my $changed_this_run = "";
1242     my $changed_since_success = "";
1243     $changed_this_run = join("!",@changed_files)
1244       if @changed_files;
1245     $changed_since_success = join("!",@changed_since_success)
1246       if ($stage ne 'OK' && @changed_since_success);
1247
1248     if ($stage eq 'OK')
1249     {
1250         $confsum= $saved_config;
1251     }
1252     elsif ($stage !~ /CVS|Git|SCM/ )
1253     {
1254         $confsum = get_config_summary();
1255     }
1256     else
1257     {
1258         $confsum = get_script_config_dump();
1259     }
1260
1261     my $savedata = Data::Dumper->Dump(
1262         [
1263             $changed_this_run, $changed_since_success, $branch, $status,$stage,
1264             $animal, $ts,$log_data, $confsum, $target, $verbose, $secret
1265         ],
1266         [
1267             qw(changed_this_run changed_since_success branch status stage
1268               animal ts log_data confsum target verbose secret)
1269         ]
1270     );
1271
1272     my $lrname = $st_prefix . $logdirname;
1273
1274     # might happen if there is a CVS failure and have never got further
1275     mkdir $lrname unless -d $lrname;
1276
1277     my $txfname = "$lrname/web-txn.data";
1278     my $txdhandle;
1279     open($txdhandle,">$txfname");
1280     print $txdhandle $savedata;
1281     close($txdhandle);
1282
1283     if ($nosend || $stage eq 'CVS' || $stage eq 'CVS-status' )
1284     {
1285         print "Branch: $branch\n";
1286         if ($stage eq 'OK')
1287         {
1288             print "All stages succeeded\n";
1289             set_last('success.snap',$current_snap) unless $nostatus;
1290             exit(0);
1291         }
1292         else
1293         {
1294             print "Stage $stage failed with status $status\n";
1295             exit(1);
1296         }
1297     }
1298
1299     if ($stage !~ /CVS|Git|SCM|Pre-run-port-check/ )
1300     {
1301
1302         my @logfiles = glob("$lrname/*.log");
1303         my %mtimes = map { $_ => (stat $_)[9] } @logfiles;
1304         @logfiles =
1305           map { basename $_ }( sort { $mtimes{$a} <=> $mtimes{$b} } @logfiles );
1306         my $logfiles = join(' ',@logfiles);
1307         $tar_log_cmd =~ s/\*\.log/$logfiles/;
1308         chdir($lrname);
1309         system("$tar_log_cmd 2>&1 ");
1310         chdir($branch_root);
1311
1312     }
1313     else
1314     {
1315
1316         # these would be from an earlier run, since we
1317         # do cleanlogs() after the cvs stage
1318         # so don't send them.
1319         unlink "$lrname/runlogs.tgz";
1320     }
1321
1322     my $txstatus;
1323
1324     # this should now only apply to older Msys installs. All others should
1325     # be running with perl >= 5.8 since that's required to build exim
1326     # anyway
1327     if (!$^V or $^V lt v5.8.0)
1328     {
1329
1330         unless (-x "$aux_path/run_web_txn.pl")
1331         {
1332             print "Could not locate $aux_path/run_web_txn.pl\n";
1333             exit(1);
1334         }
1335
1336         system("$aux_path/run_web_txn.pl $lrname");
1337         $txstatus = $? >> 8;
1338     }
1339     else
1340     {
1341         $txstatus = EximBuild::WebTxn::run_web_txn($lrname) ? 0 : 1;
1342
1343     }
1344
1345     if ($txstatus)
1346     {
1347         print "Web txn failed with status: $txstatus\n";
1348
1349         # if the web txn fails, restore the timestamps
1350         # so we try again the next time.
1351         set_last('status',$last_status) unless $nostatus;
1352         set_last('run.snap',$last_run_snap) unless $nostatus;
1353         exit($txstatus);
1354     }
1355
1356     unless ($stage eq 'OK' || $quiet)
1357     {
1358         print "BuildFarm member $animal failed on $branch stage $stage\n";
1359     }
1360
1361     #   print "Success!\n",$response->content
1362     #           if $print_success;
1363
1364     set_last('success.snap',$current_snap) if ($stage eq 'OK' && !$nostatus);
1365
1366     exit 0;
1367 }
1368
1369 sub get_config_summary
1370 {
1371     my $handle;
1372     my $config = "";
1373     # unless ($using_msvc)
1374     # {
1375     #     open($handle,"$exim/config.log") || return undef;
1376     #     my $start = undef;
1377     #     while (<$handle>)
1378     #     {
1379     #         if (!$start && /created by PostgreSQL configure/)
1380     #         {
1381     #             $start=1;
1382     #             s/It was/This file was/;
1383     #         }
1384     #         next unless $start;
1385     #         last if /Core tests/;
1386     #         next if /^\#/;
1387     #         next if /= <?unknown>?/;
1388
1389     #         # split up long configure line
1390     #         if (m!\$.*configure.*--with! && length > 70)
1391     #         {
1392     #             my $pos = index($_," ",70);
1393     #             substr($_,$pos+1,0,"\\\n        ") if ($pos > 0);
1394     #             $pos = index($_," ",140);
1395     #             substr($_,$pos+1,0,"\\\n        ") if ($pos > 0);
1396     #             $pos = index($_," ",210);
1397     #             substr($_,$pos+1,0,"\\\n        ") if ($pos > 0);
1398     #         }
1399     #         $config .= $_;
1400     #     }
1401     #     close($handle);
1402     #     $config .=
1403     #       "\n========================================================\n";
1404     # }
1405     $config .= get_script_config_dump();
1406     return $config;
1407 }
1408
1409 sub get_script_config_dump
1410 {
1411     my $conf = {
1412         %EximBuild::conf,  # shallow copy
1413         script_version => $VERSION,
1414         invocation_args => \@invocation_args,
1415         steps_completed => $steps_completed,
1416         orig_env => $orig_env,
1417     };
1418     delete $conf->{secret};
1419     $Data::Dumper::Sortkeys = 1;
1420     return  Data::Dumper->Dump([$conf],['Script_Config']);
1421 }
1422
1423 sub scm_timeout
1424 {
1425     my $wait_time = shift;
1426     my $who_to_kill = getpgrp(0);
1427     my $sig = SIGTERM;
1428     $sig = -$sig;
1429     print "waiting $wait_time secs to time out process $who_to_kill\n"
1430       if $verbose;
1431     foreach my $sig (qw(INT TERM HUP QUIT))
1432     {
1433         $SIG{$sig}='DEFAULT';
1434     }
1435     sleep($wait_time);
1436     $SIG{TERM} = 'IGNORE'; # so we don't kill ourself, we're exiting anyway
1437     # kill the whole process group
1438     unless (kill $sig,$who_to_kill)
1439     {
1440         print "scm timeout kill failed\n";
1441     }
1442 }
1443
1444 sub spawn
1445 {
1446     my $coderef = shift;
1447     my $pid = fork;
1448     if (defined($pid) && $pid == 0)
1449     {
1450         exit &$coderef(@_);
1451     }
1452     return $pid;
1453 }
1454