collectstats.pl 20.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
#                 Frédéric Buclin <LpSolit@gmail.com>
27 28

# Run me out of cron at midnight to collect Bugzilla statistics.
29 30 31
#
# To run new charts for a specific date, pass it in on the command line in
# ISO (2004-08-14) format.
32

33
use AnyDBM_File;
34
use strict;
35
use IO::Handle;
36

37
use lib qw(. lib);
38

39
use Bugzilla;
40
use Bugzilla::Constants;
41
use Bugzilla::Error;
42
use Bugzilla::Util;
43 44 45
use Bugzilla::Search;
use Bugzilla::User;
use Bugzilla::Product;
46
use Bugzilla::Field;
47

48
# Turn off output buffering (probably needed when displaying output feedback
49
# in the regenerate mode).
50 51 52
$| = 1;

# Tidy up after graphing module
53
if (chdir("graphs")) {
54
    unlink <./*.gif>;
55 56 57
    unlink <./*.png>;
    chdir("..");
}
58

59 60 61
# This is a pure command line script.
Bugzilla->usage_mode(USAGE_MODE_CMDLINE);

62
my $dbh = Bugzilla->switch_to_shadow_db();
63

64 65 66
# To recreate the daily statistics,  run "collectstats.pl --regenerate" .
my $regenerate = 0;
if ($#ARGV >= 0 && $ARGV[0] eq "--regenerate") {
67
    shift(@ARGV);
68 69 70
    $regenerate = 1;
}

71 72
my $datadir = bz_locations()->{'datadir'};

73
my @myproducts = map {$_->name} Bugzilla::Product->get_all;
74
unshift(@myproducts, "-All-");
75

76 77
# As we can now customize statuses and resolutions, looking at the current list
# of legal values only is not enough as some now removed statuses and resolutions
78
# may have existed in the past, or have been renamed. We want them all.
79 80 81 82 83
my $fields = {};
foreach my $field ('bug_status', 'resolution') {
    my $values = get_legal_field_values($field);
    my $old_values = $dbh->selectcol_arrayref(
                             "SELECT bugs_activity.added
84 85
                                FROM bugs_activity
                          INNER JOIN fielddefs
86
                                  ON fielddefs.id = bugs_activity.fieldid
87 88
                           LEFT JOIN $field
                                  ON $field.value = bugs_activity.added
89
                               WHERE fielddefs.name = ?
90
                                 AND $field.id IS NULL
91 92 93 94 95 96

                               UNION

                              SELECT bugs_activity.removed
                                FROM bugs_activity
                          INNER JOIN fielddefs
97
                                  ON fielddefs.id = bugs_activity.fieldid
98 99
                           LEFT JOIN $field
                                  ON $field.value = bugs_activity.removed
100
                               WHERE fielddefs.name = ?
101 102
                                 AND $field.id IS NULL",
                               undef, ($field, $field));
103

104 105 106 107 108 109
    push(@$values, @$old_values);
    $fields->{$field} = $values;
}

my @statuses = @{$fields->{'bug_status'}};
my @resolutions = @{$fields->{'resolution'}};
110 111 112
# Exclude "" from the resolution list.
@resolutions = grep {$_} @resolutions;

113
my $tstart = time;
114
foreach (@myproducts) {
115
    my $dir = "$datadir/mining";
116

117
    &check_data_dir ($dir);
118

119 120 121 122 123
    if ($regenerate) {
        &regenerate_stats($dir, $_);
    } else {
        &collect_stats($dir, $_);
    }
124
}
125
my $tend = time;
126 127
# Uncomment the following line for performance testing.
#print "Total time taken " . delta_time($tstart, $tend) . "\n";
128

129 130
&calculate_dupes();

131 132
CollectSeriesData();

133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
{
    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;
149
        $headers_done = 1 if $_ eq "\r\n";
150 151 152
    }
    close CGI;
    close RDF;
153
}
154 155 156
if (-s "$datadir/duplicates.tmp") {
    rename("$datadir/duplicates.rdf", "$datadir/duplicates-old.rdf");
    rename("$datadir/duplicates.tmp", "$datadir/duplicates.rdf");
157 158
}

159 160
sub check_data_dir {
    my $dir = shift;
161

162
    if (! -d $dir) {
163 164
        mkdir $dir, 0755;
        chmod 0755, $dir;
165 166
    }
}
167

168 169 170 171
sub collect_stats {
    my $dir = shift;
    my $product = shift;
    my $when = localtime (time);
172
    my $dbh = Bugzilla->dbh;
173

174 175 176 177 178
    my $product_id;
    if ($product ne '-All-') {
        my $prod = Bugzilla::Product::check_product($product);
        $product_id = $prod->id;
    }
179

180 181 182 183 184
    # 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;
185 186
    my $exists = -f $file;

187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
    # if the file exists, get the old status and resolution list for that product.
    my @data;
    @data = get_old_data($file) if $exists;

    # If @data is not empty, then we have to recreate the data file.
    if (scalar(@data)) {
        open(DATA, '>', $file)
          || ThrowCodeError('chart_file_open_fail', {'filename' => $file});
    }
    else {
        open(DATA, '>>', $file)
          || ThrowCodeError('chart_file_open_fail', {'filename' => $file});
    }

    # Now collect current data.
    my @row = (today());
    my $status_sql = q{SELECT COUNT(*) FROM bugs WHERE bug_status = ?};
    my $reso_sql   = q{SELECT COUNT(*) FROM bugs WHERE resolution = ?};

    if ($product ne '-All-') {
        $status_sql .= q{ AND product_id = ?};
        $reso_sql   .= q{ AND product_id = ?};
    }

    my $sth_status = $dbh->prepare($status_sql);
    my $sth_reso   = $dbh->prepare($reso_sql);

    my @values ;
    foreach my $status (@statuses) {
        @values = ($status);
        push (@values, $product_id) if ($product ne '-All-');
        my $count = $dbh->selectrow_array($sth_status, undef, @values);
        push(@row, $count);
    }
    foreach my $resolution (@resolutions) {
        @values = ($resolution);
        push (@values, $product_id) if ($product ne '-All-');
        my $count = $dbh->selectrow_array($sth_reso, undef, @values);
        push(@row, $count);
    }
227

228 229 230
    if (!$exists || scalar(@data)) {
        my $fields = join('|', ('DATE', @statuses, @resolutions));
        print DATA <<FIN;
231
# Bugzilla Daily Bug Stats
232
#
233
# Do not edit me! This file is generated.
234
#
235
# fields: $fields
236 237
# Product: $product
# Created: $when
238
FIN
239
    }
240

241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
    # Add existing data, if needed. Note that no count is not treated
    # the same way as a count with 0 bug.
    foreach my $data (@data) {
        print DATA join('|', map {defined $data->{$_} ? $data->{$_} : ''}
                                 ('DATE', @statuses, @resolutions)) . "\n";
    }
    print DATA (join '|', @row) . "\n";
    close DATA;
    chmod 0644, $file;
}

sub get_old_data {
    my $file = shift;

    open(DATA, '<', $file)
      || ThrowCodeError('chart_file_open_fail', {'filename' => $file});

    my @data;
    my @columns;
    my $recreate = 0;
    while (<DATA>) {
        chomp;
        next unless $_;
        if (/^# fields?:\s*(.+)\s*$/) {
            @columns = split(/\|/, $1);
            # Compare this list with @statuses and @resolutions.
            # If they are identical, then we can safely append new data
            # to the end of the file; else we have to recreate it.
            $recreate = 1;
            my @new_cols = ($columns[0], @statuses, @resolutions);
            if (scalar(@columns) == scalar(@new_cols)) {
272 273 274 275 276
                my $identical = 1;
                for (0 .. $#columns) {
                    $identical = 0 if ($columns[$_] ne $new_cols[$_]);
                }
                last if $identical;
277 278 279 280 281 282 283 284 285 286 287 288
            }
        }
        next unless $recreate;
        next if (/^#/); # Ignore comments.
        # If we have to recreate the file, we have to load all existing
        # data first.
        my @line = split /\|/;
        my %data;
        foreach my $column (@columns) {
            $data{$column} = shift @line;
        }
        push(@data, \%data);
289
    }
290 291
    close(DATA);
    return @data;
292 293
}

294
sub calculate_dupes {
295 296
    my $dbh = Bugzilla->dbh;
    my $rows = $dbh->selectall_arrayref("SELECT dupe_of, dupe FROM duplicates");
297 298 299 300 301 302

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

303
    my $today = &today_dash;
304 305 306 307

    # 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
308 309
    my $datadir = bz_locations()->{'datadir'};

310
    if (my @files = <$datadir/duplicates/dupes$today*>) {
311
        map { trick_taint($_) } @files;
312
        unlink @files;
313 314
    }
   
315
    dbmopen(%count, "$datadir/duplicates/dupes$today", 0644) || die "Can't open DBM dupes file: $!";
316 317 318

    # Create a hash with key "a bug number", value "bug which that bug is a
    # direct dupe of" - straight from the duplicates table.
319 320
    foreach my $row (@$rows) {
        my ($dupe_of, $dupe) = @$row;
321
        $dupes{$dupe} = $dupe_of;
322 323 324 325 326 327 328
    }

    # 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)) 
    {
329
        my $dupe_of = $dupes{$key};
330

331 332 333
        if (!defined($count{$dupe_of})) {
            $count{$dupe_of} = 0;
        }
334

335
        $count{$dupe_of}++;
336
    }
337 338 339 340 341

    # Now we collapse the dupe tree by iterating over %count until
    # there is no further change.
    while ($changed == 1)
    {
342 343 344 345 346 347 348 349 350 351 352 353 354 355
        $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;
                }
            }
        }
356 357 358 359 360
    }

    # Remove the values for which the count is zero
    foreach $key (keys(%count))
    {
361 362 363
        if ($count{$key} == 0) {
            delete $count{$key};
        }
364 365 366 367 368
    }
   
    dbmclose(%count);
}

369 370 371 372 373
# This regenerates all statistics from the database.
sub regenerate_stats {
    my $dir = shift;
    my $product = shift;

374 375
    my $dbh = Bugzilla->dbh;
    my $when = localtime(time());
376 377 378 379 380 381 382 383 384 385 386 387
    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 = "";
388 389

    my @values = ();
390
    if ($product ne '-All-') {
391 392
        $and_product = q{ AND products.name = ?};
        $from_product = q{ INNER JOIN products 
393 394 395 396
                          ON bugs.product_id = products.id};
        push (@values, $product);
    }

397 398 399
    # 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.
400 401 402 403 404 405 406 407 408 409
    my $query = q{SELECT } .
                $dbh->sql_to_days('creation_ts') . q{ AS start, } . 
                $dbh->sql_to_days('current_date') . q{ AS end, } . 
                $dbh->sql_to_days("'1970-01-01'") . 
                 qq{ FROM bugs $from_product 
                   WHERE } . $dbh->sql_to_days('creation_ts') . 
                         qq{ IS NOT NULL $and_product 
                ORDER BY start } . $dbh->sql_limit(1);
    my ($start, $end, $base) = $dbh->selectrow_array($query, undef, @values);

410 411 412
    if (!defined $start) {
        return;
    }
413

414 415
    if (open DATA, ">$file") {
        DATA->autoflush(1);
416
        my $fields = join('|', ('DATE', @statuses, @resolutions));
417 418 419 420 421
        print DATA <<FIN;
# Bugzilla Daily Bug Stats
#
# Do not edit me! This file is generated.
#
422
# fields: $fields
423 424 425 426 427 428 429 430 431 432 433 434
# 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.
435 436 437 438 439 440 441 442 443 444 445
            $query = qq{SELECT bug_id 
                          FROM bugs $from_product 
                         WHERE bugs.creation_ts < } . 
                         $dbh->sql_from_days($day - 1) . 
                         q{ AND bugs.creation_ts >= } . 
                         $dbh->sql_from_days($day - 2) . 
                        $and_product . q{ ORDER BY bug_id};

            my $bug_ids = $dbh->selectcol_arrayref($query, undef, @values);

            push(@bugs, @$bug_ids);
446 447 448 449 450 451 452 453 454

            # 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;
455 456
            foreach (@statuses) { $bugcount{$_} = 0; }
            foreach (@resolutions) { $bugcount{$_} = 0; }
457 458 459 460
            # Get information on bug states and resolutions.
            $query = qq{SELECT bugs_activity.removed 
                          FROM bugs_activity 
                    INNER JOIN fielddefs 
461
                            ON bugs_activity.fieldid = fielddefs.id 
462 463 464 465 466 467 468 469 470 471 472
                         WHERE fielddefs.name = ? 
                           AND bugs_activity.bug_id = ? 
                           AND bugs_activity.bug_when >= } . 
                           $dbh->sql_from_days($day) . 
                    " ORDER BY bugs_activity.bug_when " . 
                          $dbh->sql_limit(1);

            my $sth_bug = $dbh->prepare($query);
            my $sth_status = $dbh->prepare(q{SELECT bug_status 
                                               FROM bugs 
                                              WHERE bug_id = ?});
473
            
474 475 476 477
            my $sth_reso = $dbh->prepare(q{SELECT resolution 
                                             FROM bugs 
                                            WHERE bug_id = ?});

478
            for my $bug (@bugs) {
479 480 481 482
                my $status = $dbh->selectrow_array($sth_bug, undef, 
                                                       'bug_status', $bug);
                unless ($status) {
                    $status = $dbh->selectrow_array($sth_status, undef, $bug);
483
                }
484

485 486 487
                if (defined $bugcount{$status}) {
                    $bugcount{$status}++;
                }
488 489 490 491
                my $resolution = $dbh->selectrow_array($sth_bug, undef, 
                                                         'resolution', $bug);
                unless ($resolution) {
                    $resolution = $dbh->selectrow_array($sth_reso, undef, $bug);
492 493
                }
                
494 495
                if (defined $bugcount{$resolution}) {
                    $bugcount{$resolution}++;
496 497 498 499 500 501 502
                }
            }

            # Generate a line of output containing the date and counts
            # of bugs in each state.
            my $date = sqlday($day, $base);
            print DATA "$date";
503 504
            foreach (@statuses) { print DATA "|$bugcount{$_}"; }
            foreach (@resolutions) { print DATA "|$bugcount{$_}"; }
505 506 507 508 509 510 511 512 513 514 515 516 517
            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;
    }
}

518 519 520 521
sub today {
    my ($dom, $mon, $year) = (localtime(time))[3, 4, 5];
    return sprintf "%04d%02d%02d", 1900 + $year, ++$mon, $dom;
}
522

523 524 525 526 527
sub today_dash {
    my ($dom, $mon, $year) = (localtime(time))[3, 4, 5];
    return sprintf "%04d-%02d-%02d", 1900 + $year, ++$mon, $dom;
}

528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543
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);
}
544 545 546 547 548 549 550 551 552 553

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));
554
    my $today = $ARGV[0] || today_dash();
555

556 557
    # 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.
558 559
    my $dbh = Bugzilla->switch_to_main_db();
    my $shadow_dbh = Bugzilla->switch_to_shadow_db();
560
    
561
    my $serieses = $dbh->selectall_hashref("SELECT series_id, query, creator " .
562 563 564 565 566 567 568
                      "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 " .
569
                            "(series_id, series_date, series_value) " .
570 571
                            "VALUES (?, " . $dbh->quote($today) . ", ?)");

572 573 574
    # 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 
575
                                   WHERE series_id = ? AND series_date = " .
576 577
                                   $dbh->quote($today));
                                     
578 579 580
    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.
581
        my $user = new Bugzilla::User($serieses->{$series_id}->{'creator'});
582
        my $cgi = new Bugzilla::CGI($serieses->{$series_id}->{'query'});
583
        my $data;
584 585 586 587 588 589 590 591

        # Do not die if Search->new() detects invalid data, such as an obsolete
        # login name or a renamed product or component, etc.
        eval {
            my $search = new Bugzilla::Search('params' => $cgi,
                                              'fields' => ["bugs.bug_id"],
                                              'user'   => $user);
            my $sql = $search->getSQL();
592 593
            $data = $shadow_dbh->selectall_arrayref($sql);
        };
594

595 596 597 598
        if (!$@) {
            # 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.
            my $count = scalar(@$data) || 0;
599

600 601 602
            $deletesth->execute($series_id);
            $sth->execute($series_id, $count);
        }
603 604 605
    }
}