collectstats.pl 17.4 KB
Newer Older
1
#!/usr/bin/perl -w
2 3
# -*- Mode: perl; indent-tabs-mode: nil -*-
#
4 5 6 7 8 9 10 11 12 13
# The contents of this file are subject to the Mozilla Public
# License Version 1.1 (the "License"); you may not use this file
# except in compliance with the License. You may obtain a copy of
# the License at http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS
# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
# implied. See the License for the specific language governing
# rights and limitations under the License.
#
14
# The Original Code is the Bugzilla Bug Tracking System.
15
#
16
# The Initial Developer of the Original Code is Netscape Communications
17 18 19 20
# Corporation. Portions created by Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All
# Rights Reserved.
#
21 22
# Contributor(s): Terry Weissman <terry@mozilla.org>,
#                 Harrison Page <harrison@netscape.com>
23 24 25
#                 Gervase Markham <gerv@gerv.net>
#                 Richard Walters <rwalters@qualcomm.com>
#                 Jean-Sebastien Guay <jean_seb@hybride.com>
26 27 28

# Run me out of cron at midnight to collect Bugzilla statistics.

29

30
use AnyDBM_File;
31
use strict;
32
use IO::Handle;
33
use vars @::legal_product;
34

35
use lib ".";
36
require "globals.pl";
37 38
use Bugzilla::Search;
use Bugzilla::User;
39

40
use Bugzilla;
41
use Bugzilla::Config qw(:DEFAULT $datadir);
42

43 44 45 46 47
# Turn off output buffering (probably needed when displaying output feedback
# in the regenerate mode.)
$| = 1;

