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_MASTER );
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  // @phan-suppress-next-line PhanImpossibleConditionInLoop
362  if ( count( $errors ) ) {
363  $description = $this->errorDescriptions[$name];
364  echo "$description: " . implode( ',', array_keys( $errors ) ) . "\n";
365  }
366  }
367 
368  // @phan-suppress-next-line PhanImpossibleCondition
369  if ( count( $this->errors['restore text'] ) && $fix ) {
370  if ( (string)$xml !== '' ) {
371  $this->restoreText( array_keys( $this->errors['restore text'] ), $xml );
372  } else {
373  echo "Can't fix text, no XML backup specified\n";
374  }
375  }
376 
377  print "\nFlag statistics:\n";
378  $total = array_sum( $flagStats );
379  foreach ( $flagStats as $flag => $count ) {
380  printf( "%-30s %10d %5.2f%%\n", $flag, $count, $count / $total * 100 );
381  }
382  print "\nLocal object statistics:\n";
383  $total = array_sum( $objectStats );
384  foreach ( $objectStats as $className => $count ) {
385  printf( "%-30s %10d %5.2f%%\n", $className, $count, $count / $total * 100 );
386  }
387  }
388 
389  private function addError( $type, $msg, $ids ) {
390  if ( is_array( $ids ) && count( $ids ) == 1 ) {
391  $ids = reset( $ids );
392  }
393  if ( is_array( $ids ) ) {
394  $revIds = [];
395  foreach ( $ids as $id ) {
396  $revIds = array_unique( array_merge( $revIds, $this->oldIdMap[$id] ) );
397  }
398  print "$msg in text rows " . implode( ', ', $ids ) .
399  ", revisions " . implode( ', ', $revIds ) . "\n";
400  } else {
401  $id = $ids;
402  $revIds = $this->oldIdMap[$id];
403  if ( count( $revIds ) == 1 ) {
404  print "$msg in old_id $id, rev_id {$revIds[0]}\n";
405  } else {
406  print "$msg in old_id $id, revisions " . implode( ', ', $revIds ) . "\n";
407  }
408  }
409  $this->errors[$type] += array_flip( $revIds );
410  }
411 
412  private function checkExternalConcatBlobs( $externalConcatBlobs ) {
413  if ( !count( $externalConcatBlobs ) ) {
414  return;
415  }
416 
417  if ( $this->dbStore === null ) {
418  $esFactory = MediaWikiServices::getInstance()->getExternalStoreFactory();
419  $this->dbStore = $esFactory->getStore( 'DB' );
420  }
421 
422  foreach ( $externalConcatBlobs as $cluster => $oldIds ) {
423  $blobIds = array_keys( $oldIds );
424  $extDb =& $this->dbStore->getReplica( $cluster );
425  $blobsTable = $this->dbStore->getTable( $extDb );
426  $headerLength = strlen( self::CONCAT_HEADER );
427  $res = $extDb->select( $blobsTable,
428  [ 'blob_id', "LEFT(blob_text, $headerLength) AS header" ],
429  [ 'blob_id' => $blobIds ],
430  __METHOD__
431  );
432  foreach ( $res as $row ) {
433  if ( strcasecmp( $row->header, self::CONCAT_HEADER ) ) {
434  $this->addError(
435  'restore text',
436  "Error: invalid header on target $cluster/{$row->blob_id} of two-part ES URL",
437  $oldIds[$row->blob_id]
438  );
439  }
440  unset( $oldIds[$row->blob_id] );
441  }
442 
443  // Print errors for missing blobs rows
444  foreach ( $oldIds as $blobId => $oldIds2 ) {
445  $this->addError(
446  'restore text',
447  "Error: missing target $cluster/$blobId for two-part ES URL",
448  $oldIds2
449  );
450  }
451  }
452  }
453 
454  private function restoreText( $revIds, $xml ) {
455  global $wgDBname;
456  $tmpDir = wfTempDir();
457 
458  if ( !count( $revIds ) ) {
459  return;
460  }
461 
462  print "Restoring text from XML backup...\n";
463 
464  $revFileName = "$tmpDir/broken-revlist-$wgDBname";
465  $filteredXmlFileName = "$tmpDir/filtered-$wgDBname.xml";
466 
467  // Write revision list
468  if ( !file_put_contents( $revFileName, implode( "\n", $revIds ) ) ) {
469  echo "Error writing revision list, can't restore text\n";
470 
471  return;
472  }
473 
474  // Run mwdumper
475  echo "Filtering XML dump...\n";
476  $exitStatus = 0;
477  passthru( 'mwdumper ' .
478  Shell::escape(
479  "--output=file:$filteredXmlFileName",
480  "--filter=revlist:$revFileName",
481  $xml
482  ), $exitStatus
483  );
484 
485  if ( $exitStatus ) {
486  echo "mwdumper died with exit status $exitStatus\n";
487 
488  return;
489  }
490 
491  $file = fopen( $filteredXmlFileName, 'r' );
492  if ( !$file ) {
493  echo "Unable to open filtered XML file\n";
494 
495  return;
496  }
497 
498  $dbr = wfGetDB( DB_REPLICA );
499  $dbw = wfGetDB( DB_MASTER );
500  $dbr->ping();
501  $dbw->ping();
502 
504  $importer = new WikiImporter(
505  $source,
506  MediaWikiServices::getInstance()->getMainConfig()
507  );
508  $importer->setRevisionCallback( [ $this, 'importRevision' ] );
509  $importer->setNoticeCallback( function ( $msg, $params ) {
510  echo wfMessage( $msg, $params )->text() . "\n";
511  } );
512  $importer->doImport();
513  }
514 
515  private function importRevision( &$revision, &$importer ) {
516  $id = $revision->getID();
517  $content = $revision->getContent( RevisionRecord::RAW );
518  $id = $id ?: '';
519 
520  if ( $content === null ) {
521  echo "Revision $id is broken, we have no content available\n";
522 
523  return;
524  }
525 
526  $text = $content->serialize();
527  if ( $text === '' ) {
528  // This is what happens if the revision was broken at the time the
529  // dump was made. Unfortunately, it also happens if the revision was
530  // legitimately blank, so there's no way to tell the difference. To
531  // be safe, we'll skip it and leave it broken
532 
533  echo "Revision $id is blank in the dump, may have been broken before export\n";
534 
535  return;
536  }
537 
538  if ( !$id ) {
539  // No ID, can't import
540  echo "No id tag in revision, can't import\n";
541 
542  return;
543  }
544 
545  // Find text row again
546  $dbr = wfGetDB( DB_REPLICA );
547  $res = $dbr->selectRow(
548  [ 'slots', 'content' ],
549  [ 'content_address' ],
550  [ 'slot_revision_id' => $id ],
551  __METHOD__,
552  [],
553  [ 'content' => [ 'INNER JOIN', [ 'content_id = slot_content_id' ] ] ]
554  );
555 
556  $blobStore = MediaWikiServices::getInstance()
557  ->getBlobStoreFactory()
558  ->newSqlBlobStore();
559  $oldId = $blobStore->getTextIdFromAddress( $res->content_address );
560 
561  if ( !$oldId ) {
562  echo "Missing revision row for rev_id $id\n";
563  return;
564  }
565 
566  // Compress the text
567  $flags = $blobStore->compressData( $text );
568 
569  // Update the text row
570  $dbw = wfGetDB( DB_MASTER );
571  $dbw->update( 'text',
572  [ 'old_flags' => $flags, 'old_text' => $text ],
573  [ 'old_id' => $oldId ],
574  __METHOD__, [ 'LIMIT' => 1 ]
575  );
576 
577  // Remove it from the unfixed list and add it to the fixed list
578  unset( $this->errors['restore text'][$id] );
579  $this->errors['fixed'][$id] = true;
580  }
581 }
MediaWiki\Shell\Shell
Executes shell commands.
Definition: Shell.php:44
WikiImporter
XML file reader for the page data importer.
Definition: WikiImporter.php:37
CheckStorage
Maintenance script to do various checks on external storage.
Definition: checkStorage.php:46
Revision\RevisionRecord
Page revision base class.
Definition: RevisionRecord.php:46
ExternalStoreDB
DB accessible external objects.
Definition: ExternalStoreDB.php:39
$wgDBname
$wgDBname
Current wiki database name.
Definition: DefaultSettings.php:1990
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:166
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:1230
$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:515
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:2466
$matches
$matches
Definition: NoLocalSettings.php:24
$args
if( $line===false) $args
Definition: mcc.php:124
CheckStorage\addError
addError( $type, $msg, $ids)
Definition: checkStorage.php:389
DB_REPLICA
const DB_REPLICA
Definition: defines.php:25
DB_MASTER
const DB_MASTER
Definition: defines.php:26
CheckStorage\CONCAT_HEADER
const CONCAT_HEADER
Definition: checkStorage.php:47
$content
$content
Definition: router.php:76
$optionsWithoutArgs
global $optionsWithoutArgs
Definition: CommandLineInc.php:28
CheckStorage\restoreText
restoreText( $revIds, $xml)
Definition: checkStorage.php:454
unserialize
unserialize( $serialized)
Definition: ApiMessageTrait.php:146
wfTempDir
wfTempDir()
Tries to get the system directory for temporary files.
Definition: GlobalFunctions.php:1894
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:412
$type
$type
Definition: testCompression.php:52