Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 57
0.00% covered (danger)
0.00%
0 / 3
CRAP
0.00% covered (danger)
0.00%
0 / 1
PurgeParserCache
0.00% covered (danger)
0.00%
0 / 57
0.00% covered (danger)
0.00%
0 / 3
72
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 21
0.00% covered (danger)
0.00%
0 / 1
2
 execute
0.00% covered (danger)
0.00%
0 / 25
0.00% covered (danger)
0.00%
0 / 1
30
 showProgressAndWait
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
6
1<?php
2/**
3 * @license GPL-2.0-or-later
4 * @file
5 */
6
7// @codeCoverageIgnoreStart
8require_once __DIR__ . '/Maintenance.php';
9// @codeCoverageIgnoreEnd
10
11use MediaWiki\MainConfigNames;
12use MediaWiki\Maintenance\Maintenance;
13use Wikimedia\Timestamp\ConvertibleTimestamp;
14use Wikimedia\Timestamp\TimestampFormat as TS;
15
16/**
17 * Remove expired objects from the parser cache database.
18 *
19 * By default, this does not need to be run. The default parser cache
20 * backend is CACHE_DB (SqlBagOStuff), and by default that automatically
21 * performs incremental purges in the background of write requests.
22 * Check your wiki's $wgParserCacheType setting to determine if you need to run this script.
23 *
24 * @ingroup Maintenance
25 */
26class PurgeParserCache extends Maintenance {
27
28    /** @var null|string */
29    private $lastProgress;
30
31    /** @var null|float */
32    private $lastTimestamp;
33
34    /** @var int */
35    private $tmpCount = 0;
36    /** @var float */
37    private $usleep = 0;
38
39    public function __construct() {
40        parent::__construct();
41        $this->addDescription( "Remove old objects from the parser cache. " .
42            "This only works when the parser cache is in an SQL database." );
43        $this->addOption( 'expiredate', 'Delete objects expiring before this date.', false, true );
44        $this->addOption(
45            'age',
46            'Delete objects created more than this many seconds ago, assuming ' .
47                '$wgParserCacheExpireTime has remained consistent.',
48            false,
49            true );
50        $this->addOption( 'dry-run', 'Perform a dry run, to verify age and date calculation.' );
51        $this->addOption( 'msleep', 'Milliseconds to sleep between purge chunks of $wgUpdateRowsPerQuery.',
52            false,
53            true );
54        $this->addOption(
55            'tag',
56            'Purge a single server only. This feature is designed for use by large wiki farms where ' .
57                'one has to purge multiple servers concurrently in order to keep up with new writes. ' .
58                'This requires using the SqlBagOStuff "servers" option in $wgObjectCaches.',
59            false,
60            true );
61    }
62
63    public function execute() {
64        $inputDate = $this->getOption( 'expiredate' );
65        $inputAge = $this->getOption( 'age' );
66
67        if ( $inputDate !== null ) {
68            $timestamp = strtotime( $inputDate );
69        } elseif ( $inputAge !== null ) {
70            $expireTime = (int)$this->getConfig()->get( MainConfigNames::ParserCacheExpireTime );
71            $timestamp = time() + $expireTime - intval( $inputAge );
72        } else {
73            $this->fatalError( "Must specify either --expiredate or --age" );
74        }
75        $this->usleep = 1e3 * $this->getOption( 'msleep', 0 );
76        $this->lastTimestamp = microtime( true );
77
78        $humanDate = ConvertibleTimestamp::convert( TS::RFC2822, $timestamp );
79        if ( $this->hasOption( 'dry-run' ) ) {
80            $this->fatalError( "\nDry run mode, would delete objects having an expiry before " . $humanDate . "\n" );
81        }
82
83        $this->output( "Deleting objects expiring before " . $humanDate . "\n" );
84
85        $pc = $this->getServiceContainer()->getParserCache()->getCacheStorage();
86        $success = $pc->deleteObjectsExpiringBefore(
87            $timestamp,
88            $this->showProgressAndWait( ... ),
89            INF,
90            // Note that "0" can be a valid server tag, and must not be discarded or changed to null.
91            $this->getOption( 'tag', null )
92        );
93        if ( !$success ) {
94            $this->fatalError( "\nCannot purge this kind of parser cache." );
95        }
96        $this->showProgressAndWait( 100 );
97        $this->output( "\nDone\n" );
98    }
99
100    private function showProgressAndWait( int $percent ) {
101        // Parser caches involve mostly-unthrottled writes of large blobs. This is sometimes prone
102        // to replication lag. As such, while our purge queries are simple primary key deletes,
103        // we want to avoid adding significant load to the replication stream, by being
104        // proactively graceful with these sleeps between each batch.
105        // The reason we don't explicitly wait for replication is that that would require the script
106        // to be aware of cross-dc replicas, which we prefer not to, and waiting for replication
107        // and confirmation latency might actually be *too* graceful and take so long that the
108        // purge script would not be able to finish within 24 hours for large wiki farms.
109        // (T150124).
110        usleep( $this->usleep );
111        $this->tmpCount++;
112
113        $percentString = sprintf( "%.1f", $percent );
114        if ( $percentString === $this->lastProgress ) {
115            // Only print a line if we've progressed >= 0.1% since the last printed line.
116            // This does not mean every 0.1% step is printed since we only run this callback
117            // once after a deletion batch. How often and how many lines we print depends on the
118            // batch size (SqlBagOStuff::deleteObjectsExpiringBefore, $wgUpdateRowsPerQuery),
119            // and on how many table rows there are.
120            return;
121        }
122        $now = microtime( true );
123        $sec = sprintf( "%.1f", $now - $this->lastTimestamp );
124
125        // Give a sense of how much time is spent in the delete operations vs the sleep time,
126        // by recording the number of iterations we've completed since the last progress update.
127        $this->output( "... {$percentString}% done (+{$this->tmpCount} iterations in {$sec}s)\n" );
128
129        $this->lastProgress = $percentString;
130        $this->tmpCount = 0;
131        $this->lastTimestamp = $now;
132    }
133}
134
135// @codeCoverageIgnoreStart
136$maintClass = PurgeParserCache::class;
137require_once RUN_MAINTENANCE_IF_MAIN;
138// @codeCoverageIgnoreEnd