# Tidy up after graphing module
48
if (chdir("graphs")) {
49
    unlink <./*.gif>;
50 51 52
    unlink <./*.png>;
    chdir("..");
}
53

54
GetVersionTable();
55

56
Bugzilla->switch_to_shadow_db();
57

58 59 60 61 62 63
# To recreate the daily statistics,  run "collectstats.pl --regenerate" .
my $regenerate = 0;
if ($#ARGV >= 0 && $ARGV[0] eq "--regenerate") {
    $regenerate = 1;
}

64 65 66
my @myproducts;
push( @myproducts, "-All-", @::legal_product );

67
my $tstart = time;
68
foreach (@myproducts) {
69
    my $dir = "$datadir/mining";
70

71
    &check_data_dir ($dir);
72 73 74 75 76 77
    
    if ($regenerate) {
        &regenerate_stats($dir, $_);
    } else {
        &collect_stats($dir, $_);
    }
78
}
79
my $tend = time;
80 81
# Uncomment the following line for performance testing.
#print "Total time taken " . delta_time($tstart, $tend) . "\n";
82

83 84
&calculate_dupes();

85 86
CollectSeriesData();

87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
{
    local $ENV{'GATEWAY_INTERFACE'} = 'cmdline';
    local $ENV{'REQUEST_METHOD'} = 'GET';
    local $ENV{'QUERY_STRING'} = 'ctype=rdf';

    my $perl = $^X;
    trick_taint($perl);

    # Generate a static RDF file containing the default view of the duplicates data.
    open(CGI, "$perl -T duplicates.cgi |")
        || die "can't fork duplicates.cgi: $!";
    open(RDF, ">$datadir/duplicates.tmp")
        || die "can't write to $datadir/duplicates.tmp: $!";
    my $headers_done = 0;
    while (<CGI>) {
        print RDF if $headers_done;
        $headers_done = 1 if $_ eq "\n";
    }
    close CGI;
    close RDF;
107
}
108 109 110
if (-s "$datadir/duplicates.tmp") {
    rename("$datadir/duplicates.rdf", "$datadir/duplicates-old.rdf");
    rename("$datadir/duplicates.tmp", "$datadir/duplicates.rdf");
111 112
}

113 114
sub check_data_dir {
    my $dir = shift;
115

116
    if (! -d $dir) {
117 118
        mkdir $dir, 0755;
        chmod 0755, $dir;
119 120
    }
}
121

122 123 124 125
sub collect_stats {
    my $dir = shift;
    my $product = shift;
    my $when = localtime (time);
126 127 128
    my $product_id = get_product_id($product) unless $product eq '-All-';

    die "Unknown product $product" unless ($product_id or $product eq '-All-');
129

130 131 132 133 134
    # NB: Need to mangle the product for the filename, but use the real
    # product name in the query
    my $file_product = $product;
    $file_product =~ s/\//-/gs;
    my $file = join '/', $dir, $file_product;
135 136 137 138 139
    my $exists = -f $file;

    if (open DATA, ">>$file") {
        push my @row, &today;

140 141
        foreach my $status ('NEW', 'ASSIGNED', 'REOPENED', 'UNCONFIRMED', 'RESOLVED', 'VERIFIED', 'CLOSED') {
            if( $product eq "-All-" ) {
142
                SendSQL("SELECT COUNT(bug_status) FROM bugs WHERE bug_status='$status'");
143
            } else {
144
                SendSQL("SELECT COUNT(bug_status) FROM bugs WHERE bug_status='$status' AND product_id=$product_id");
145 146 147 148 149 150 151
            }

            push @row, FetchOneColumn();
        }

        foreach my $resolution ('FIXED', 'INVALID', 'WONTFIX', 'LATER', 'REMIND', 'DUPLICATE', 'WORKSFORME', 'MOVED') {
            if( $product eq "-All-" ) {
152
                SendSQL("SELECT COUNT(resolution) FROM bugs WHERE resolution='$resolution'");
153
            } else {
154
                SendSQL("SELECT COUNT(resolution) FROM bugs WHERE resolution='$resolution' AND product_id=$product_id");
155 156 157 158 159 160 161
            }

            push @row, FetchOneColumn();
        }

        if (! $exists) {
            print DATA <<FIN;
162
# Bugzilla Daily Bug Stats
163
#
164
# Do not edit me! This file is generated.
165
#
166
# fields: DATE|NEW|ASSIGNED|REOPENED|UNCONFIRMED|RESOLVED|VERIFIED|CLOSED|FIXED|INVALID|WONTFIX|LATER|REMIND|DUPLICATE|WORKSFORME|MOVED
167 168
# Product: $product
# Created: $when
169
FIN
170 171
        }

172 173
        print DATA (join '|', @row) . "\n";
        close DATA;
174
        chmod 0644, $file;
175 176 177 178 179
    } else {
        print "$0: $file, $!";
    }
}

180 181 182 183 184 185 186 187 188
sub calculate_dupes {
    SendSQL("SELECT * FROM duplicates");

    my %dupes;
    my %count;
    my @row;
    my $key;
    my $changed = 1;

189
    my $today = &today_dash;
190 191 192 193

    # Save % count here in a date-named file
    # so we can read it back in to do changed counters
    # First, delete it if it exists, so we don't add to the contents of an old file
194
    if (my @files = <$datadir/duplicates/dupes$today*>) {
195
        map { trick_taint($_) } @files;
196
        unlink @files;
197 198
    }
   
199
    dbmopen(%count, "$datadir/duplicates/dupes$today", 0644) || die "Can't open DBM dupes file: $!";
200 201 202

    # Create a hash with key "a bug number", value "bug which that bug is a
    # direct dupe of" - straight from the duplicates table.
203 204 205 206
    while (@row = FetchSQLData()) {
        my $dupe_of = shift @row;
        my $dupe = shift @row;
        $dupes{$dupe} = $dupe_of;
207 208 209 210 211 212 213
    }

    # Total up the number of bugs which are dupes of a given bug
    # count will then have key = "bug number", 
    # value = "number of immediate dupes of that bug".
    foreach $key (keys(%dupes)) 
    {
214
        my $dupe_of = $dupes{$key};
215

216 217 218
        if (!defined($count{$dupe_of})) {
            $count{$dupe_of} = 0;
        }
219

220
        $count{$dupe_of}++;
221 222 223 224 225 226
    }   

    # Now we collapse the dupe tree by iterating over %count until
    # there is no further change.
    while ($changed == 1)
    {
227 228 229 230 231 232 233 234 235 236 237 238 239 240
        $changed = 0;
        foreach $key (keys(%count)) {
            # if this bug is actually itself a dupe, and has a count...
            if (defined($dupes{$key}) && $count{$key} > 0) {
                # add that count onto the bug it is a dupe of,
                # and zero the count; the check is to avoid
                # loops
                if ($count{$dupes{$key}} != 0) {
                    $count{$dupes{$key}} += $count{$key};
                    $count{$key} = 0;
                    $changed = 1;
                }
            }
        }
241 242 243 244 245
    }

    # Remove the values for which the count is zero
    foreach $key (keys(%count))
    {
246 247 248
        if ($count{$key} == 0) {
            delete $count{$key};
        }
249 250 251 252 253
    }
   
    dbmclose(%count);
}

254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412
# This regenerates all statistics from the database.
sub regenerate_stats {
    my $dir = shift;
    my $product = shift;
    my $when = localtime(time());

    my $tstart = time();

    # NB: Need to mangle the product for the filename, but use the real
    # product name in the query
    my $file_product = $product;
    $file_product =~ s/\//-/gs;
    my $file = join '/', $dir, $file_product;

    my @bugs;

    my $and_product = "";
    my $from_product = "";
                    
    if ($product ne '-All-') {
        $and_product = "AND bugs.product_id = products.id " .
                       "AND products.name = " . SqlQuote($product) . " ";
        $from_product = ", products";                       
    }          
              
    # Determine the start date from the date the first bug in the
    # database was created, and the end date from the current day.
    # If there were no bugs in the search, return early.
    SendSQL("SELECT to_days(creation_ts) AS start, " .
            "to_days(current_date) AS end, " .
            "to_days('1970-01-01') " . 
            "FROM bugs $from_product WHERE to_days(creation_ts) != 'NULL' " .
            $and_product .
            "ORDER BY start LIMIT 1");
    
    my ($start, $end, $base) = FetchSQLData();
    if (!defined $start) {
        return;
    }
 
    if (open DATA, ">$file") {
        DATA->autoflush(1);
        print DATA <<FIN;
# Bugzilla Daily Bug Stats
#
# Do not edit me! This file is generated.
#
# fields: DATE|NEW|ASSIGNED|REOPENED|UNCONFIRMED|RESOLVED|VERIFIED|CLOSED|FIXED|INVALID|WONTFIX|LATER|REMIND|DUPLICATE|WORKSFORME|MOVED
# Product: $product
# Created: $when
FIN
        # For each day, generate a line of statistics.
        my $total_days = $end - $start;
        for (my $day = $start + 1; $day <= $end; $day++) {
            # Some output feedback
            my $percent_done = ($day - $start - 1) * 100 / $total_days;
            printf "\rRegenerating $product \[\%.1f\%\%]", $percent_done;

            # Get a list of bugs that were created the previous day, and
            # add those bugs to the list of bugs for this product.
            SendSQL("SELECT bug_id FROM bugs $from_product " .
                    "WHERE bugs.creation_ts < from_days(" . ($day - 1) . ") " . 
                    "AND bugs.creation_ts >= from_days(" . ($day - 2) . ") " .
                    $and_product .
                    " ORDER BY bug_id");
            
            my @row;        
            while (@row = FetchSQLData()) {
                push @bugs, $row[0];
            }

            # For each bug that existed on that day, determine its status
            # at the beginning of the day.  If there were no status
            # changes on or after that day, the status was the same as it
            # is today, which can be found in the bugs table.  Otherwise,
            # the status was equal to the first "previous value" entry in
            # the bugs_activity table for that bug made on or after that
            # day.
            my %bugcount;
            my @logstates = qw(NEW ASSIGNED REOPENED UNCONFIRMED RESOLVED 
                               VERIFIED CLOSED);
            my @logresolutions = qw(FIXED INVALID WONTFIX LATER REMIND 
                                    DUPLICATE WORKSFORME MOVED);
            foreach (@logstates) {
                $bugcount{$_} = 0;
            }
            
            foreach (@logresolutions) {
                $bugcount{$_} = 0;
            }
            
            for my $bug (@bugs) {
                # First, get information on various bug states.
                SendSQL("SELECT bugs_activity.removed " .
                        "FROM bugs_activity,fielddefs " .
                        "WHERE bugs_activity.fieldid = fielddefs.fieldid " .
                        "AND fielddefs.name = 'bug_status' " .
                        "AND bugs_activity.bug_id = $bug " .
                        "AND bugs_activity.bug_when >= from_days($day) " .
                        "ORDER BY bugs_activity.bug_when LIMIT 1");
                
                my $status;
                if (@row = FetchSQLData()) {
                    $status = $row[0];
                } else {
                    SendSQL("SELECT bug_status FROM bugs WHERE bug_id = $bug");
                    $status = FetchOneColumn();
                }
                
                if (defined $bugcount{$status}) {
                    $bugcount{$status}++;
                }

                # Next, get information on various bug resolutions.
                SendSQL("SELECT bugs_activity.removed " .
                        "FROM bugs_activity,fielddefs " .
                        "WHERE bugs_activity.fieldid = fielddefs.fieldid " .
                        "AND fielddefs.name = 'resolution' " .
                        "AND bugs_activity.bug_id = $bug " .
                        "AND bugs_activity.bug_when >= from_days($day) " .
                        "ORDER BY bugs_activity.bug_when LIMIT 1");
                        
                if (@row = FetchSQLData()) {
                    $status = $row[0];
                } else {
                    SendSQL("SELECT resolution FROM bugs WHERE bug_id = $bug");
                    $status = FetchOneColumn();
                }
                
                if (defined $bugcount{$status}) {
                    $bugcount{$status}++;
                }
            }

            # Generate a line of output containing the date and counts
            # of bugs in each state.
            my $date = sqlday($day, $base);
            print DATA "$date";
            foreach (@logstates) {
                print DATA "|$bugcount{$_}";
            }
            
            foreach (@logresolutions) {
                print DATA "|$bugcount{$_}";
            }
            
            print DATA "\n";
        }
        
        # Finish up output feedback for this product.
        my $tend = time;
        print "\rRegenerating $product \[100.0\%] - " .
            delta_time($tstart, $tend) . "\n";
            
        close DATA;
        chmod 0640, $file;
    }
}

413 414 415 416
sub today {
    my ($dom, $mon, $year) = (localtime(time))[3, 4, 5];
    return sprintf "%04d%02d%02d", 1900 + $year, ++$mon, $dom;
}
417

418 419 420 421 422
sub today_dash {
    my ($dom, $mon, $year) = (localtime(time))[3, 4, 5];
    return sprintf "%04d-%02d-%02d", 1900 + $year, ++$mon, $dom;
}

423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438
sub sqlday {
    my ($day, $base) = @_;
    $day = ($day - $base) * 86400;
    my ($dom, $mon, $year) = (gmtime($day))[3, 4, 5];
    return sprintf "%04d%02d%02d", 1900 + $year, ++$mon, $dom;
}

sub delta_time {
    my $tstart = shift;
    my $tend = shift;
    my $delta = $tend - $tstart;
    my $hours = int($delta/3600);
    my $minutes = int($delta/60) - ($hours * 60);
    my $seconds = $delta - ($minutes * 60) - ($hours * 3600);
    return sprintf("%02d:%02d:%02d" , $hours, $minutes, $seconds);
}
439 440 441 442 443 444 445 446 447 448 449 450 451 452

sub CollectSeriesData {
    # We need some way of randomising the distribution of series, such that
    # all of the series which are to be run every 7 days don't run on the same
    # day. This is because this might put the server under severe load if a
    # particular frequency, such as once a week, is very common. We achieve
    # this by only running queries when:
    # (days_since_epoch + series_id) % frequency = 0. So they'll run every
    # <frequency> days, but the start date depends on the series_id.
    my $days_since_epoch = int(time() / (60 * 60 * 24));
    my $today = today_dash();

    CleanupChartTables() if ($days_since_epoch % 7 == 0);

453 454 455
    # We save a copy of the main $dbh and then switch to the shadow and get
    # that one too. Remember, these may be the same.
    Bugzilla->switch_to_main_db();
456
    my $dbh = Bugzilla->dbh;
457 458 459
    Bugzilla->switch_to_shadow_db();
    my $shadow_dbh = Bugzilla->dbh;
    
460
    my $serieses = $dbh->selectall_hashref("SELECT series_id, query, creator " .
461 462 463 464 465 466 467 468 469 470
                      "FROM series " .
                      "WHERE frequency != 0 AND " . 
                      "($days_since_epoch + series_id) % frequency = 0",
                      "series_id");

    # We prepare the insertion into the data table, for efficiency.
    my $sth = $dbh->prepare("INSERT INTO series_data " .
                            "(series_id, date, value) " .
                            "VALUES (?, " . $dbh->quote($today) . ", ?)");

471 472 473 474 475 476
    # We delete from the table beforehand, to avoid SQL errors if people run
    # collectstats.pl twice on the same day.
    my $deletesth = $dbh->prepare("DELETE FROM series_data 
                                   WHERE series_id = ? AND date = " .
                                   $dbh->quote($today));
                                     
477 478 479
    foreach my $series_id (keys %$serieses) {
        # We set up the user for Search.pm's permission checking - each series
        # runs with the permissions of its creator.
480
        my $user = new Bugzilla::User($serieses->{$series_id}->{'creator'});
481 482 483

        my $cgi = new Bugzilla::CGI($serieses->{$series_id}->{'query'});
        my $search = new Bugzilla::Search('params' => $cgi,
484 485
                                          'fields' => ["bugs.bug_id"],
                                          'user'   => $user);
486 487 488 489
        my $sql = $search->getSQL();
        
        # We need to count the returned rows. Without subselects, we can't
        # do this directly in the SQL for all queries. So we do it by hand.
490
        my $data = $shadow_dbh->selectall_arrayref($sql);
491 492 493
        
        my $count = scalar(@$data) || 0;

494
        $deletesth->execute($series_id);
495 496 497 498 499
        $sth->execute($series_id, $count);
    }
}

sub CleanupChartTables {
500
    Bugzilla->switch_to_main_db();
501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519
    my $dbh = Bugzilla->dbh;

    $dbh->do("LOCK TABLES series WRITE, user_series_map AS usm READ");

    # Find all those that no-one subscribes to
    my $series_data = $dbh->selectall_arrayref("SELECT series.series_id " .
                              "FROM series LEFT JOIN user_series_map AS usm " .
                              "ON series.series_id = usm.series_id " .
                              "WHERE usm.series_id IS NULL");

    my $series_ids = join(",", map({ $_->[0] } @$series_data));

    # Stop collecting data on all series which no-one is subscribed to.
    if ($series_ids) {
        $dbh->do("UPDATE series SET frequency = 0 " . 
                 "WHERE series_id IN($series_ids)");
    }
   
    $dbh->do("UNLOCK TABLES");
520
    Bugzilla->switch_to_shadow_db();
521
}