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