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