481eb5ad3855035488f6938ce6374260eb320996
[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 $sth=$db->prepare($logst);
299
300 $sth->bind_param(1,$animal);
301 $sth->bind_param(2,$dbdate);
302 $sth->bind_param(3,$res);
303 $sth->bind_param(4,$stage);
304 $sth->bind_param(5,$log);
305 $sth->bind_param(6,$conf);
306 $sth->bind_param(7,$branch);
307 $sth->bind_param(8,$changed_this_run);
308 $sth->bind_param(9,$changed_since_success);
309 $sth->bind_param(10,$log_file_names);
310 #$sth->bind_param(11,$log_archive,{ pg_type => DBD::Pg::PG_BYTEA });
311 $sth->bind_param(11,undef,{ pg_type => DBD::Pg::PG_BYTEA });
312 $sth->bind_param(12,$config_flags);
313 $sth->bind_param(13,$scm);
314 $sth->bind_param(14,$scmurl);
315 $sth->bind_param(15,$githeadref);
316 $sth->bind_param(16,$frozen_sconf,{ pg_type => DBD::Pg::PG_BYTEA });
317
318 $sth->execute;
319 $sth->finish;
320
321 my $logst2 = <<EOSQL;
322
323   insert into build_status_log 
324     (sysname, snapshot, branch, log_stage, log_text, stage_duration)
325     values (?, ?, ?, ?, ?, ?)
326
327 EOSQL
328     ;
329
330 $sth = $db->prepare($logst2);
331
332 $/=undef;
333
334 my $stage_start = $ts;
335
336 foreach my $log_file( @log_file_names )
337 {
338     next if $log_file =~ /^githead/;
339     my $handle;
340     open($handle,"$dirname/$log_file");
341     my $mtime = (stat $handle)[9];
342     my $stage_interval = $mtime - $stage_start;
343     $stage_start = $mtime;
344     my $ltext = <$handle>;
345     close($handle);
346     $ltext =~ s/\x00/\\0/g;
347     $sth->execute($animal,$dbdate,$branch,$log_file,$ltext, 
348                   "$stage_interval seconds");
349 }
350
351
352 $sth->finish;
353
354 my $prevst = <<EOSQL;
355
356   select coalesce((select distinct on (snapshot) stage
357                   from build_status
358                   where sysname = ? and branch = ? and snapshot < ?
359                   order by snapshot desc
360                   limit 1), 'NEW') as prev_status
361   
362 EOSQL
363
364 $sth=$db->prepare($prevst);
365 $sth->execute($animal,$branch,$dbdate);
366 my $row=$sth->fetchrow_arrayref;
367 my $prev_stat=$row->[0];
368 $sth->finish;
369
370 my $det_st = <<EOS;
371
372           select operating_system|| ' / ' || os_version as os , 
373                  compiler || ' / ' || compiler_version as compiler, 
374                  architecture as arch
375           from buildsystems 
376           where status = 'approved'
377                 and name = ?
378
379 EOS
380 ;
381 $sth=$db->prepare($det_st);
382 $sth->execute($animal);
383 $row=$sth->fetchrow_arrayref;
384 my ($os, $compiler,$arch) = @$row;
385 $sth->finish;
386
387 $db->begin_work;
388 # prevent occasional duplication by forcing serialization of this operation
389 $db->do("lock table dashboard_mat in share row exclusive mode");
390 $db->do("delete from dashboard_mat");
391 $db->do("insert into dashboard_mat select * from dashboard_mat_data");
392 $db->commit;
393
394 $db->disconnect;
395
396 print "Content-Type: text/plain\n\n";
397 print "request was on:\n";
398 print "res=$res&stage=$stage&animal=$animal&ts=$ts";
399
400 my $client_events = $client_conf->{mail_events};
401
402 if ($ENV{BF_DEBUG})
403 {
404         my $client_time = $client_conf->{current_ts};
405     open(TX,">>$buildlogs/$animal.$date");
406     print TX "\n",Dumper(\$client_conf),"\n";
407         print TX "server time: $server_time, client time: $client_time\n" if $client_time;
408     close(TX);
409 }
410
411 my $bcc_stat = [];
412 my $bcc_chg=[];
413 if (ref $client_events)
414 {
415     my $cbcc = $client_events->{all};
416     if (ref $cbcc)
417     {
418         push @$bcc_stat, @$cbcc;
419     }
420     elsif (defined $cbcc)
421     {
422         push @$bcc_stat, $cbcc;
423     }
424     if ($stage ne 'OK')
425     {
426         $cbcc = $client_events->{all};
427         if (ref $cbcc)
428         {
429             push @$bcc_stat, @$cbcc;
430         }
431         elsif (defined $cbcc)
432         {
433             push @$bcc_stat, $cbcc;
434         }
435     }
436     $cbcc = $client_events->{change};
437     if (ref $cbcc)
438     {
439         push @$bcc_chg, @$cbcc;
440     }
441     elsif (defined $cbcc)
442     {
443         push @$bcc_chg, $cbcc;
444     }
445     if ($stage eq 'OK' || $prev_stat eq 'OK')
446     {
447         $cbcc = $client_events->{green};
448         if (ref $cbcc)
449         {
450             push @$bcc_chg, @$cbcc;
451         }
452         elsif (defined $cbcc)
453         {
454             push @$bcc_chg, $cbcc;
455         }
456     }
457 }
458
459
460 my $url = $query->url(-base => 1);
461
462
463 my $stat_type = $stage eq 'OK' ? 'Status' : 'Failed at Stage';
464
465 my $mailto = [@$all_stat];
466 push(@$mailto,@$fail_stat) if $stage ne 'OK';
467
468 my $me = `id -un`; chomp($me);
469
470 my $host = `hostname`; chomp ($host);
471 $host = $default_host unless ($host =~ m/[.]/ || !defined($default_host));
472
473 my $from_addr = "PG Build Farm <$me\@$host>";
474 $from_addr =~ tr /\r\n//d;
475
476 my $msg = new Mail::Send;
477
478
479 $msg->to(@$mailto);
480 $msg->bcc(@$bcc_stat) if (@$bcc_stat);
481 $msg->subject("PGBuildfarm member $animal Branch $branch $stat_type $stage");
482 $msg->set('From',$from_addr);
483 my $fh = $msg->open;
484 print $fh <<EOMAIL; 
485
486
487 The PGBuildfarm member $animal had the following event on branch $branch:
488
489 $stat_type: $stage
490
491 The snapshot timestamp for the build that triggered this notification is: $dbdate
492
493 The specs of this machine are:
494 OS:  $os
495 Arch: $arch
496 Comp: $compiler
497
498 For more information, see $url/cgi-bin/show_history.pl?nm=$animal&br=$branch
499
500 EOMAIL
501
502 $fh->close;
503
504 exit if ($stage eq $prev_stat);
505
506 $mailto = [@$change_stat];
507 push(@$mailto,@$green_stat) if ($stage eq 'OK' || $prev_stat eq 'OK');
508
509 $msg = new Mail::Send;
510
511
512 $msg->to(@$mailto);
513 $msg->bcc(@$bcc_chg) if (@$bcc_chg);
514
515 $stat_type = $prev_stat ne 'OK' ? "changed from $prev_stat failure to $stage" :
516     "changed from OK to $stage";
517 $stat_type = "New member: $stage" if $prev_stat eq 'NEW';
518 $stat_type .= " failure" if $stage ne 'OK';
519
520 $msg->subject("PGBuildfarm member $animal Branch $branch Status $stat_type");
521 $msg->set('From',$from_addr);
522 $fh = $msg->open;
523 print $fh <<EOMAIL;
524
525 The PGBuildfarm member $animal had the following event on branch $branch:
526
527 Status $stat_type
528
529 The snapshot timestamp for the build that triggered this notification is: $dbdate
530
531 The specs of this machine are:
532 OS:  $os
533 Arch: $arch
534 Comp: $compiler
535
536 For more information, see $url/cgi-bin/show_history.pl?nm=$animal&br=$branch
537
538 EOMAIL
539
540 $fh->close;