MediaWiki  master
checkStorage.php
Go to the documentation of this file.
1 <?php
27 
28 if ( !defined( 'MEDIAWIKI' ) ) {
29  $optionsWithoutArgs = [ 'fix' ];
30  require_once __DIR__ . '/../CommandLineInc.php';
31 
32  $cs = new CheckStorage;
33  $fix = isset( $options['fix'] );
34  $xml = $args[0] ?? false;
35  $cs->check( $fix, $xml );
36 }
37 
38 // ----------------------------------------------------------------------------------
39 
46 class CheckStorage {
47  private const CONCAT_HEADER = 'O:27:"concatenatedgziphistoryblob"';
48  public $oldIdMap, $errors;
50  public $dbStore = null;
51 
52  public $errorDescriptions = [
53  'restore text' => 'Damaged text, need to be restored from a backup',
54  'restore revision' => 'Damaged revision row, need to be restored from a backup',
55  'unfixable' => 'Unexpected errors with no automated fixing method',
56  'fixed' => 'Errors already fixed',
57  'fixable' => 'Errors which would already be fixed if --fix was specified',
58  ];
59 
60  public function check( $fix = false, $xml = '' ) {
61  $dbr = wfGetDB( DB_REPLICA );
62  if ( $fix ) {
63  print "Checking, will fix errors if possible...\n";
64  } else {
65  print "Checking...\n";
66  }
67  $maxRevId = $dbr->selectField( 'revision', 'MAX(rev_id)', '', __METHOD__ );
68  $chunkSize = 1000;
69  $flagStats = [];
70  $objectStats = [];
71  $knownFlags = [ 'external', 'gzip', 'object', 'utf-8' ];
72  $this->errors = [
73  'restore text' => [],
74  'restore revision' => [],
75  'unfixable' => [],
76  'fixed' => [],
77  'fixable' => [],
78  ];
79 
80  for ( $chunkStart = 1; $chunkStart < $maxRevId; $chunkStart += $chunkSize ) {
81  $chunkEnd = $chunkStart + $chunkSize - 1;
82  // print "$chunkStart of $maxRevId\n";
83 
84  $this->oldIdMap = [];
85  $dbr->ping();
86 
87  // Fetch revision rows
88  $res = $dbr->select(
89  [ 'slots', 'content' ],
90  [ 'slot_revision_id', 'content_address' ],
91  [ "slot_revision_id BETWEEN $chunkStart AND $chunkEnd" ],
92  __METHOD__,
93  [],
94  [ 'content' => [ 'INNER JOIN', [ 'content_id = slot_content_id' ] ] ]
95  );
97  $blobStore = MediaWikiServices::getInstance()->getBlobStore();
98  '@phan-var \MediaWiki\Storage\SqlBlobStore $blobStore';
99  foreach ( $res as $row ) {
100  $textId = $blobStore->getTextIdFromAddress( $row->content_address );
101  if ( $textId ) {
102  if ( !isset( $this->oldIdMap[$textId] ) ) {
103  $this->oldIdMap[ $textId ] = [ $row->slot_revision_id ];
104  } elseif ( !in_array( $row->slot_revision_id, $this->oldIdMap[$textId] ) ) {
105  $this->oldIdMap[ $textId ][] = $row->slot_revision_id;
106  }
107  }
108  }
109 
110  if ( !count( $this->oldIdMap ) ) {
111  continue;
112  }
113 
114  // Fetch old_flags
115  $missingTextRows = $this->oldIdMap;
116  $externalRevs = [];
117  $objectRevs = [];
118  $res = $dbr->select(
119  'text',
120  [ 'old_id', 'old_flags' ],
121  [ 'old_id' => array_keys( $this->oldIdMap ) ],
122  __METHOD__
123  );
124  foreach ( $res as $row ) {
128  $flags = $row->old_flags;
129  $id = $row->old_id;
130 
131  // Create flagStats row if it doesn't exist
132  $flagStats += [ $flags => 0 ];
133  // Increment counter
134  $flagStats[$flags]++;
135 
136  // Not missing
137  unset( $missingTextRows[$row->old_id] );
138 
139  // Check for external or object
140  if ( $flags == '' ) {
141  $flagArray = [];
142  } else {
143  $flagArray = explode( ',', $flags );
144  }
145  if ( in_array( 'external', $flagArray ) ) {
146  $externalRevs[] = $id;
147  } elseif ( in_array( 'object', $flagArray ) ) {
148  $objectRevs[] = $id;
149  }
150 
151  // Check for unrecognised flags
152  if ( $flags == '0' ) {
153  // This is a known bug from 2004
154  // It's safe to just erase the old_flags field
155  if ( $fix ) {
156  $this->addError( 'fixed', "Warning: old_flags set to 0", $id );
157  $dbw = wfGetDB( DB_PRIMARY );
158  $dbw->ping();
159  $dbw->update( 'text', [ 'old_flags' => '' ],
160  [ 'old_id' => $id ], __METHOD__ );
161  echo "Fixed\n";
162  } else {
163  $this->addError( 'fixable', "Warning: old_flags set to 0", $id );
164  }
165  } elseif ( count( array_diff( $flagArray, $knownFlags ) ) ) {
166  $this->addError( 'unfixable', "Error: invalid flags field \"$flags\"", $id );
167  }
168  }
169 
170  // Output errors for any missing text rows
171  foreach ( $missingTextRows as $oldId => $revIds ) {
172  $this->addError( 'restore revision', "Error: missing text row", $oldId );
173  }
174 
175  // Verify external revisions
176  $externalConcatBlobs = [];
177  $externalNormalBlobs = [];
178  if ( count( $externalRevs ) ) {
179  $res = $dbr->select(
180  'text',
181  [ 'old_id', 'old_flags', 'old_text' ],
182  [ 'old_id' => $externalRevs ],
183  __METHOD__
184  );
185  foreach ( $res as $row ) {
186  $urlParts = explode( '://', $row->old_text, 2 );
187  if ( count( $urlParts ) !== 2 || $urlParts[1] == '' ) {
188  $this->addError( 'restore text', "Error: invalid URL \"{$row->old_text}\"", $row->old_id );
189  continue;
190  }
191  list( $proto, ) = $urlParts;
192  if ( $proto != 'DB' ) {
193  $this->addError(
194  'restore text',
195  "Error: invalid external protocol \"$proto\"",
196  $row->old_id );
197  continue;
198  }
199  $path = explode( '/', $row->old_text );
200  $cluster = $path[2];
201  $id = $path[3];
202  if ( isset( $path[4] ) ) {
203  $externalConcatBlobs[$cluster][$id][] = $row->old_id;
204  } else {
205  $externalNormalBlobs[$cluster][$id][] = $row->old_id;
206  }
207  }
208  }
209 
210  // Check external concat blobs for the right header
211  $this->checkExternalConcatBlobs( $externalConcatBlobs );
212 
213  // Check external normal blobs for existence
214  if ( count( $externalNormalBlobs ) ) {
215  if ( $this->dbStore === null ) {
216  $esFactory = MediaWikiServices::getInstance()->getExternalStoreFactory();
217  $this->dbStore = $esFactory->getStore( 'DB' );
218  }
219  foreach ( $externalConcatBlobs as $cluster => $xBlobIds ) {
220  $blobIds = array_keys( $xBlobIds );
221  $extDb =& $this->dbStore->getReplica( $cluster );
222  $blobsTable = $this->dbStore->getTable( $extDb );
223  $res = $extDb->select( $blobsTable,
224  [ 'blob_id' ],
225  [ 'blob_id' => $blobIds ],
226  __METHOD__
227  );
228  foreach ( $res as $row ) {
229  unset( $xBlobIds[$row->blob_id] );
230  }
231  // Print errors for missing blobs rows
232  foreach ( $xBlobIds as $blobId => $oldId ) {
233  $this->addError(
234  'restore text',
235  "Error: missing target $blobId for one-part ES URL",
236  $oldId );
237  }
238  }
239  }
240 
241  // Check local objects
242  $dbr->ping();
243  $concatBlobs = [];
244  $curIds = [];
245  if ( count( $objectRevs ) ) {
246  $headerLength = 300;
247  $res = $dbr->select(
248  'text',
249  [ 'old_id', 'old_flags', "LEFT(old_text, $headerLength) AS header" ],
250  [ 'old_id' => $objectRevs ],
251  __METHOD__
252  );
253  foreach ( $res as $row ) {
254  $oldId = $row->old_id;
255  $matches = [];
256  if ( !preg_match( '/^O:(\d+):"(\w+)"/', $row->header, $matches ) ) {
257  $this->addError( 'restore text', "Error: invalid object header", $oldId );
258  continue;
259  }
260 
261  $className = strtolower( $matches[2] );
262  if ( strlen( $className ) != $matches[1] ) {
263  $this->addError(
264  'restore text',
265  "Error: invalid object header, wrong class name length",
266  $oldId
267  );
268  continue;
269  }
270 
271  $objectStats += [ $className => 0 ];
272  $objectStats[$className]++;
273 
274  switch ( $className ) {
275  case 'concatenatedgziphistoryblob':
276  // Good
277  break;
278  case 'historyblobstub':
279  case 'historyblobcurstub':
280  if ( strlen( $row->header ) == $headerLength ) {
281  $this->addError( 'unfixable', "Error: overlong stub header", $oldId );
282  break;
283  }
284  $stubObj = unserialize( $row->header );
285  if ( !is_object( $stubObj ) ) {
286  $this->addError( 'restore text', "Error: unable to unserialize stub object", $oldId );
287  break;
288  }
289  if ( $className == 'historyblobstub' ) {
290  $concatBlobs[$stubObj->mOldId][] = $oldId;
291  } else {
292  $curIds[$stubObj->mCurId][] = $oldId;
293  }
294  break;
295  default:
296  $this->addError( 'unfixable', "Error: unrecognised object class \"$className\"", $oldId );
297  }
298  }
299  }
300 
301  // Check local concat blob validity
302  $externalConcatBlobs = [];
303  if ( count( $concatBlobs ) ) {
304  $headerLength = 300;
305  $res = $dbr->select(
306  'text',
307  [ 'old_id', 'old_flags', "LEFT(old_text, $headerLength) AS header" ],
308  [ 'old_id' => array_keys( $concatBlobs ) ],
309  __METHOD__
310  );
311  foreach ( $res as $row ) {
312  $flags = explode( ',', $row->old_flags );
313  if ( in_array( 'external', $flags ) ) {
314  // Concat blob is in external storage?
315  if ( in_array( 'object', $flags ) ) {
316  $urlParts = explode( '/', $row->header );
317  if ( $urlParts[0] != 'DB:' ) {
318  $this->addError(
319  'unfixable',
320  "Error: unrecognised external storage type \"{$urlParts[0]}",
321  $row->old_id
322  );
323  } else {
324  $cluster = $urlParts[2];
325  $id = $urlParts[3];
326  if ( !isset( $externalConcatBlobs[$cluster][$id] ) ) {
327  $externalConcatBlobs[$cluster][$id] = [];
328  }
329  $externalConcatBlobs[$cluster][$id] = array_merge(
330  $externalConcatBlobs[$cluster][$id], $concatBlobs[$row->old_id]
331  );
332  }
333  } else {
334  $this->addError(
335  'unfixable',
336  "Error: invalid flags \"{$row->old_flags}\" on concat bulk row {$row->old_id}",
337  $concatBlobs[$row->old_id] );
338  }
339  } elseif ( strcasecmp(
340  substr( $row->header, 0, strlen( self::CONCAT_HEADER ) ),
341  self::CONCAT_HEADER
342  ) ) {
343  $this->addError(
344  'restore text',
345  "Error: Incorrect object header for concat bulk row {$row->old_id}",
346  $concatBlobs[$row->old_id]
347  );
348  }
349 
350  unset( $concatBlobs[$row->old_id] );
351  }
352  }
353 
354  // Check targets of unresolved stubs
355  $this->checkExternalConcatBlobs( $externalConcatBlobs );
356  // next chunk
357  }
358 
359  print "\n\nErrors:\n";
360  foreach ( $this->errors as $name => $errors ) {
361  if ( count( $errors ) ) {
362  $description = $this->errorDescriptions[$name];
363  echo "$description: " . implode( ',', array_keys( $errors ) ) . "\n";
364  }
365  }
366 
367  if ( count( $this->errors['restore text'] ) && $fix ) {
368  if ( (string)$xml !== '' ) {
369  $this->restoreText( array_keys( $this->errors['restore text'] ), $xml );
370  } else {
371  echo "Can't fix text, no XML backup specified\n";
372  }
373  }
374 
375  print "\nFlag statistics:\n";
376  $total = array_sum( $flagStats );
377  foreach ( $flagStats as $flag => $count ) {
378  printf( "%-30s %10d %5.2f%%\n", $flag, $count, $count / $total * 100 );
379  }
380  print "\nLocal object statistics:\n";
381  $total = array_sum( $objectStats );
382  foreach ( $objectStats as $className => $count ) {
383  printf( "%-30s %10d %5.2f%%\n", $className, $count, $count / $total * 100 );
384  }
385  }
386 
387  private function addError( $type, $msg, $ids ) {
388  if ( is_array( $ids ) && count( $ids ) == 1 ) {
389  $ids = reset( $ids );
390  }
391  if ( is_array( $ids ) ) {
392  $revIds = [];
393  foreach ( $ids as $id ) {
394  $revIds = array_unique( array_merge( $revIds, $this->oldIdMap[$id] ) );
395  }
396  print "$msg in text rows " . implode( ', ', $ids ) .
397  ", revisions " . implode( ', ', $revIds ) . "\n";
398  } else {
399  $id = $ids;
400  $revIds = $this->oldIdMap[$id];
401  if ( count( $revIds ) == 1 ) {
402  print "$msg in old_id $id, rev_id {$revIds[0]}\n";
403  } else {
404  print "$msg in old_id $id, revisions " . implode( ', ', $revIds ) . "\n";
405  }
406  }
407  $this->errors[$type] += array_fill_keys( $revIds, true );
408  }
409 
410  private function checkExternalConcatBlobs( $externalConcatBlobs ) {
411  if ( !count( $externalConcatBlobs ) ) {
412  return;
413  }
414 
415  if ( $this->dbStore === null ) {
416  $esFactory = MediaWikiServices::getInstance()->getExternalStoreFactory();
417  $this->dbStore = $esFactory->getStore( 'DB' );
418  }
419 
420  foreach ( $externalConcatBlobs as $cluster => $oldIds ) {
421  $blobIds = array_keys( $oldIds );
422  $extDb =& $this->dbStore->getReplica( $cluster );
423  $blobsTable = $this->dbStore->getTable( $extDb );
424  $headerLength = strlen( self::CONCAT_HEADER );
425  $res = $extDb->select( $blobsTable,
426  [ 'blob_id', "LEFT(blob_text, $headerLength) AS header" ],
427  [ 'blob_id' => $blobIds ],
428  __METHOD__
429  );
430  foreach ( $res as $row ) {
431  if ( strcasecmp( $row->header, self::CONCAT_HEADER ) ) {
432  $this->addError(
433  'restore text',
434  "Error: invalid header on target $cluster/{$row->blob_id} of two-part ES URL",
435  $oldIds[$row->blob_id]
436  );
437  }
438  unset( $oldIds[$row->blob_id] );
439  }
440 
441  // Print errors for missing blobs rows
442  foreach ( $oldIds as $blobId => $oldIds2 ) {
443  $this->addError(
444  'restore text',
445  "Error: missing target $cluster/$blobId for two-part ES URL",
446  $oldIds2
447  );
448  }
449  }
450  }
451 
452  private function restoreText( $revIds, $xml ) {
453  global $wgDBname;
454  $tmpDir = wfTempDir();
455 
456  if ( !count( $revIds ) ) {
457  return;
458  }
459 
460  print "Restoring text from XML backup...\n";
461 
462  $revFileName = "$tmpDir/broken-revlist-$wgDBname";
463  $filteredXmlFileName = "$tmpDir/filtered-$wgDBname.xml";
464 
465  // Write revision list
466  if ( !file_put_contents( $revFileName, implode( "\n", $revIds ) ) ) {
467  echo "Error writing revision list, can't restore text\n";
468 
469  return;
470  }
471 
472  // Run mwdumper
473  echo "Filtering XML dump...\n";
474  $exitStatus = 0;
475  passthru( 'mwdumper ' .
476  Shell::escape(
477  "--output=file:$filteredXmlFileName",
478  "--filter=revlist:$revFileName",
479  $xml
480  ), $exitStatus
481  );
482 
483  if ( $exitStatus ) {
484  echo "mwdumper died with exit status $exitStatus\n";
485 
486  return;
487  }
488 
489  $file = fopen( $filteredXmlFileName, 'r' );
490  if ( !$file ) {
491  echo "Unable to open filtered XML file\n";
492 
493  return;
494  }
495 
496  $dbr = wfGetDB( DB_REPLICA );
497  $dbw = wfGetDB( DB_PRIMARY );
498  $dbr->ping();
499  $dbw->ping();
500 
502  $importer = MediaWikiServices::getInstance()
503  ->getWikiImporterFactory()
504  ->getWikiImporter( $source );
505  $importer->setRevisionCallback( [ $this, 'importRevision' ] );
506  $importer->setNoticeCallback( static function ( $msg, $params ) {
507  echo wfMessage( $msg, $params )->text() . "\n";
508  } );
509  $importer->doImport();
510  }
511 
512  private function importRevision( &$revision, &$importer ) {
513  $id = $revision->getID();
514  $content = $revision->getContent( RevisionRecord::RAW );
515  $id = $id ?: '';
516 
517  if ( $content === null ) {
518  echo "Revision $id is broken, we have no content available\n";
519 
520  return;
521  }
522 
523  $text = $content->serialize();
524  if ( $text === '' ) {
525  // This is what happens if the revision was broken at the time the
526  // dump was made. Unfortunately, it also happens if the revision was
527  // legitimately blank, so there's no way to tell the difference. To
528  // be safe, we'll skip it and leave it broken
529 
530  echo "Revision $id is blank in the dump, may have been broken before export\n";
531 
532  return;
533  }
534 
535  if ( !$id ) {
536  // No ID, can't import
537  echo "No id tag in revision, can't import\n";
538 
539  return;
540  }
541 
542  // Find text row again
543  $dbr = wfGetDB( DB_REPLICA );
544  $res = $dbr->selectRow(
545  [ 'slots', 'content' ],
546  [ 'content_address' ],
547  [ 'slot_revision_id' => $id ],
548  __METHOD__,
549  [],
550  [ 'content' => [ 'INNER JOIN', [ 'content_id = slot_content_id' ] ] ]
551  );
552 
553  $blobStore = MediaWikiServices::getInstance()
554  ->getBlobStoreFactory()
555  ->newSqlBlobStore();
556  $oldId = $blobStore->getTextIdFromAddress( $res->content_address );
557 
558  if ( !$oldId ) {
559  echo "Missing revision row for rev_id $id\n";
560  return;
561  }
562 
563  // Compress the text
564  $flags = $blobStore->compressData( $text );
565 
566  // Update the text row
567  $dbw = wfGetDB( DB_PRIMARY );
568  $dbw->update( 'text',
569  [ 'old_flags' => $flags, 'old_text' => $text ],
570  [ 'old_id' => $oldId ],
571  __METHOD__, [ 'LIMIT' => 1 ]
572  );
573 
574  // Remove it from the unfixed list and add it to the fixed list
575  unset( $this->errors['restore text'][$id] );
576  $this->errors['fixed'][$id] = true;
577  }
578 }
MediaWiki\Shell\Shell
Executes shell commands.
Definition: Shell.php:45
CheckStorage
Maintenance script to do various checks on external storage.
Definition: checkStorage.php:46
MediaWiki\Revision\RevisionRecord
Page revision base class.
Definition: RevisionRecord.php:47
ExternalStoreDB
DB accessible external objects.
Definition: ExternalStoreDB.php:40
$wgDBname
$wgDBname
Current wiki database name.
Definition: DefaultSettings.php:2054
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:193
CheckStorage\check
check( $fix=false, $xml='')
Definition: checkStorage.php:60
$file
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Item class for a filearchive table row.
Definition: router.php:42
wfMessage
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
Definition: GlobalFunctions.php:1186
$res
$res
Definition: testCompression.php:57
ImportStreamSource
Imports a XML dump from a file (either from file upload, files on disk, or HTTP)
Definition: ImportStreamSource.php:32
CheckStorage\importRevision
importRevision(&$revision, &$importer)
Definition: checkStorage.php:512
CheckStorage\$errorDescriptions
$errorDescriptions
Definition: checkStorage.php:52
$dbr
$dbr
Definition: testCompression.php:54
CheckStorage\$oldIdMap
$oldIdMap
Definition: checkStorage.php:48
wfGetDB
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
Definition: GlobalFunctions.php:2202
$matches
$matches
Definition: NoLocalSettings.php:24
$args
if( $line===false) $args
Definition: mcc.php:124
CheckStorage\addError
addError( $type, $msg, $ids)
Definition: checkStorage.php:387
DB_REPLICA
const DB_REPLICA
Definition: defines.php:25
CheckStorage\CONCAT_HEADER
const CONCAT_HEADER
Definition: checkStorage.php:47
$content
$content
Definition: router.php:76
$optionsWithoutArgs
global $optionsWithoutArgs
Definition: CommandLineInc.php:28
DB_PRIMARY
const DB_PRIMARY
Definition: defines.php:27
CheckStorage\restoreText
restoreText( $revIds, $xml)
Definition: checkStorage.php:452
unserialize
unserialize( $serialized)
Definition: ApiMessageTrait.php:146
wfTempDir
wfTempDir()
Tries to get the system directory for temporary files.
Definition: GlobalFunctions.php:1731
CheckStorage\$errors
$errors
Definition: checkStorage.php:48
$path
$path
Definition: NoLocalSettings.php:25
$source
$source
Definition: mwdoc-filter.php:34
CheckStorage\$dbStore
ExternalStoreDB $dbStore
Definition: checkStorage.php:50
CheckStorage\checkExternalConcatBlobs
checkExternalConcatBlobs( $externalConcatBlobs)
Definition: checkStorage.php:410
$type
$type
Definition: testCompression.php:52