Add a max_days param, default 10, to failures page.
[buildfarm-server.git] / cgi-bin / pgstatus.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 use strict;
12
13 use vars qw($dbhost $dbname $dbuser $dbpass $dbport
14        $all_stat $fail_stat $change_stat $green_stat
15        $server_time
16            $min_script_version $min_web_script_version
17        $default_host
18 );
19
20 # force this before we do anything - even load modules
21 BEGIN { $server_time = time; }
22
23 use CGI;
24 use Digest::SHA1  qw(sha1_hex);
25 use MIME::Base64;
26 use DBI;
27 use DBD::Pg;
28 use Data::Dumper;
29 use Mail::Send;
30 use Time::ParseDate;
31 use Storable qw(thaw);
32
33 require "$ENV{BFConfDir}/BuildFarmWeb.pl";
34 my $buildlogs = "$ENV{BFConfDir}/buildlogs";
35
36 die "no dbname" unless $dbname;
37 die "no dbuser" unless $dbuser;
38
39 my $dsn="dbi:Pg:dbname=$dbname";
40 $dsn .= ";host=$dbhost" if $dbhost;
41 $dsn .= ";port=$dbport" if $dbport;
42
43 my $query = new CGI;
44
45 my $sig = $query->path_info;
46 $sig =~ s!^/!!;
47
48 my $stage = $query->param('stage');
49 my $ts = $query->param('ts');
50 my $animal = $query->param('animal');
51 my $log = $query->param('log');
52 my $res = $query->param('res');
53 my $conf = $query->param('conf');
54 my $branch = $query->param('branch');
55 my $changed_since_success = $query->param('changed_since_success');
56 my $changed_this_run = $query->param('changed_files');
57 my $log_archive = $query->param('logtar');
58 my $frozen_sconf = $query->param('frozen_sconf') || '';
59
60 my $brhandle;
61 if (open($brhandle,"../htdocs/branches_of_interest.txt"))
62 {
63     my @branches_of_interest = <$brhandle>;
64     close($brhandle);
65     chomp(@branches_of_interest);
66     unless (grep {$_ eq $branch} @branches_of_interest)
67     {
68         print
69             "Status: 492 bad branch parameter $branch\nContent-Type: text/plain\n\n",
70             "bad branch parameter $branch\n";
71         exit;   
72     }
73 }
74
75
76 my $content = 
77         "branch=$branch&res=$res&stage=$stage&animal=$animal&".
78         "ts=$ts&log=$log&conf=$conf";
79
80 my $extra_content = 
81         "changed_files=$changed_this_run&".
82         "changed_since_success=$changed_since_success&";
83
84 unless ($animal && $ts && $stage && $sig)
85 {
86         print 
87             "Status: 490 bad parameters\nContent-Type: text/plain\n\n",
88             "bad parameters for request\n";
89         exit;
90         
91 }
92
93 unless ($branch =~ /^(HEAD|REL\d+_\d+_STABLE)$/)
94 {
95         print
96             "Status: 492 bad branch parameter $branch\nContent-Type: text/plain\n\n",
97             "bad branch parameter $branch\n";
98         exit;
99
100 }
101
102
103 my $db = DBI->connect($dsn,$dbuser,$dbpass);
104
105 die $DBI::errstr unless $db;
106
107 my $gethost=
108     "select secret from buildsystems where name = ? and status = 'approved'";
109 my $sth = $db->prepare($gethost);
110 $sth->execute($animal);
111 my ($secret)=$sth->fetchrow_array();
112 $sth->finish;
113
114 my $tsdiff = time - $ts;
115
116 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($ts);
117 $year += 1900; $mon +=1;
118 my $date=
119     sprintf("%d-%.2d-%.2d_%.2d:%.2d:%.2d",$year,$mon,$mday,$hour,$min,$sec);
120
121 if ($ENV{BF_DEBUG} || ($ts > time) || ($ts + 86400 < time ) || (! $secret) )
122 {
123     open(TX,">$buildlogs/$animal.$date");
124     print TX "sig=$sig\nlogtar-len=" , length($log_archive),
125         "\nstatus=$res\nstage=$stage\nconf:\n$conf\n",
126         "tsdiff:$tsdiff\n",
127         "changed_this_run:\n$changed_this_run\n",
128         "changed_since_success:\n$changed_since_success\n",
129         "frozen_sconf:$frozen_sconf\n",
130         "log:\n",$log;
131 #    $query->save(\*TX);
132     close(TX);
133 }
134
135 unless ($ts < time + 120)
136 {
137     my $gmt = gmtime($ts);
138     print "Status: 491 bad ts parameter - $ts ($gmt GMT) is in the future.\n",
139     "Content-Type: text/plain\n\n bad ts parameter - $ts ($gmt GMT) is in the future\n";
140         $db->disconnect;
141     exit;
142 }
143
144 unless ($ts + 86400 > time)
145 {
146     my $gmt = gmtime($ts);
147     print "Status: 491 bad ts parameter - $ts ($gmt GMT) is more than 24 hours ago.\n",
148      "Content-Type: text/plain\n\n bad ts parameter - $ts ($gmt GMT) is more than 24 hours ago.\n";
149     $db->disconnect;
150     exit;
151 }
152
153 unless ($secret)
154 {
155         print 
156             "Status: 495 Unknown System\nContent-Type: text/plain\n\n",
157             "System $animal is unknown\n";
158         $db->disconnect;
159         exit;
160         
161 }
162
163
164
165
166 my $calc_sig = sha1_hex($content,$secret);
167 my $calc_sig2 = sha1_hex($extra_content,$content,$secret);
168
169 if ($calc_sig ne $sig && $calc_sig2 ne $sig)
170 {
171
172         print "Status: 450 sig mismatch\nContent-Type: text/plain\n\n";
173         print "$sig mismatches $calc_sig($calc_sig2) on content:\n$content";
174         $db->disconnect;
175         exit;
176 }
177
178 # undo escape-proofing of base64 data and decode it
179 map {tr/$@/+=/; $_ = decode_base64($_); } 
180     ($log, $conf,$changed_this_run,$changed_since_success,$log_archive, $frozen_sconf);
181
182 if ($log =~/Last file mtime in snapshot: (.*)/)
183 {
184     my $snaptime = parsedate($1);
185     if ($snaptime < (time - (10 * 86400)))
186     {
187         print "Status: 493 snapshot too old: $1\nContent-Type: text/plain\n\n";
188         print "snapshot to old: $1\n";
189         $db->disconnect;
190         exit;   
191     }
192 }
193
194 ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime($ts);
195 $year += 1900; $mon +=1;
196 my $dbdate=
197     sprintf("%d-%.2d-%.2d %.2d:%.2d:%.2d",$year,$mon,$mday,$hour,$min,$sec);
198
199 my $log_file_names;
200 my @log_file_names;
201 my $dirname = "$buildlogs/tmp.$$.unpacklogs";
202
203 my $githeadref;
204
205 if ($log_archive)
206 {
207     my $log_handle;
208     my $archname = "$buildlogs/tmp.$$.tgz";
209     open($log_handle,">$archname");
210     binmode $log_handle;
211     print $log_handle $log_archive;
212     close $log_handle;
213     mkdir $dirname;
214     @log_file_names = `tar -z -C $dirname -xvf $archname 2>/dev/null`;
215     map {s/\s+//g; } @log_file_names;
216     my @qnames = grep { $_ ne 'githead.log' } @log_file_names;
217     map { $_ = qq("$_"); } @qnames;
218     $log_file_names = '{' . join(',',@qnames) . '}';
219     if (-e "$dirname/githead.log" )
220     {
221         open(my $githead,"$dirname/githead.log");
222         $githeadref = <$githead>;
223         chomp $githeadref;
224         close $githead;
225     }
226     # unlink $archname;
227 }
228
229 my $config_flags;
230 my $client_conf;
231 if ($frozen_sconf)
232 {
233     $client_conf = thaw $frozen_sconf;
234 }
235
236 if ($min_script_version)
237 {
238         $client_conf->{script_version} ||= '0.0';
239         my $cli_ver = $client_conf->{script_version} ;
240         $cli_ver =~ s/^REL_//;
241         my ($minmajor,$minminor) = split(/\./,$min_script_version);
242         my ($smajor,$sminor) = split(/\./,$cli_ver);
243         if ($minmajor > $smajor || ($minmajor == $smajor && $minminor > $sminor))
244         {
245                 print "Status: 460 script version too low\nContent-Type: text/plain\n\n";
246                 print 
247                         "Script version is below minimum required\n",
248                         "Reported version: $client_conf->{script_version},",
249                         "Minumum version required: $min_script_version\n";
250                 $db->disconnect;
251                 exit;
252         }
253 }
254
255 if ($min_web_script_version)
256 {
257         $client_conf->{web_script_version} ||= '0.0';
258         my $cli_ver = $client_conf->{web_script_version} ;
259         $cli_ver =~ s/^REL_//;
260         my ($minmajor,$minminor) = split(/\./,$min_web_script_version);
261         my ($smajor,$sminor) = split(/\./,$cli_ver);
262         if ($minmajor > $smajor || ($minmajor == $smajor && $minminor > $sminor))
263         {
264                 print "Status: 461 web script version too low\nContent-Type: text/plain\n\n";
265                 print 
266                         "Web Script version is below minimum required\n",
267                         "Reported version: $client_conf->{web_script_version}, ",
268                         "Minumum version required: $min_web_script_version\n"
269                         ;
270                 $db->disconnect;
271                 exit;
272         }
273 }
274
275 my @config_flags;
276 if (not exists $client_conf->{config_opts} )
277 {
278         @config_flags = ();
279 }
280 elsif (ref $client_conf->{config_opts} eq 'HASH')
281 {
282         # leave out keys with false values
283         @config_flags = grep { $client_conf->{config_opts}->{$_} } 
284             keys %{$client_conf->{config_opts}};
285 }
286 elsif (ref $client_conf->{config_opts} eq 'ARRAY' )
287 {
288         @config_flags = @{$client_conf->{config_opts}};
289 }
290
291 if (@config_flags)
292 {
293     @config_flags = grep {! m/=/ } @config_flags;
294     map {s/\s+//g; $_=qq("$_"); } @config_flags;
295     push @config_flags,'git' if $client_conf->{scm} eq 'git';
296     $config_flags = '{' . join(',',@config_flags) . '}' ;
297 }
298
299 my $scm = $client_conf->{scm} || 'cvs';
300 my $scmurl = $client_conf->{scm_url};
301
302 my $logst = <<EOSQL;
303     insert into build_status 
304       (sysname, snapshot,status, stage, log,conf_sum, branch,
305        changed_this_run, changed_since_success, 
306        log_archive_filenames , log_archive, build_flags, scm, scmurl, 
307        git_head_ref,frozen_conf)
308     values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
309 EOSQL
310 ;
311
312
313 # this transaction lets us set log_error_verbosity to terse
314 # just for the duration of the transaction. That turns off logging the
315 # bind params, so all the logs don't get stuffed on the postgres logs
316
317 $db->begin_work;
318 $db->do("select set_local_error_terse()");
319
320
321 $sth=$db->prepare($logst);
322
323 $sth->bind_param(1,$animal);
324 $sth->bind_param(2,$dbdate);
325 $sth->bind_param(3,$res);
326 $sth->bind_param(4,$stage);
327 $sth->bind_param(5,$log);
328 $sth->bind_param(6,$conf);
329 $sth->bind_param(7,$branch);
330 $sth->bind_param(8,$changed_this_run);
331 $sth->bind_param(9,$changed_since_success);
332 $sth->bind_param(10,$log_file_names);
333 #$sth->bind_param(11,$log_archive,{ pg_type => DBD::Pg::PG_BYTEA });
334 $sth->bind_param(11,undef,{ pg_type => DBD::Pg::PG_BYTEA });
335 $sth->bind_param(12,$config_flags);
336 $sth->bind_param(13,$scm);
337 $sth->bind_param(14,$scmurl);
338 $sth->bind_param(15,$githeadref);
339 $sth->bind_param(16,$frozen_sconf,{ pg_type => DBD::Pg::PG_BYTEA });
340
341 $sth->execute;
342 $sth->finish;
343
344
345
346 my $logst2 = <<EOSQL;
347
348   insert into build_status_log 
349     (sysname, snapshot, branch, log_stage, log_text, stage_duration)
350     values (?, ?, ?, ?, ?, ?)
351
352 EOSQL
353     ;
354
355 $sth = $db->prepare($logst2);
356
357 $/=undef;
358
359 my $stage_start = $ts;
360
361 foreach my $log_file( @log_file_names )
362 {
363     next if $log_file =~ /^githead/;
364     my $handle;
365     open($handle,"$dirname/$log_file");
366     my $mtime = (stat $handle)[9];
367     my $stage_interval = $mtime - $stage_start;
368     $stage_start = $mtime;
369     my $ltext = <$handle>;
370     close($handle);
371     $ltext =~ s/\x00/\\0/g;
372     $sth->execute($animal,$dbdate,$branch,$log_file,$ltext, 
373                   "$stage_interval seconds");
374 }
375
376 $sth->finish;
377
378 $db->commit;
379
380 my $prevst = <<EOSQL;
381
382   select coalesce((select distinct on (snapshot) stage
383                   from build_status
384                   where sysname = ? and branch = ? and snapshot < ?
385                   order by snapshot desc
386                   limit 1), 'NEW') as prev_status
387   
388 EOSQL
389
390 $sth=$db->prepare($prevst);
391 $sth->execute($animal,$branch,$dbdate);
392 my $row=$sth->fetchrow_arrayref;
393 my $prev_stat=$row->[0];
394 $sth->finish;
395
396 my $det_st = <<EOS;
397
398           select operating_system|| ' / ' || os_version as os , 
399                  compiler || ' / ' || compiler_version as compiler, 
400                  architecture as arch
401           from buildsystems 
402           where status = 'approved'
403                 and name = ?
404
405 EOS
406 ;
407 $sth=$db->prepare($det_st);
408 $sth->execute($animal);
409 $row=$sth->fetchrow_arrayref;
410 my ($os, $compiler,$arch) = @$row;
411 $sth->finish;
412
413 $db->begin_work;
414 # prevent occasional duplication by forcing serialization of this operation
415 $db->do("lock table dashboard_mat in share row exclusive mode");
416 $db->do("delete from dashboard_mat");
417 $db->do("insert into dashboard_mat select * from dashboard_mat_data");
418 $db->commit;
419
420 if ($stage ne 'OK')
421 {
422         $db->begin_work;
423         # prevent occasional duplication by forcing serialization of this operation
424         $db->do("lock table nrecent_failures in share row exclusive mode");
425         $db->do("delete from nrecent_failures");
426         $db->do("insert into nrecent_failures select bs.sysname, bs.snapshot, bs.branch from build_status bs where bs.stage <> 'OK' and bs.snapshot > now() - interval '90 days'");
427         $db->commit;
428 }
429
430 $db->disconnect;
431
432 print "Content-Type: text/plain\n\n";
433 print "request was on:\n";
434 print "res=$res&stage=$stage&animal=$animal&ts=$ts";
435
436 my $client_events = $client_conf->{mail_events};
437
438 if ($ENV{BF_DEBUG})
439 {
440         my $client_time = $client_conf->{current_ts};
441     open(TX,">>$buildlogs/$animal.$date");
442     print TX "\n",Dumper(\$client_conf),"\n";
443         print TX "server time: $server_time, client time: $client_time\n" if $client_time;
444     close(TX);
445 }
446
447 my $bcc_stat = [];
448 my $bcc_chg=[];
449 if (ref $client_events)
450 {
451     my $cbcc = $client_events->{all};
452     if (ref $cbcc)
453     {
454         push @$bcc_stat, @$cbcc;
455     }
456     elsif (defined $cbcc)
457     {
458         push @$bcc_stat, $cbcc;
459     }
460     if ($stage ne 'OK')
461     {
462         $cbcc = $client_events->{all};
463         if (ref $cbcc)
464         {
465             push @$bcc_stat, @$cbcc;
466         }
467         elsif (defined $cbcc)
468         {
469             push @$bcc_stat, $cbcc;
470         }
471     }
472     $cbcc = $client_events->{change};
473     if (ref $cbcc)
474     {
475         push @$bcc_chg, @$cbcc;
476     }
477     elsif (defined $cbcc)
478     {
479         push @$bcc_chg, $cbcc;
480     }
481     if ($stage eq 'OK' || $prev_stat eq 'OK')
482     {
483         $cbcc = $client_events->{green};
484         if (ref $cbcc)
485         {
486             push @$bcc_chg, @$cbcc;
487         }
488         elsif (defined $cbcc)
489         {
490             push @$bcc_chg, $cbcc;
491         }
492     }
493 }
494
495
496 my $url = $query->url(-base => 1);
497
498
499 my $stat_type = $stage eq 'OK' ? 'Status' : 'Failed at Stage';
500
501 my $mailto = [@$all_stat];
502 push(@$mailto,@$fail_stat) if $stage ne 'OK';
503
504 my $me = `id -un`; chomp($me);
505
506 my $host = `hostname`; chomp ($host);
507 $host = $default_host unless ($host =~ m/[.]/ || !defined($default_host));
508
509 my $from_addr = "PG Build Farm <$me\@$host>";
510 $from_addr =~ tr /\r\n//d;
511
512 my $msg = new Mail::Send;
513
514
515 $msg->to(@$mailto);
516 $msg->bcc(@$bcc_stat) if (@$bcc_stat);
517 $msg->subject("PGBuildfarm member $animal Branch $branch $stat_type $stage");
518 $msg->set('From',$from_addr);
519 my $fh = $msg->open;
520 print $fh <<EOMAIL; 
521
522
523 The PGBuildfarm member $animal had the following event on branch $branch:
524
525 $stat_type: $stage
526
527 The snapshot timestamp for the build that triggered this notification is: $dbdate
528
529 The specs of this machine are:
530 OS:  $os
531 Arch: $arch
532 Comp: $compiler
533
534 For more information, see $url/cgi-bin/show_history.pl?nm=$animal&br=$branch
535
536 EOMAIL
537
538 $fh->close;
539
540 exit if ($stage eq $prev_stat);
541
542 $mailto = [@$change_stat];
543 push(@$mailto,@$green_stat) if ($stage eq 'OK' || $prev_stat eq 'OK');
544
545 $msg = new Mail::Send;
546
547
548 $msg->to(@$mailto);
549 $msg->bcc(@$bcc_chg) if (@$bcc_chg);
550
551 $stat_type = $prev_stat ne 'OK' ? "changed from $prev_stat failure to $stage" :
552     "changed from OK to $stage";
553 $stat_type = "New member: $stage" if $prev_stat eq 'NEW';
554 $stat_type .= " failure" if $stage ne 'OK';
555
556 $msg->subject("PGBuildfarm member $animal Branch $branch Status $stat_type");
557 $msg->set('From',$from_addr);
558 $fh = $msg->open;
559 print $fh <<EOMAIL;
560
561 The PGBuildfarm member $animal had the following event on branch $branch:
562
563 Status $stat_type
564
565 The snapshot timestamp for the build that triggered this notification is: $dbdate
566
567 The specs of this machine are:
568 OS:  $os
569 Arch: $arch
570 Comp: $compiler
571
572 For more information, see $url/cgi-bin/show_history.pl?nm=$animal&br=$branch
573
574 EOMAIL
575
576 $fh->close;