MediaWiki master
compressOld.php
Go to the documentation of this file.
1<?php
48
49// @codeCoverageIgnoreStart
50require_once __DIR__ . '/../Maintenance.php';
51// @codeCoverageIgnoreEnd
52
58class CompressOld extends Maintenance {
59 public function __construct() {
60 parent::__construct();
61 $this->addDescription( 'Compress the text of a wiki' );
62 $this->addOption( 'type', 'Set compression type to either: gzip|concat', false, true, 't' );
63 $this->addOption(
64 'chunksize',
65 'Maximum number of revisions in a concat chunk',
66 false,
67 true,
68 'c'
69 );
70 $this->addOption(
71 'begin-date',
72 'Earliest date to check for uncompressed revisions',
73 false,
74 true,
75 'b'
76 );
77 $this->addOption( 'end-date', 'Latest revision date to compress', false, true, 'e' );
78 $this->addOption(
79 'startid',
80 'The id to start from (gzip -> text table, concat -> page table)',
81 false,
82 true,
83 's'
84 );
85 $this->addOption(
86 'extdb',
87 'Store specified revisions in an external cluster (untested)',
88 false,
89 true
90 );
91 $this->addOption(
92 'endid',
93 'The page_id to stop at (only when using concat compression type)',
94 false,
95 true,
96 'n'
97 );
98 }
99
100 public function execute() {
101 global $wgDBname;
102 if ( !function_exists( "gzdeflate" ) ) {
103 $this->fatalError( "You must enable zlib support in PHP to compress old revisions!\n" .
104 "Please see https://www.php.net/manual/en/ref.zlib.php\n" );
105 }
106
107 $type = $this->getOption( 'type', 'concat' );
108 $chunkSize = $this->getOption( 'chunksize', 20 );
109 $startId = $this->getOption( 'startid', 0 );
110 $beginDate = $this->getOption( 'begin-date', '' );
111 $endDate = $this->getOption( 'end-date', '' );
112 $extDB = $this->getOption( 'extdb', '' );
113 $endId = $this->getOption( 'endid', false );
114
115 if ( $type != 'concat' && $type != 'gzip' ) {
116 $this->error( "Type \"{$type}\" not supported" );
117 }
118
119 if ( $extDB != '' ) {
120 $this->output( "Compressing database {$wgDBname} to external cluster {$extDB}\n"
121 . str_repeat( '-', 76 ) . "\n\n" );
122 } else {
123 $this->output( "Compressing database {$wgDBname}\n"
124 . str_repeat( '-', 76 ) . "\n\n" );
125 }
126
127 $success = true;
128 if ( $type == 'concat' ) {
129 $success = $this->compressWithConcat( $startId, $chunkSize, $beginDate,
130 $endDate, $extDB, $endId );
131 } else {
132 $this->compressOldPages( $startId, $extDB );
133 }
134
135 if ( $success ) {
136 $this->output( "Done.\n" );
137 }
138 }
139
146 private function compressOldPages( $start = 0, $extdb = '' ) {
147 $chunksize = 50;
148 $this->output( "Starting from old_id $start...\n" );
149 $dbw = $this->getPrimaryDB();
150 do {
151 $res = $dbw->newSelectQueryBuilder()
152 ->select( [ 'old_id', 'old_flags', 'old_text' ] )
153 ->forUpdate()
154 ->from( 'text' )
155 ->where( "old_id>=$start" )
156 ->orderBy( 'old_id' )
157 ->limit( $chunksize )
158 ->caller( __METHOD__ )->fetchResultSet();
159
160 if ( $res->numRows() == 0 ) {
161 break;
162 }
163
164 $last = $start;
165
166 foreach ( $res as $row ) {
167 # print " {$row->old_id} - {$row->old_namespace}:{$row->old_title}\n";
168 $this->compressPage( $row, $extdb );
169 $last = $row->old_id;
170 }
171
172 $start = $last + 1; # Deletion may leave long empty stretches
173 $this->output( "$start...\n" );
174 } while ( true );
175 }
176
184 private function compressPage( $row, $extdb ) {
185 if ( strpos( $row->old_flags, 'gzip' ) !== false
186 || strpos( $row->old_flags, 'object' ) !== false
187 ) {
188 # print "Already compressed row {$row->old_id}\n";
189 return false;
190 }
191 $dbw = $this->getPrimaryDB();
192 $flags = $row->old_flags ? "{$row->old_flags},gzip" : "gzip";
193 $compress = gzdeflate( $row->old_text );
194
195 # Store in external storage if required
196 if ( $extdb !== '' ) {
197 $esFactory = $this->getServiceContainer()->getExternalStoreFactory();
199 $storeObj = $esFactory->getStore( 'DB' );
200 $compress = $storeObj->store( $extdb, $compress );
201 if ( $compress === false ) {
202 $this->error( "Unable to store object" );
203
204 return false;
205 }
206 }
207
208 # Update text row
209 $dbw->newUpdateQueryBuilder()
210 ->update( 'text' )
211 ->set( [
212 'old_flags' => $flags,
213 'old_text' => $compress
214 ] )
215 ->where( [
216 'old_id' => $row->old_id
217 ] )
218 ->caller( __METHOD__ )
219 ->execute();
220
221 return true;
222 }
223
235 private function compressWithConcat( $startId, $maxChunkSize, $beginDate,
236 $endDate, $extdb = "", $maxPageId = false
237 ) {
238 $dbr = $this->getReplicaDB();
239 $dbw = $this->getPrimaryDB();
240
241 # Set up external storage
242 if ( $extdb != '' ) {
243 $esFactory = $this->getServiceContainer()->getExternalStoreFactory();
245 $storeObj = $esFactory->getStore( 'DB' );
246 }
247
248 $blobStore = $this->getServiceContainer()
249 ->getBlobStoreFactory()
250 ->newSqlBlobStore();
251
252 # Get all articles by page_id
253 if ( !$maxPageId ) {
254 $maxPageId = $dbr->newSelectQueryBuilder()
255 ->select( 'max(page_id)' )
256 ->from( 'page' )
257 ->caller( __METHOD__ )->fetchField();
258 }
259 $this->output( "Starting from $startId of $maxPageId\n" );
260 $pageConds = [];
261
262 /*
263 if ( $exclude_ns0 ) {
264 print "Excluding main namespace\n";
265 $pageConds[] = 'page_namespace<>0';
266 }
267 if ( $queryExtra ) {
268 $pageConds[] = $queryExtra;
269 }
270 */
271
272 # For each article, get a list of revisions which fit the criteria
273
274 # No recompression, use a condition on old_flags
275 # Don't compress object type entities, because that might produce data loss when
276 # overwriting bulk storage concat rows. Don't compress external references, because
277 # the script doesn't yet delete rows from external storage.
278 $slotRoleStore = $this->getServiceContainer()->getSlotRoleStore();
279 $queryBuilderTemplate = $dbw->newSelectQueryBuilder()
280 ->select( [ 'rev_id', 'old_id', 'old_flags', 'old_text' ] )
281 ->forUpdate()
282 ->from( 'revision' )
283 ->join( 'slots', null, 'rev_id=slot_revision_id' )
284 ->join( 'content', null, 'content_id=slot_content_id' )
285 ->join( 'text', null, 'SUBSTRING(content_address, 4)=old_id' )
286 ->where(
287 $dbr->expr(
288 'old_flags',
289 IExpression::NOT_LIKE,
290 new LikeValue( $dbr->anyString(), 'object', $dbr->anyString() )
291 )->and(
292 'old_flags',
293 IExpression::NOT_LIKE,
294 new LikeValue( $dbr->anyString(), 'external', $dbr->anyString() )
295 )
296 )
297 ->andWhere( [
298 'slot_role_id' => $slotRoleStore->getId( SlotRecord::MAIN ),
299 'SUBSTRING(content_address, 1, 3)=' . $dbr->addQuotes( 'tt:' ),
300 ] );
301
302 if ( $beginDate ) {
303 if ( !preg_match( '/^\d{14}$/', $beginDate ) ) {
304 $this->error( "Invalid begin date \"$beginDate\"\n" );
305
306 return false;
307 }
308 $queryBuilderTemplate->andWhere( $dbr->expr( 'rev_timestamp', '>', $beginDate ) );
309 }
310 if ( $endDate ) {
311 if ( !preg_match( '/^\d{14}$/', $endDate ) ) {
312 $this->error( "Invalid end date \"$endDate\"\n" );
313
314 return false;
315 }
316 $queryBuilderTemplate->andWhere( $dbr->expr( 'rev_timestamp', '<', $endDate ) );
317 }
318
319 for ( $pageId = $startId; $pageId <= $maxPageId; $pageId++ ) {
320 $this->waitForReplication();
321
322 # Wake up
323 $dbr->ping();
324
325 # Get the page row
326 $pageRow = $dbr->newSelectQueryBuilder()
327 ->select( [ 'page_id', 'page_namespace', 'page_title', 'rev_timestamp' ] )
328 ->from( 'page' )
329 ->straightJoin( 'revision', null, 'page_latest = rev_id' )
330 ->where( $pageConds )
331 ->andWhere( [ 'page_id' => $pageId ] )
332 ->caller( __METHOD__ )->fetchRow();
333 if ( $pageRow === false ) {
334 continue;
335 }
336
337 # Display progress
338 $titleObj = Title::makeTitle( $pageRow->page_namespace, $pageRow->page_title );
339 $this->output( "$pageId\t" . $titleObj->getPrefixedDBkey() . " " );
340
341 # Load revisions
342 $queryBuilder = clone $queryBuilderTemplate;
343 $revRes = $queryBuilder->where(
344 [
345 'rev_page' => $pageRow->page_id,
346 // Don't operate on the current revision
347 // Use < instead of <> in case the current revision has changed
348 // since the page select, which wasn't locking
349 $dbr->expr( 'rev_timestamp', '<', (int)$pageRow->rev_timestamp ),
350 ] )
351 ->caller( __METHOD__ )->fetchResultSet();
352
353 $revs = [];
354 foreach ( $revRes as $revRow ) {
355 $revs[] = $revRow;
356 }
357
358 if ( count( $revs ) < 2 ) {
359 # No revisions matching, no further processing
360 $this->output( "\n" );
361 continue;
362 }
363
364 # For each chunk
365 $i = 0;
366 while ( $i < count( $revs ) ) {
367 if ( $i < count( $revs ) - $maxChunkSize ) {
368 $thisChunkSize = $maxChunkSize;
369 } else {
370 $thisChunkSize = count( $revs ) - $i;
371 }
372
373 $chunk = new ConcatenatedGzipHistoryBlob();
374 $stubs = [];
375 $this->beginTransaction( $dbw, __METHOD__ );
376 $usedChunk = false;
377 $primaryOldid = $revs[$i]->old_id;
378
379 # Get the text of each revision and add it to the object
380 for ( $j = 0; $j < $thisChunkSize && $chunk->isHappy(); $j++ ) {
381 $oldid = $revs[$i + $j]->old_id;
382
383 # Get text. We do not need the full `extractBlob` since the query is built
384 # to fetch non-externalstore blobs.
385 $text = $blobStore->decompressData(
386 $revs[$i + $j]->old_text,
387 explode( ',', $revs[$i + $j]->old_flags )
388 );
389
390 if ( $text === false ) {
391 $this->error( "\nError, unable to get text in old_id $oldid" );
392 # $dbw->delete( 'old', [ 'old_id' => $oldid ] );
393 }
394
395 if ( $extdb == "" && $j == 0 ) {
396 $chunk->setText( $text );
397 $this->output( '.' );
398 } else {
399 # Don't make a stub if it's going to be longer than the article
400 # Stubs are typically about 100 bytes
401 if ( strlen( $text ) < 120 ) {
402 $stub = false;
403 $this->output( 'x' );
404 } else {
405 $stub = new HistoryBlobStub( $chunk->addItem( $text ) );
406 $stub->setLocation( $primaryOldid );
407 $stub->setReferrer( $oldid );
408 $this->output( '.' );
409 $usedChunk = true;
410 }
411 $stubs[$j] = $stub;
412 }
413 }
414 $thisChunkSize = $j;
415
416 # If we couldn't actually use any stubs because the pages were too small, do nothing
417 if ( $usedChunk ) {
418 if ( $extdb != "" ) {
419 # Move blob objects to External Storage
420 // @phan-suppress-next-line PhanPossiblyUndeclaredVariable storeObj is set when used
421 $stored = $storeObj->store( $extdb, serialize( $chunk ) );
422 if ( $stored === false ) {
423 $this->error( "Unable to store object" );
424
425 return false;
426 }
427 # Store External Storage URLs instead of Stub placeholders
428 foreach ( $stubs as $stub ) {
429 if ( $stub === false ) {
430 continue;
431 }
432 # $stored should provide base path to a BLOB
433 $url = $stored . "/" . $stub->getHash();
434 $dbw->newUpdateQueryBuilder()
435 ->update( 'text' )
436 ->set( [
437 'old_text' => $url,
438 'old_flags' => 'external,utf-8',
439 ] )
440 ->where( [
441 'old_id' => $stub->getReferrer(),
442 ] )
443 ->caller( __METHOD__ )
444 ->execute();
445 }
446 } else {
447 # Store the main object locally
448 $dbw->newUpdateQueryBuilder()
449 ->update( 'text' )
450 ->set( [
451 'old_text' => serialize( $chunk ),
452 'old_flags' => 'object,utf-8',
453 ] )
454 ->where( [
455 'old_id' => $primaryOldid
456 ] )
457 ->caller( __METHOD__ )
458 ->execute();
459
460 # Store the stub objects
461 for ( $j = 1; $j < $thisChunkSize; $j++ ) {
462 # Skip if not compressing and don't overwrite the first revision
463 if ( $stubs[$j] !== false && $revs[$i + $j]->old_id != $primaryOldid ) {
464 $dbw->newUpdateQueryBuilder()
465 ->update( 'text' )
466 ->set( [
467 'old_text' => serialize( $stubs[$j] ),
468 'old_flags' => 'object,utf-8',
469 ] )
470 ->where( [
471 'old_id' => $revs[$i + $j]->old_id
472 ] )
473 ->caller( __METHOD__ )
474 ->execute();
475 }
476 }
477 }
478 }
479 # Done, next
480 $this->output( "/" );
481 $this->commitTransaction( $dbw, __METHOD__ );
482 $i += $thisChunkSize;
483 }
484 $this->output( "\n" );
485 }
486
487 return true;
488 }
489}
490
491// @codeCoverageIgnoreStart
492$maintClass = CompressOld::class;
493require_once RUN_MAINTENANCE_IF_MAIN;
494// @codeCoverageIgnoreEnd
Maintenance script that compress the text of a wiki.
execute()
Do the actual work.
__construct()
Default constructor.
Concatenated gzip (CGZ) storage Improves compression ratio by concatenating like objects before gzipp...
Pointer object for an item within a CGZ blob stored in the text table.
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
output( $out, $channel=null)
Throw some output to the user.
commitTransaction(IDatabase $dbw, $fname)
Commit the transaction on a DB handle and wait for replica DB servers to catch up.
fatalError( $msg, $exitCode=1)
Output a message and terminate the current script.
addOption( $name, $description, $required=false, $withArg=false, $shortName=false, $multiOccurrence=false)
Add a parameter to the script.
waitForReplication()
Wait for replica DB servers to catch up.
getOption( $name, $default=null)
Get an option, or return the default.
beginTransaction(IDatabase $dbw, $fname)
Begin a transaction on a DB handle.
error( $err, $die=0)
Throw an error to the user.
getServiceContainer()
Returns the main service container.
addDescription( $text)
Set the description text.
Value object representing a content slot associated with a page revision.
Represents a title within MediaWiki.
Definition Title.php:78
Content of like value.
Definition LikeValue.php:14
$maintClass
$wgDBname
Config variable stub for the DBname setting, for use by phpdoc and IDEs.