3 * Compress the text of a wiki.
8 * php compressOld.php [options...]
11 * php compressOld.php <database> [options...]
14 * -t <type> set compression type to either:
15 * gzip: compress revisions independently
16 * concat: concatenate revisions and compress in chunks (default)
17 * -c <chunk-size> maximum number of revisions in a concat chunk
18 * -b <begin-date> earliest date to check for uncompressed revisions
19 * -e <end-date> latest revision date to compress
20 * -s <startid> the id to start from (referring to the text table for
21 * type gzip, and to the page table for type concat)
22 * -n <endid> the page_id to stop at (only when using concat compression type)
23 * --extdb <cluster> store specified revisions in an external cluster (untested)
25 * This program is free software; you can redistribute it and/or modify
26 * it under the terms of the GNU General Public License as published by
27 * the Free Software Foundation; either version 2 of the License, or
28 * (at your option) any later version.
30 * This program is distributed in the hope that it will be useful,
31 * but WITHOUT ANY WARRANTY; without even the implied warranty of
32 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
33 * GNU General Public License for more details.
35 * You should have received a copy of the GNU General Public License along
36 * with this program; if not, write to the Free Software Foundation, Inc.,
37 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
38 * http://www.gnu.org/copyleft/gpl.html
41 * @ingroup Maintenance ExternalStorage
43 use MediaWiki\Revision\SlotRecord
;
44 use MediaWiki\Title\Title
;
45 use Wikimedia\Rdbms\IExpression
;
46 use Wikimedia\Rdbms\LikeValue
;
48 // @codeCoverageIgnoreStart
49 require_once __DIR__
. '/../Maintenance.php';
50 // @codeCoverageIgnoreEnd
53 * Maintenance script that compress the text of a wiki.
55 * @ingroup Maintenance ExternalStorage
57 class CompressOld
extends Maintenance
{
58 public function __construct() {
59 parent
::__construct();
60 $this->addDescription( 'Compress the text of a wiki' );
61 $this->addOption( 'type', 'Set compression type to either: gzip|concat', false, true, 't' );
64 'Maximum number of revisions in a concat chunk',
71 'Earliest date to check for uncompressed revisions',
76 $this->addOption( 'end-date', 'Latest revision date to compress', false, true, 'e' );
79 'The id to start from (gzip -> text table, concat -> page table)',
86 'Store specified revisions in an external cluster (untested)',
92 'The page_id to stop at (only when using concat compression type)',
99 public function execute() {
101 if ( !function_exists( "gzdeflate" ) ) {
102 $this->fatalError( "You must enable zlib support in PHP to compress old revisions!\n" .
103 "Please see https://www.php.net/manual/en/ref.zlib.php\n" );
106 $type = $this->getOption( 'type', 'concat' );
107 $chunkSize = $this->getOption( 'chunksize', 20 );
108 $startId = $this->getOption( 'startid', 0 );
109 $beginDate = $this->getOption( 'begin-date', '' );
110 $endDate = $this->getOption( 'end-date', '' );
111 $extDB = $this->getOption( 'extdb', '' );
112 $endId = $this->getOption( 'endid', false );
114 if ( $type != 'concat' && $type != 'gzip' ) {
115 $this->error( "Type \"{$type}\" not supported" );
118 if ( $extDB != '' ) {
119 $this->output( "Compressing database {$wgDBname} to external cluster {$extDB}\n"
120 . str_repeat( '-', 76 ) . "\n\n" );
122 $this->output( "Compressing database {$wgDBname}\n"
123 . str_repeat( '-', 76 ) . "\n\n" );
127 if ( $type == 'concat' ) {
128 $success = $this->compressWithConcat( $startId, $chunkSize, $beginDate,
129 $endDate, $extDB, $endId );
131 $this->compressOldPages( $startId, $extDB );
135 $this->output( "Done.\n" );
140 * Fetch the text row-by-row to 'compressPage' function for compression.
143 * @param string $extdb
145 private function compressOldPages( $start = 0, $extdb = '' ) {
147 $this->output( "Starting from old_id $start...\n" );
148 $dbw = $this->getPrimaryDB();
150 $res = $dbw->newSelectQueryBuilder()
151 ->select( [ 'old_id', 'old_flags', 'old_text' ] )
154 ->where( "old_id>=$start" )
155 ->orderBy( 'old_id' )
156 ->limit( $chunksize )
157 ->caller( __METHOD__
)->fetchResultSet();
159 if ( $res->numRows() == 0 ) {
165 foreach ( $res as $row ) {
166 # print " {$row->old_id} - {$row->old_namespace}:{$row->old_title}\n";
167 $this->compressPage( $row, $extdb );
168 $last = $row->old_id
;
171 $start = $last +
1; # Deletion may leave long empty stretches
172 $this->output( "$start...\n" );
177 * Compress the text in gzip format.
179 * @param stdClass $row
180 * @param string $extdb
183 private function compressPage( $row, $extdb ) {
184 if ( strpos( $row->old_flags
, 'gzip' ) !== false
185 ||
strpos( $row->old_flags
, 'object' ) !== false
187 # print "Already compressed row {$row->old_id}\n";
190 $dbw = $this->getPrimaryDB();
191 $flags = $row->old_flags ?
"{$row->old_flags},gzip" : "gzip";
192 $compress = gzdeflate( $row->old_text
);
194 # Store in external storage if required
195 if ( $extdb !== '' ) {
196 $esFactory = $this->getServiceContainer()->getExternalStoreFactory();
197 /** @var ExternalStoreDB $storeObj */
198 $storeObj = $esFactory->getStore( 'DB' );
199 $compress = $storeObj->store( $extdb, $compress );
200 if ( $compress === false ) {
201 $this->error( "Unable to store object" );
208 $dbw->newUpdateQueryBuilder()
211 'old_flags' => $flags,
212 'old_text' => $compress
215 'old_id' => $row->old_id
217 ->caller( __METHOD__
)
224 * Compress the text in chunks after concatenating the revisions.
226 * @param int $startId
227 * @param int $maxChunkSize
228 * @param string $beginDate
229 * @param string $endDate
230 * @param string $extdb
231 * @param bool|int $maxPageId
234 private function compressWithConcat( $startId, $maxChunkSize, $beginDate,
235 $endDate, $extdb = "", $maxPageId = false
237 $dbr = $this->getReplicaDB();
238 $dbw = $this->getPrimaryDB();
240 # Set up external storage
241 if ( $extdb != '' ) {
242 $esFactory = $this->getServiceContainer()->getExternalStoreFactory();
243 /** @var ExternalStoreDB $storeObj */
244 $storeObj = $esFactory->getStore( 'DB' );
247 $blobStore = $this->getServiceContainer()
248 ->getBlobStoreFactory()
251 # Get all articles by page_id
253 $maxPageId = $dbr->newSelectQueryBuilder()
254 ->select( 'max(page_id)' )
256 ->caller( __METHOD__
)->fetchField();
258 $this->output( "Starting from $startId of $maxPageId\n" );
262 if ( $exclude_ns0 ) {
263 print "Excluding main namespace\n";
264 $pageConds[] = 'page_namespace<>0';
267 $pageConds[] = $queryExtra;
271 # For each article, get a list of revisions which fit the criteria
273 # No recompression, use a condition on old_flags
274 # Don't compress object type entities, because that might produce data loss when
275 # overwriting bulk storage concat rows. Don't compress external references, because
276 # the script doesn't yet delete rows from external storage.
277 $slotRoleStore = $this->getServiceContainer()->getSlotRoleStore();
278 $queryBuilderTemplate = $dbw->newSelectQueryBuilder()
279 ->select( [ 'rev_id', 'old_id', 'old_flags', 'old_text' ] )
282 ->join( 'slots', null, 'rev_id=slot_revision_id' )
283 ->join( 'content', null, 'content_id=slot_content_id' )
284 ->join( 'text', null, 'SUBSTRING(content_address, 4)=old_id' )
288 IExpression
::NOT_LIKE
,
289 new LikeValue( $dbr->anyString(), 'object', $dbr->anyString() )
292 IExpression
::NOT_LIKE
,
293 new LikeValue( $dbr->anyString(), 'external', $dbr->anyString() )
297 'slot_role_id' => $slotRoleStore->getId( SlotRecord
::MAIN
),
298 'SUBSTRING(content_address, 1, 3)=' . $dbr->addQuotes( 'tt:' ),
302 if ( !preg_match( '/^\d{14}$/', $beginDate ) ) {
303 $this->error( "Invalid begin date \"$beginDate\"\n" );
307 $queryBuilderTemplate->andWhere( $dbr->expr( 'rev_timestamp', '>', $beginDate ) );
310 if ( !preg_match( '/^\d{14}$/', $endDate ) ) {
311 $this->error( "Invalid end date \"$endDate\"\n" );
315 $queryBuilderTemplate->andWhere( $dbr->expr( 'rev_timestamp', '<', $endDate ) );
318 for ( $pageId = $startId; $pageId <= $maxPageId; $pageId++
) {
319 $this->waitForReplication();
325 $pageRow = $dbr->newSelectQueryBuilder()
326 ->select( [ 'page_id', 'page_namespace', 'page_title', 'rev_timestamp' ] )
328 ->straightJoin( 'revision', null, 'page_latest = rev_id' )
329 ->where( $pageConds )
330 ->andWhere( [ 'page_id' => $pageId ] )
331 ->caller( __METHOD__
)->fetchRow();
332 if ( $pageRow === false ) {
337 $titleObj = Title
::makeTitle( $pageRow->page_namespace
, $pageRow->page_title
);
338 $this->output( "$pageId\t" . $titleObj->getPrefixedDBkey() . " " );
341 $queryBuilder = clone $queryBuilderTemplate;
342 $revRes = $queryBuilder->where(
344 'rev_page' => $pageRow->page_id
,
345 // Don't operate on the current revision
346 // Use < instead of <> in case the current revision has changed
347 // since the page select, which wasn't locking
348 $dbr->expr( 'rev_timestamp', '<', (int)$pageRow->rev_timestamp
),
350 ->caller( __METHOD__
)->fetchResultSet();
353 foreach ( $revRes as $revRow ) {
357 if ( count( $revs ) < 2 ) {
358 # No revisions matching, no further processing
359 $this->output( "\n" );
365 while ( $i < count( $revs ) ) {
366 if ( $i < count( $revs ) - $maxChunkSize ) {
367 $thisChunkSize = $maxChunkSize;
369 $thisChunkSize = count( $revs ) - $i;
372 $chunk = new ConcatenatedGzipHistoryBlob();
374 $this->beginTransaction( $dbw, __METHOD__
);
376 $primaryOldid = $revs[$i]->old_id
;
378 # Get the text of each revision and add it to the object
379 for ( $j = 0; $j < $thisChunkSize && $chunk->isHappy(); $j++
) {
380 $oldid = $revs[$i +
$j]->old_id
;
382 # Get text. We do not need the full `extractBlob` since the query is built
383 # to fetch non-externalstore blobs.
384 $text = $blobStore->decompressData(
385 $revs[$i +
$j]->old_text
,
386 explode( ',', $revs[$i +
$j]->old_flags
)
389 if ( $text === false ) {
390 $this->error( "\nError, unable to get text in old_id $oldid" );
391 # $dbw->delete( 'old', [ 'old_id' => $oldid ] );
394 if ( $extdb == "" && $j == 0 ) {
395 $chunk->setText( $text );
396 $this->output( '.' );
398 # Don't make a stub if it's going to be longer than the article
399 # Stubs are typically about 100 bytes
400 if ( strlen( $text ) < 120 ) {
402 $this->output( 'x' );
404 $stub = new HistoryBlobStub( $chunk->addItem( $text ) );
405 $stub->setLocation( $primaryOldid );
406 $stub->setReferrer( $oldid );
407 $this->output( '.' );
415 # If we couldn't actually use any stubs because the pages were too small, do nothing
417 if ( $extdb != "" ) {
418 # Move blob objects to External Storage
419 // @phan-suppress-next-line PhanPossiblyUndeclaredVariable storeObj is set when used
420 $stored = $storeObj->store( $extdb, serialize( $chunk ) );
421 if ( $stored === false ) {
422 $this->error( "Unable to store object" );
426 # Store External Storage URLs instead of Stub placeholders
427 foreach ( $stubs as $stub ) {
428 if ( $stub === false ) {
431 # $stored should provide base path to a BLOB
432 $url = $stored . "/" . $stub->getHash();
433 $dbw->newUpdateQueryBuilder()
437 'old_flags' => 'external,utf-8',
440 'old_id' => $stub->getReferrer(),
442 ->caller( __METHOD__
)
446 # Store the main object locally
447 $dbw->newUpdateQueryBuilder()
450 'old_text' => serialize( $chunk ),
451 'old_flags' => 'object,utf-8',
454 'old_id' => $primaryOldid
456 ->caller( __METHOD__
)
459 # Store the stub objects
460 for ( $j = 1; $j < $thisChunkSize; $j++
) {
461 # Skip if not compressing and don't overwrite the first revision
462 if ( $stubs[$j] !== false && $revs[$i +
$j]->old_id
!= $primaryOldid ) {
463 $dbw->newUpdateQueryBuilder()
466 'old_text' => serialize( $stubs[$j] ),
467 'old_flags' => 'object,utf-8',
470 'old_id' => $revs[$i +
$j]->old_id
472 ->caller( __METHOD__
)
479 $this->output( "/" );
480 $this->commitTransaction( $dbw, __METHOD__
);
481 $i +
= $thisChunkSize;
483 $this->output( "\n" );
490 // @codeCoverageIgnoreStart
491 $maintClass = CompressOld
::class;
492 require_once RUN_MAINTENANCE_IF_MAIN
;
493 // @codeCoverageIgnoreEnd