You need to sign in or sign up before continuing.
collectstats.pl 18 KB
Newer Older
1
#!/usr/bin/perl -w
2 3 4
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
5
#
6 7
# This Source Code Form is "Incompatible With Secondary Licenses", as
# defined by the Mozilla Public License, v. 2.0.
8 9

use strict;
10 11
use lib qw(. lib);

12 13
use Getopt::Long qw(:config bundling);
use Pod::Usage;
14
use List::Util qw(first);
15
use Cwd;
16

17
use Bugzilla;
18
use Bugzilla::Constants;
19
use Bugzilla::Error;
20
use Bugzilla::Util;
21 22 23
use Bugzilla::Search;
use Bugzilla::User;
use Bugzilla::Product;
24
use Bugzilla::Field;
25
use Bugzilla::Install::Filesystem qw(fix_dir_permissions);
26

27 28 29 30 31 32
my %switch;
GetOptions(\%switch, 'help|h', 'regenerate');

# Print the help message if that switch was selected.
pod2usage({-verbose => 1, -exitval => 1}) if $switch{'help'};

33
# Turn off output buffering (probably needed when displaying output feedback
34
# in the regenerate mode).
35 36
$| = 1;

37 38 39
my $datadir = bz_locations()->{'datadir'};
my $graphsdir = bz_locations()->{'graphsdir'};

