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