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