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