40
# Tidy up after graphing module
41
my $cwd = Cwd::getcwd();
42
if (chdir($graphsdir)) {
43
    unlink <./*.gif>;
44
    unlink <./*.png>;
45 46
    # chdir("..") doesn't work if graphs is a symlink, see bug 429378
    chdir($cwd);
47
}
48

49
my $dbh = Bugzilla->switch_to_shadow_db();
50

51 52
# 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
53
# may have existed in the past, or have been renamed. We want them all.
54 55 56 57 58
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
59 60
                                FROM bugs_activity
                          INNER JOIN fielddefs
61
                                  ON fielddefs.id = bugs_activity.fieldid
62 63
                           LEFT JOIN $field
                                  ON $field.value = bugs_activity.added
64
                               WHERE fielddefs.name = ?
65
                                 AND $field.id IS NULL
66 67 68 69 70 71

                               UNION

                              SELECT bugs_activity.removed
                                FROM bugs_activity
                          INNER JOIN fielddefs
72
                                  ON fielddefs.id = bugs_activity.fieldid
73 74
                           LEFT JOIN $field
                                  ON $field.value = bugs_activity.removed
75
                               WHERE fielddefs.name = ?
76 77
                                 AND $field.id IS NULL",
                               undef, ($field, $field));
78

79 80 81 82 83 84
    push(@$values, @$old_values);
    $fields->{$field} = $values;
}

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

88 89 90 91
# --regenerate was taking an enormous amount of time to query everything
# per bug, per day. Instead, we now just get all the data out of the DB
# at once and stuff it into some data structures.
my (%bug_status, %bug_resolution, %removed);
92
if ($switch{'regenerate'}) {
93 94 95 96 97 98 99 100
    %bug_resolution = @{ $dbh->selectcol_arrayref(
        'SELECT bug_id, resolution FROM bugs', {Columns=>[1,2]}) };
    %bug_status = @{ $dbh->selectcol_arrayref(
        'SELECT bug_id, bug_status FROM bugs', {Columns=>[1,2]}) };

    my $removed_sth = $dbh->prepare(
        q{SELECT bugs_activity.bug_id, bugs_activity.removed,}
        . $dbh->sql_to_days('bugs_activity.bug_when')
101
       . q{ FROM bugs_activity
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
           WHERE bugs_activity.fieldid = ?
        ORDER BY bugs_activity.bug_when});

    %removed = (bug_status => {}, resolution => {});
    foreach my $field (qw(bug_status resolution)) {
        my $field_id = Bugzilla::Field->check($field)->id;
        my $rows = $dbh->selectall_arrayref($removed_sth, undef, $field_id);
        my $hash = $removed{$field};
        foreach my $row (@$rows) {
            my ($bug_id, $removed, $when) = @$row;
            $hash->{$bug_id} ||= [];
            push(@{ $hash->{$bug_id} }, { when    => int($when),
                                          removed => $removed });
        }
    }
}

119
my $tstart = time;
120 121 122 123

my @myproducts = Bugzilla::Product->get_all;
unshift(@myproducts, "-All-");

124 125 126 127 128
my $dir = "$datadir/mining";
if (!-d $dir) {
    mkdir $dir or die "mkdir $dir failed: $!";
    fix_dir_permissions($dir);
}
129

130
foreach (@myproducts) {
131
    if ($switch{'regenerate'}) {
132
        regenerate_stats($dir, $_, \%bug_resolution, \%bug_status, \%removed);
133 134 135
    } else {
        &collect_stats($dir, $_);
    }
136
}
137 138 139
# Fix permissions for all files in mining/.
fix_dir_permissions($dir);

140
my $tend = time;
141
# Uncomment the following line for performance testing.
142
#say "Total time taken " . delta_time($tstart, $tend);
143

144 145
CollectSeriesData();

146 147 148 149
sub collect_stats {
    my $dir = shift;
    my $product = shift;
    my $when = localtime (time);
150
    my $dbh = Bugzilla->dbh;
151
    my $product_id;
152 153 154 155

    if (ref $product) {
        $product_id = $product->id;
        $product = $product->name;
156
    }
157

158 159 160 161 162
    # 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;
163 164
    my $exists = -f $file;

165 166 167 168 169 170 171 172 173 174 175 176 177 178
    # 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});
    }

179 180 181 182
    if (Bugzilla->params->{'utf8'}) {
        binmode DATA, ':utf8';
    }

183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
    # 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);
    }
209

210 211 212
    if (!$exists || scalar(@data)) {
        my $fields = join('|', ('DATE', @statuses, @resolutions));
        print DATA <<FIN;
213
# Bugzilla Daily Bug Stats
214
#
215
# Do not edit me! This file is generated.
216
#
217
# fields: $fields
218 219
# Product: $product
# Created: $when
220
FIN
221
    }
222

223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
    # 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;
}

sub get_old_data {
    my $file = shift;

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

239 240 241 242
    if (Bugzilla->params->{'utf8'}) {
        binmode DATA, ':utf8';
    }

243 244 245 246 247 248 249 250 251 252 253 254 255 256
    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)) {
257 258 259 260 261
                my $identical = 1;
                for (0 .. $#columns) {
                    $identical = 0 if ($columns[$_] ne $new_cols[$_]);
                }
                last if $identical;
262 263 264 265 266 267 268 269 270 271 272 273
            }
        }
        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);
274
    }
275 276
    close(DATA);
    return @data;
277 278
}

279 280
# This regenerates all statistics from the database.
sub regenerate_stats {
281
    my ($dir, $product, $bug_resolution, $bug_status, $removed) = @_;
282

283 284
    my $dbh = Bugzilla->dbh;
    my $when = localtime(time());
285 286 287 288
    my $tstart = time();

    # NB: Need to mangle the product for the filename, but use the real
    # product name in the query
289 290 291
    if (ref $product) {
        $product = $product->name;
    }
292 293 294 295 296 297
    my $file_product = $product;
    $file_product =~ s/\//-/gs;
    my $file = join '/', $dir, $file_product;

    my $and_product = "";
    my $from_product = "";
298 299

    my @values = ();
300
    if ($product ne '-All-') {
301 302
        $and_product = q{ AND products.name = ?};
        $from_product = q{ INNER JOIN products 
303 304 305 306
                          ON bugs.product_id = products.id};
        push (@values, $product);
    }

307 308 309
    # 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.
310
    my $query = q{SELECT } .
311 312
                $dbh->sql_to_days('creation_ts') . q{ AS start_day, } .
                $dbh->sql_to_days('current_date') . q{ AS end_day, } . 
313 314 315 316
                $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 
317
                ORDER BY start_day } . $dbh->sql_limit(1);
318 319
    my ($start, $end, $base) = $dbh->selectrow_array($query, undef, @values);

320 321 322
    if (!defined $start) {
        return;
    }
323

324
    if (open DATA, ">", $file) {
325
        my $fields = join('|', ('DATE', @statuses, @resolutions));
326 327 328 329 330
        print DATA <<FIN;
# Bugzilla Daily Bug Stats
#
# Do not edit me! This file is generated.
#
331
# fields: $fields
332 333 334 335 336
# Product: $product
# Created: $when
FIN
        # For each day, generate a line of statistics.
        my $total_days = $end - $start;
337
        my @bugs;
338 339 340 341 342 343 344
        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.
345 346 347 348 349 350 351 352 353 354
            $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);
355 356

            my %bugcount;
357 358
            foreach (@statuses) { $bugcount{$_} = 0; }
            foreach (@resolutions) { $bugcount{$_} = 0; }
359
            # Get information on bug states and resolutions.
360
            for my $bug (@bugs) {
361 362 363
                my $status = _get_value(
                    $removed->{'bug_status'}->{$bug},
                    $bug_status,  $day, $bug);
364

365 366 367
                if (defined $bugcount{$status}) {
                    $bugcount{$status}++;
                }
368 369 370 371 372

                my $resolution = _get_value(
                    $removed->{'resolution'}->{$bug},
                    $bug_resolution, $day, $bug);

373 374
                if (defined $bugcount{$resolution}) {
                    $bugcount{$resolution}++;
375 376 377 378 379 380 381
                }
            }

            # Generate a line of output containing the date and counts
            # of bugs in each state.
            my $date = sqlday($day, $base);
            print DATA "$date";
382 383
            foreach (@statuses) { print DATA "|$bugcount{$_}"; }
            foreach (@resolutions) { print DATA "|$bugcount{$_}"; }
384 385
            print DATA "\n";
        }
386

387 388
        # Finish up output feedback for this product.
        my $tend = time;
389 390
        say "\rRegenerating $product \[100.0\%] - " . delta_time($tstart, $tend);

391 392 393 394
        close DATA;
    }
}

395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412
# A helper for --regenerate.
# For each bug that exists on a day, we determine its status/resolution
# at the beginning of the day.  If there were no status/resolution
# changes on or after that day, the status was the same as it
# is today (the "current" value).  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.
sub _get_value {
    my ($removed, $current, $day, $bug) = @_;

    # Get the first change that's on or after this day.
    my $item = first { $_->{when} >= $day } @{ $removed || [] };

    # If there's no change on or after this day, then we just return the
    # current value.
    return $item ? $item->{removed} : $current->{$bug};
}

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

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));
449
    my $today = today_dash();
450

451 452
    # 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.
453 454
    my $dbh = Bugzilla->switch_to_main_db();
    my $shadow_dbh = Bugzilla->switch_to_shadow_db();
455
    
456
    my $serieses = $dbh->selectall_hashref("SELECT series_id, query, creator " .
457 458
                      "FROM series " .
                      "WHERE frequency != 0 AND " . 
459
                      "MOD(($days_since_epoch + series_id), frequency) = 0",
460 461 462 463
                      "series_id");

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

467 468 469
    # 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 
470
                                   WHERE series_id = ? AND series_date = " .
471 472
                                   $dbh->quote($today));
                                     
473 474 475
    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.
476
        my $user = new Bugzilla::User($serieses->{$series_id}->{'creator'});
477
        my $cgi = new Bugzilla::CGI($serieses->{$series_id}->{'query'});
478
        my $data;
479 480 481 482

        # Do not die if Search->new() detects invalid data, such as an obsolete
        # login name or a renamed product or component, etc.
        eval {
483
            my $search = new Bugzilla::Search('params' => scalar $cgi->Vars,
484
                                              'fields' => ["bug_id"],
485
                                              'allow_unlimited' => 1,
486
                                              'user'   => $user);
487
            $data = $search->data;
488
        };
489

490 491 492 493
        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;
494

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

501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536
__END__

=head1 NAME

collectstats.pl - Collect data about Bugzilla bugs.

=head1 SYNOPSIS

 ./collectstats.pl [--regenerate] [--help]

Collects data about bugs to be used in Old and New Charts.

=head1 OPTIONS

=over

=item B<--help>

Print this help page.

=item B<--regenerate>

Recreate all the data about bugs, from day 1. This option is only relevant
for Old Charts, and has no effect for New Charts.
This option will overwrite all existing collected data and can take a huge
amount of time. You normally don't need to use this option (do not use it
in a cron job).

=back

=head1 DESCRIPTION

This script collects data about all bugs for Old Charts, triaged by product
and by bug status and resolution. It also collects data for New Charts, based
on existing series. For New Charts, data is only collected once a series is
defined; this script cannot recreate data prior to this date.