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