Always run optional steps if configured to run.
[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
566     ($current_config) = (stat $orig_dir.'/'.$buildconf)[9];
567     if ($current_config > $last_config)
568     {
569       $last_status = 0;
570       set_last('config',$current_config) unless $nostatus;
571     }
572
573     # updated by find_changed to last mtime of any file in the repo
574     $current_snap=0;
575
576     # see if we need to force a build
577     $last_status = 0
578       if ( $last_status
579         && $force_every
580         &&$last_status+($force_every*3600) < $now);
581     $last_status = 0 if $forcerun;
582
583     # see what's changed since the last time we did work
584     $scm->find_changed(\$current_snap,$last_run_snap, $last_success_snap,
585         \@changed_files,\@changed_since_success);
586
587     #ignore changes to files specified by the trigger exclude filter, if any
588     if (defined($trigger_exclude))
589     {
590         @filtered_files = grep { !m[$trigger_exclude] } @changed_files;
591     }
592     else
593     {
594         @filtered_files = @changed_files;
595     }
596
597     #ignore changes to files NOT specified by the trigger include filter, if any
598     if (defined($trigger_include))
599     {
600         @filtered_files = grep { m[$trigger_include] } @filtered_files;
601     }
602
603     my $modules_need_run;
604
605     process_module_hooks('need-run',\$modules_need_run);
606
607     # if no build required do nothing
608     if ($last_status && !@filtered_files && !$modules_need_run)
609     {
610         print time_str(),
611           "No build required: last status = ",scalar(gmtime($last_status)),
612           " GMT, current snapshot = ",scalar(gmtime($current_snap))," GMT,",
613           " changed files = ",scalar(@filtered_files),"\n"
614           if $verbose;
615         rmtree("$exim");
616         exit 0;
617     }
618
619     # get version info on both changed files sets
620     # XXX modules support?
621
622     $scm->get_versions(\@changed_files);
623     $scm->get_versions(\@changed_since_success);
624
625 } # end of unless ($from_source)
626
627 cleanlogs();
628
629 writelog('SCM-checkout',$savescmlog) unless $from_source;
630 $scm->log_id() unless $from_source;
631
632 # copy/create according to vpath/scm settings
633
634 if ($use_vpath)
635 {
636     print time_str(),"creating vpath build dir $exim ...\n" if $verbose;
637     mkdir $exim || die "making $exim: $!";
638 }
639 elsif (!$from_source && $scm->copy_source_required())
640 {
641     print time_str(),"copying source to $exim ...\n" if $verbose;
642
643     $scm->copy_source($using_msvc);
644 }
645
646 process_module_hooks('setup-target');
647
648 # start working
649
650 set_last('status',$now) unless $nostatus;
651 set_last('run.snap',$current_snap) unless $nostatus;
652
653 my $started_times = 0;
654 print time_str(),"running configure ...\n" if $verbose;
655
656 # each of these routines will call send_result, which calls exit,
657 # on any error, so each step depends on success in the previous
658 # steps.
659 configure();
660
661 make();
662
663 display_features();
664
665 make_test() if (check_optional_step('test'));
666
667 make_doc() if (check_optional_step('make-doc'));
668
669 ##check_port_is_ok($buildport,'Post');
670
671 # if we get here everything went fine ...
672
673 my $saved_config = get_config_summary();
674
675 rmtree("inst"); # only keep failures
676 rmtree("$exim") unless ($from_source || $keepall);
677
678 print(time_str(),"OK\n") if $verbose;
679
680 send_result("OK");
681
682 exit;
683
684 ############## end of main program ###########################
685
686 sub print_help
687 {
688     print qq!
689 usage: $0 [options] [branch]
690
691  where options are one or more of:
692
693   --nosend                  = don't send results
694   --nostatus                = don't set status files
695   --force                   = force a build run (ignore status files)
696   --from-source=/path       = use source in path, not from SCM
697   or
698   --from-source-clean=/path = same as --from-source, run make distclean first
699   --config=/path/to/file    = alternative location for config file
700   --keepall                 = keep directories if an error occurs
701   --verbose[=n]             = verbosity (default 1) 2 or more = huge output.
702   --quiet                   = suppress normal error message 
703   --test                    = short for --nosend --nostatus --verbose --force
704   --skip-steps=list         = skip certain steps
705   --only-steps=list         = only do certain steps, not allowed with skip-steps
706                               lists can be comma, colon, or space separated
707
708 Default branch is HEAD. Usually only the --config option should be necessary.
709
710 !;
711     exit(0);
712 }
713
714 sub time_str
715 {
716     my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
717     return sprintf("[%.2d:%.2d:%.2d] ",$hour, $min, $sec);
718 }
719
720 sub step_wanted
721 {
722     my $step = shift;
723     return $only_steps{$step} if $only_steps;
724     return !$skip_steps{$step} if $skip_steps;
725     return 1; # default is everything is wanted
726 }
727
728 sub register_module_hooks
729 {
730     my $who = shift;
731     my $what = shift;
732     while (my ($hook,$func) = each %$what)
733     {
734         $module_hooks{$hook} ||= [];
735         push(@{$module_hooks{$hook}},[$func,$who]);
736     }
737 }
738
739 sub process_module_hooks
740 {
741     my $hook = shift;
742
743     # pass remaining args (if any) to module func
744     foreach my $module (@{$module_hooks{$hook}})
745     {
746         my ($func,$module_instance) = @$module;
747         &$func($module_instance, @_);
748     }
749 }
750
751 sub check_optional_step
752 {
753     my $step = shift;
754     my $oconf;
755     my $shandle;
756
757     return undef unless ref($oconf = $optional_steps->{$step});
758     if ($oconf->{branches})
759     {
760         return undef unless grep {$_ eq $branch} @{$oconf->{branches}};
761     }
762
763     my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =localtime(time);
764     return undef if (exists $oconf->{min_hour} &&  $hour < $oconf->{min_hour});
765     return undef if (exists $oconf->{max_hour} &&  $hour > $oconf->{max_hour});
766     return undef if (exists $oconf->{dow}
767         &&grep {$_ eq $wday} @{$oconf->{dow}});
768
769     my $last_step = $last_status = find_last("$step") || 0;
770     ## If made it *to* these optional steps, we just run them and reset last time
771     #return undef unless ($forcerun ||
772     #                     time >$last_step + (3600 * $oconf->{min_hours_since}));
773     set_last("$step") unless $nostatus;
774
775     return 1;
776 }
777
778 sub clean_from_source
779 {
780     if (-e "$exim/GNUmakefile")
781     {
782
783         # fixme for MSVC
784         my @makeout = `cd $exim && $make distclean 2>&1`;
785         my $status = $? >>8;
786         writelog('distclean',\@makeout);
787         print "======== distclean log ===========\n",@makeout if ($verbose > 1);
788         send_result('distclean',$status,\@makeout) if $status;
789     }
790 }
791
792 sub interrupt_exit
793 {
794     my $signame = shift;
795     print "Exiting on signal $signame\n";
796     exit(1);
797 }
798
799 sub cleanlogs
800 {
801     my $lrname = $st_prefix . $logdirname;
802     rmtree("$lrname");
803     mkdir "$lrname" || die "can't make $lrname dir: $!";
804 }
805
806 sub writelog
807 {
808     my $stage = shift;
809     my $loglines = shift;
810     my $handle;
811     my $lrname = $st_prefix . $logdirname;
812     open($handle,">$lrname/$stage.log") || die $!;
813     print $handle @$loglines;
814     close($handle);
815 }
816
817 sub display_features
818 {
819     return unless step_wanted('features');
820     my @out = `cd $exim
821                src/build-*/exim -C test/confs/0000 -bV `;
822     my $status = $? >>8;
823     writelog('features',\@out);
824     print "======== features log ===========\n",@out if ($verbose > 1);
825     send_result('Features',$status,\@out) if $status;
826     $steps_completed .= " Features";
827 }
828     
829 sub check_make
830 {
831     # Allow farm member to configure non-GNU make
832     my $non_gnu_make = $EximBuild::conf{non_gnu_make};
833     if (!defined $non_gnu_make ||
834         (defined $non_gnu_make && $non_gnu_make == 1)) {
835       return 'OK';
836     }
837     my @out = `$make -v 2>&1`;
838     return undef unless ($? == 0 && grep {/GNU Make/} @out);
839     return 'OK';
840 }
841
842 sub make
843 {
844     return unless step_wanted('make');
845     print time_str(),"running make ...\n" if $verbose;
846     my $make_args = join(' ',$EximBuild::conf{make_args});
847     my (@makeout);
848     my $make_cmd = $make;
849     $make_cmd = "$make -j $make_jobs"
850       if ($make_jobs > 1 && ($branch eq 'HEAD' || $branch ge 'REL9_1'));
851     @makeout = `cd $exim/src && $make_cmd $make_args 2>&1`;
852     my $status = $? >>8;
853     writelog('make',\@makeout);
854     print "======== make log ===========\n",@makeout if ($verbose > 1);
855     send_result('Make',$status,\@makeout) if $status;
856     $steps_completed .= " Make";
857 }
858
859 sub make_doc
860 {
861     return unless step_wanted('make-doc');
862     print time_str(),"running make doc ...\n" if $verbose;
863
864     my (@makeout);
865     @makeout = `cd $exim/doc/doc-docbook/ && \
866                 EXIM_VER="4.82" $make everything 2>&1`;
867     my $status = $? >>8;
868     writelog('make-doc',\@makeout);
869     print "======== make doc log ===========\n",@makeout if ($verbose > 1);
870     send_result('Doc',$status,\@makeout) if $status;
871     $steps_completed .= " Doc";
872 }
873
874 sub get_stack_trace
875 {
876     my $bindir = shift;
877     my $pgdata = shift;
878
879     # no core = no result
880     my @cores = glob("$pgdata/$core_file_glob");
881     return () unless @cores;
882
883     # no gdb = no result
884     system "gdb --version > $devnull 2>&1";
885     my $status = $? >>8;
886     return () if $status;
887
888     my $cmdfile = "./gdbcmd";
889     my $handle;
890     open($handle, ">$cmdfile");
891     print $handle "bt\n";
892     close($handle);
893
894     my @trace;
895
896     foreach my $core (@cores)
897     {
898         my @onetrace = `gdb -x $cmdfile --batch $bindir/exim $core 2>&1`;
899         push(@trace,
900             "\n\n================== stack trace: $core ==================\n",
901             @onetrace);
902     }
903
904     unlink $cmdfile;
905
906     return @trace;
907 }
908
909 sub make_install_check
910 {
911     my $locale = shift;
912     return unless step_wanted('install-check');
913     print time_str(),"running make installcheck ($locale)...\n" if $verbose;
914
915     my @checklog;
916     unless ($using_msvc)
917     {
918         @checklog = `cd $exim/src/test/regress && $make installcheck 2>&1`;
919     }
920     else
921     {
922         chdir "$exim/src/tools/msvc";
923         @checklog = `perl vcregress.pl installcheck 2>&1`;
924         chdir $branch_root;
925     }
926     my $status = $? >>8;
927     my @logfiles =
928       ("$exim/src/test/regress/regression.diffs","$installdir/logfile");
929     foreach my $logfile(@logfiles)
930     {
931         next unless (-e $logfile );
932         push(@checklog,"\n\n================== $logfile ==================\n");
933         my $handle;
934         open($handle,$logfile);
935         while(<$handle>)
936         {
937             push(@checklog,$_);
938         }
939         close($handle);
940     }
941     if ($status)
942     {
943         my @trace =
944           get_stack_trace("$installdir/bin","$installdir/data-$locale");
945         push(@checklog,@trace);
946     }
947     writelog("install-check-$locale",\@checklog);
948     print "======== make installcheck log ===========\n",@checklog
949       if ($verbose > 1);
950     send_result("InstallCheck-$locale",$status,\@checklog) if $status;
951     $steps_completed .= " InstallCheck-$locale";
952 }
953
954 sub make_isolation_check
955 {
956     my $locale = shift;
957     return unless step_wanted('isolation-check');
958     my @makeout;
959     unless ($using_msvc)
960     {
961         my $cmd =
962           "cd $exim/src/test/isolation && $make NO_LOCALE=1 installcheck";
963         @makeout = `$cmd 2>&1`;
964     }
965     else
966     {
967         chdir "$exim/src/tools/msvc";
968         @makeout = `perl vcregress.pl isolationcheck 2>&1`;
969         chdir $branch_root;
970     }
971
972     my $status = $? >>8;
973
974     # get the log files and the regression diffs
975     my @logs = glob("$exim/src/test/isolation/log/*.log");
976     push(@logs,"$installdir/logfile");
977     unshift(@logs,"$exim/src/test/isolation/regression.diffs")
978       if (-e "$exim/src/test/isolation/regression.diffs");
979     foreach my $logfile (@logs)
980     {
981         push(@makeout,"\n\n================== $logfile ===================\n");
982         my $handle;
983         open($handle,$logfile);
984         while(<$handle>)
985         {
986             push(@makeout,$_);
987         }
988         close($handle);
989     }
990     if ($status)
991     {
992         my @trace =
993           get_stack_trace("$installdir/bin","$installdir/data-$locale");
994         push(@makeout,@trace);
995     }
996     writelog('isolation-check',\@makeout);
997     print "======== make isolation check logs ===========\n",@makeout
998       if ($verbose > 1);
999
1000     send_result('IsolationCheck',$status,\@makeout) if $status;
1001     $steps_completed .= " IsolationCheck";
1002 }
1003
1004 sub make_test
1005 {
1006     return unless step_wanted('test');
1007     print time_str(),"running make test ...\n" if $verbose;
1008     my $tests_range = $EximBuild::conf{range_num_tests} || "1 4";
1009     my @makeout;
1010     @makeout =`(cd $exim/test
1011                 autoconf && ./configure && $make )2>&1 `;
1012     my $status = $? >>8;
1013     unless($status)
1014     {
1015       my @tmp = `(WORKDIR=\$PWD
1016                   cd $exim/test
1017                   ./runtest \$WORKDIR/$exim/src/build-*/exim -CONTINUE $tests_range )2>&1`;
1018       $status = $? >>8;
1019       push @makeout, @tmp;
1020       # Prepend the failed summary log outputs for ease of reading
1021       my $fail_summary = "$exim/test/failed-summary.log";
1022       if (-f $fail_summary)
1023       {
1024         @tmp = `cat $fail_summary`;
1025         push @tmp, "\n";
1026         unshift @makeout, @tmp;
1027         unshift @makeout, "Summary of failed tests:\n";
1028       }
1029     }
1030     writelog('test',\@makeout);
1031     print "======== make test logs ===========\n",@makeout
1032       if ($verbose > 1);
1033
1034     send_result('Test',$status,\@makeout) if $status;
1035     $steps_completed .= " Test";
1036 }
1037
1038 sub make_ecpg_check
1039 {
1040     return unless step_wanted('ecpg-check');
1041     my @makeout;
1042     my $ecpg_dir = "$exim/src/interfaces/ecpg";
1043     if ($using_msvc)
1044     {
1045         chdir "$exim/src/tools/msvc";
1046         @makeout = `perl vcregress.pl ecpgcheck 2>&1`;
1047         chdir $branch_root;
1048     }
1049     else
1050     {
1051         @makeout = `cd  $ecpg_dir && $make NO_LOCALE=1 check 2>&1`;
1052     }
1053     my $status = $? >>8;
1054
1055     # get the log files and the regression diffs
1056     my @logs = glob("$ecpg_dir/test/log/*.log");
1057     unshift(@logs,"$ecpg_dir/test/regression.diffs")
1058       if (-e "$ecpg_dir/test/regression.diffs");
1059     foreach my $logfile (@logs)
1060     {
1061         push(@makeout,"\n\n================== $logfile ===================\n");
1062         my $handle;
1063         open($handle,$logfile);
1064         while(<$handle>)
1065         {
1066             push(@makeout,$_);
1067         }
1068         close($handle);
1069     }
1070     if ($status)
1071     {
1072         my $base = "$ecpg_dir/test/regress/tmp_check";
1073         my @trace =
1074           get_stack_trace("$base/install$installdir/bin",       "$base/data");
1075         push(@makeout,@trace);
1076     }
1077     writelog('ecpg-check',\@makeout);
1078     print "======== make ecpg check logs ===========\n",@makeout
1079       if ($verbose > 1);
1080
1081     send_result('ECPG-Check',$status,\@makeout) if $status;
1082     $steps_completed .= " ECPG-Check";
1083 }
1084
1085 sub configure
1086 {
1087     return unless step_wanted('configure');
1088     print time_str(),"creating configuration ...\n" if $verbose;
1089
1090     my $env = $EximBuild::conf{makefile_set};
1091     my $add = $EximBuild::conf{makefile_add};
1092     my $features = $EximBuild::conf{makefile_regex};
1093
1094     my $envstr = "";
1095     while (my ($key,$val) = each %$env)
1096     {
1097         $envstr .= "$key='$val'\n";
1098     }
1099     while (my ($key,$val) = each %$add)
1100     {
1101         $envstr .= "$key+='$val'\n";
1102     }
1103
1104     my $conf_path = "src/src/EDITME";
1105     my $local_conf = "src/Local/Makefile";
1106     my @confout = `cd $exim; mkdir -p src/Local 2>&1`;
1107     my @tmp = `cd $exim && cp $conf_path $local_conf 2>&1`;
1108     my $status = $? >> 8;
1109     push @confout, @tmp;
1110     if ($status == 0)
1111     {
1112         # First, let's display some directory permissions in case
1113         # permissions are causing problems.
1114         my @dir = split('/',`pwd`);
1115         chomp(@dir);
1116         my $count = scalar @dir;
1117         my $loop = 1;
1118         my $dirs = '';
1119         while ($loop < $count)
1120         {
1121           my $dir = "";
1122           foreach my $i (0 .. $loop)
1123           {
1124             $dir .= $dir[$i].'/';
1125           }
1126           $dirs .= " $dir";
1127           $loop++;
1128         }
1129         @tmp = `echo "Verify Directory Permissions"
1130                 ls -ld $dirs`;
1131         push @confout, @tmp;
1132         # Build the config file from the EDITME template
1133         @tmp = `cd $exim && echo '$envstr' >> $local_conf`;
1134         push @confout, @tmp;
1135         my $exim_user = $EximBuild::conf{master_exim_user} || 'exim';
1136         @tmp = `echo "Hardcoded Exim user info:"; id $exim_user
1137           cd $exim && perl -pi -e 's/^EXIM_USER=.*/EXIM_USER=$exim_user/' $local_conf`;
1138         push @confout, @tmp;
1139         my $me = `whoami`; chomp $me;
1140         @tmp = `echo "Build Farm user info:"; id $me
1141           cd $exim && perl -pi -e 's/^# CONFIGURE_OWNER=\$/CONFIGURE_OWNER=$me/' $local_conf`;
1142         push @confout, @tmp;
1143         @tmp = `cd $exim && perl -pi -e 's/^# TRUSTED_CONFIG_LIST=/TRUSTED_CONFIG_LIST=/' $local_conf`;
1144         push @confout, @tmp;
1145         @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`;
1146         push @confout, @tmp;
1147         @tmp = `cd $exim && perl -pi -e 's/^EXIM_MONITOR=(.*)/# EXIM_MONITOR=\$1/' $local_conf`;
1148         push @confout, @tmp;
1149         for my $regex ( @$features )
1150         {
1151             @tmp = `cd $exim
1152                     perl -pi -e '$regex' $local_conf 2>&1
1153                     echo "Used regex: $regex" `;
1154             push @confout, @tmp;
1155         }
1156         # Add the final build file to the display output
1157         @tmp = `cd $exim
1158                 echo
1159                 echo "Contents of Local/Makefile:"
1160                 egrep '^[^#]' $local_conf `;
1161         push @confout, @tmp;
1162         # Build the config_opts array to send to the server
1163         chomp @tmp;
1164         my @config_opts = grep s/(?:LOOKUP_|EXPERIMENTAL_|USE_)(\S+)=.*/$1/,
1165                           @tmp;
1166         push @config_opts, grep s/^(?:EXIM_)(PERL|PYTHON)=.*/$1/,
1167                            @tmp;
1168         # OpenSSL doesn't have a specific USE flag
1169         push @config_opts, grep s/^(TLS_LIBS.*-l(ssl|crypto)).*/OPENSSL/,
1170                            @tmp;
1171         $EximBuild::conf{config_opts} = \@config_opts;
1172         
1173         # Does not matter what the Exim version is, as long as it is valid.
1174         my $exim_ver = $EximBuild::conf{exim_test_version} || '4.82';
1175         `cd $exim
1176          echo 'EXIM_RELEASE_VERSION="$exim_ver"' > src/src/version.sh
1177          echo 'EXIM_VARIANT_VERSION=""' >> src/src/version.sh
1178          echo 'EXIM_COMPILE_NUMBER="0"' >> src/src/version.sh`;
1179     }
1180    
1181     print "======== configure output ===========\n",@confout
1182       if ($verbose > 1);
1183
1184     writelog('configure',\@confout);
1185
1186     if ($status)
1187     {
1188         send_result('Configure',$status,\@confout);
1189     }
1190
1191     $steps_completed .= " Configure";
1192 }
1193
1194 sub find_last
1195 {
1196     my $which = shift;
1197     my $stname = $st_prefix . "last.$which";
1198     my $handle;
1199     open($handle,$stname) or return undef;
1200     my $time = <$handle>;
1201     close($handle);
1202     chomp $time;
1203     return $time + 0;
1204 }
1205
1206 sub set_last
1207 {
1208     my $which = shift;
1209     my $stname = $st_prefix . "last.$which";
1210     my $st_now = shift || time;
1211     my $handle;
1212     open($handle,">$stname") or die "opening $stname: $!";
1213     print $handle "$st_now\n";
1214     close($handle);
1215 }
1216
1217 sub send_result
1218 {
1219
1220     # clean up temp file
1221     $extraconf = undef;
1222
1223     my $stage = shift;
1224
1225     my $ts = $now || time;
1226     my $status=shift || 0;
1227     my $log = shift || [];
1228     print "======== log passed to send_result ===========\n",@$log
1229       if ($verbose > 1);
1230
1231     unshift(@$log,
1232         "Last file mtime in snapshot: ",
1233         scalar(gmtime($current_snap)),
1234         " GMT\n","===================================================\n")
1235       unless ($from_source || !$current_snap);
1236
1237     my $log_data = join("",@$log);
1238     my $confsum = "";
1239     my $changed_this_run = "";
1240     my $changed_since_success = "";
1241     $changed_this_run = join("!",@changed_files)
1242       if @changed_files;
1243     $changed_since_success = join("!",@changed_since_success)
1244       if ($stage ne 'OK' && @changed_since_success);
1245
1246     if ($stage eq 'OK')
1247     {
1248         $confsum= $saved_config;
1249     }
1250     elsif ($stage !~ /CVS|Git|SCM/ )
1251     {
1252         $confsum = get_config_summary();
1253     }
1254     else
1255     {
1256         $confsum = get_script_config_dump();
1257     }
1258
1259     my $savedata = Data::Dumper->Dump(
1260         [
1261             $changed_this_run, $changed_since_success, $branch, $status,$stage,
1262             $animal, $ts,$log_data, $confsum, $target, $verbose, $secret
1263         ],
1264         [
1265             qw(changed_this_run changed_since_success branch status stage
1266               animal ts log_data confsum target verbose secret)
1267         ]
1268     );
1269
1270     my $lrname = $st_prefix . $logdirname;
1271
1272     # might happen if there is a CVS failure and have never got further
1273     mkdir $lrname unless -d $lrname;
1274
1275     my $txfname = "$lrname/web-txn.data";
1276     my $txdhandle;
1277     open($txdhandle,">$txfname");
1278     print $txdhandle $savedata;
1279     close($txdhandle);
1280
1281     if ($nosend || $stage eq 'CVS' || $stage eq 'CVS-status' )
1282     {
1283         print "Branch: $branch\n";
1284         if ($stage eq 'OK')
1285         {
1286             print "All stages succeeded\n";
1287             set_last('success.snap',$current_snap) unless $nostatus;
1288             exit(0);
1289         }
1290         else
1291         {
1292             print "Stage $stage failed with status $status\n";
1293             exit(1);
1294         }
1295     }
1296
1297     if ($stage !~ /CVS|Git|SCM|Pre-run-port-check/ )
1298     {
1299
1300         my @logfiles = glob("$lrname/*.log");
1301         my %mtimes = map { $_ => (stat $_)[9] } @logfiles;
1302         @logfiles =
1303           map { basename $_ }( sort { $mtimes{$a} <=> $mtimes{$b} } @logfiles );
1304         my $logfiles = join(' ',@logfiles);
1305         $tar_log_cmd =~ s/\*\.log/$logfiles/;
1306         chdir($lrname);
1307         system("$tar_log_cmd 2>&1 ");
1308         chdir($branch_root);
1309
1310     }
1311     else
1312     {
1313
1314         # these would be from an earlier run, since we
1315         # do cleanlogs() after the cvs stage
1316         # so don't send them.
1317         unlink "$lrname/runlogs.tgz";
1318     }
1319
1320     my $txstatus;
1321
1322     # this should now only apply to older Msys installs. All others should
1323     # be running with perl >= 5.8 since that's required to build exim
1324     # anyway
1325     if (!$^V or $^V lt v5.8.0)
1326     {
1327
1328         unless (-x "$aux_path/run_web_txn.pl")
1329         {
1330             print "Could not locate $aux_path/run_web_txn.pl\n";
1331             exit(1);
1332         }
1333
1334         system("$aux_path/run_web_txn.pl $lrname");
1335         $txstatus = $? >> 8;
1336     }
1337     else
1338     {
1339         $txstatus = EximBuild::WebTxn::run_web_txn($lrname) ? 0 : 1;
1340
1341     }
1342
1343     if ($txstatus)
1344     {
1345         print "Web txn failed with status: $txstatus\n";
1346
1347         # if the web txn fails, restore the timestamps
1348         # so we try again the next time.
1349         set_last('status',$last_status) unless $nostatus;
1350         set_last('run.snap',$last_run_snap) unless $nostatus;
1351         exit($txstatus);
1352     }
1353
1354     unless ($stage eq 'OK' || $quiet)
1355     {
1356         print "BuildFarm member $animal failed on $branch stage $stage\n";
1357     }
1358
1359     #   print "Success!\n",$response->content
1360     #           if $print_success;
1361
1362     set_last('success.snap',$current_snap) if ($stage eq 'OK' && !$nostatus);
1363
1364     exit 0;
1365 }
1366
1367 sub get_config_summary
1368 {
1369     my $handle;
1370     my $config = "";
1371     # unless ($using_msvc)
1372     # {
1373     #     open($handle,"$exim/config.log") || return undef;
1374     #     my $start = undef;
1375     #     while (<$handle>)
1376     #     {
1377     #         if (!$start && /created by PostgreSQL configure/)
1378     #         {
1379     #             $start=1;
1380     #             s/It was/This file was/;
1381     #         }
1382     #         next unless $start;
1383     #         last if /Core tests/;
1384     #         next if /^\#/;
1385     #         next if /= <?unknown>?/;
1386
1387     #         # split up long configure line
1388     #         if (m!\$.*configure.*--with! && length > 70)
1389     #         {
1390     #             my $pos = index($_," ",70);
1391     #             substr($_,$pos+1,0,"\\\n        ") if ($pos > 0);
1392     #             $pos = index($_," ",140);
1393     #             substr($_,$pos+1,0,"\\\n        ") if ($pos > 0);
1394     #             $pos = index($_," ",210);
1395     #             substr($_,$pos+1,0,"\\\n        ") if ($pos > 0);
1396     #         }
1397     #         $config .= $_;
1398     #     }
1399     #     close($handle);
1400     #     $config .=
1401     #       "\n========================================================\n";
1402     # }
1403     $config .= get_script_config_dump();
1404     return $config;
1405 }
1406
1407 sub get_script_config_dump
1408 {
1409     my $conf = {
1410         %EximBuild::conf,  # shallow copy
1411         script_version => $VERSION,
1412         invocation_args => \@invocation_args,
1413         steps_completed => $steps_completed,
1414         orig_env => $orig_env,
1415     };
1416     delete $conf->{secret};
1417     $Data::Dumper::Sortkeys = 1;
1418     return  Data::Dumper->Dump([$conf],['Script_Config']);
1419 }
1420
1421 sub scm_timeout
1422 {
1423     my $wait_time = shift;
1424     my $who_to_kill = getpgrp(0);
1425     my $sig = SIGTERM;
1426     $sig = -$sig;
1427     print "waiting $wait_time secs to time out process $who_to_kill\n"
1428       if $verbose;
1429     foreach my $sig (qw(INT TERM HUP QUIT))
1430     {
1431         $SIG{$sig}='DEFAULT';
1432     }
1433     sleep($wait_time);
1434     $SIG{TERM} = 'IGNORE'; # so we don't kill ourself, we're exiting anyway
1435     # kill the whole process group
1436     unless (kill $sig,$who_to_kill)
1437     {
1438         print "scm timeout kill failed\n";
1439     }
1440 }
1441
1442 sub spawn
1443 {
1444     my $coderef = shift;
1445     my $pid = fork;
1446     if (defined($pid) && $pid == 0)
1447     {
1448         exit &$coderef(@_);
1449     }
1450     return $pid;
1451 }
1452