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