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