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