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  // @phan-suppress-next-line PhanSuspiciousBinaryAddLists
133  $flagStats += [ $flags => 0 ];
134  // Increment counter
135  $flagStats[$flags]++;
136 
137  // Not missing
138  unset( $missingTextRows[$row->old_id] );
139 
140  // Check for external or object
141  if ( $flags == '' ) {
142  $flagArray = [];
143  } else {
144  $flagArray = explode( ',', $flags );
145  }
146  if ( in_array( 'external', $flagArray ) ) {
147  $externalRevs[] = $id;
148  } elseif ( in_array( 'object', $flagArray ) ) {
149  $objectRevs[] = $id;
150  }
151 
152  // Check for unrecognised flags
153  if ( $flags == '0' ) {
154  // This is a known bug from 2004
155  // It's safe to just erase the old_flags field
156  if ( $fix ) {
157  $this->addError( 'fixed', "Warning: old_flags set to 0", $id );
158  $dbw = wfGetDB( DB_MASTER );
159  $dbw->ping();
160  $dbw->update( 'text', [ 'old_flags' => '' ],
161  [ 'old_id' => $id ], __METHOD__ );
162  echo "Fixed\n";
163  } else {
164  $this->addError( 'fixable', "Warning: old_flags set to 0", $id );
165  }
166  } elseif ( count( array_diff( $flagArray, $knownFlags ) ) ) {
167  $this->addError( 'unfixable', "Error: invalid flags field \"$flags\"", $id );
168  }
169  }
170 
171  // Output errors for any missing text rows
172  foreach ( $missingTextRows as $oldId => $revIds ) {
173  $this->addError( 'restore revision', "Error: missing text row", $oldId );
174  }
175 
176  // Verify external revisions
177  $externalConcatBlobs = [];
178  $externalNormalBlobs = [];
179  if ( count( $externalRevs ) ) {
180  $res = $dbr->select(
181  'text',
182  [ 'old_id', 'old_flags', 'old_text' ],
183  [ 'old_id' => $externalRevs ],
184  __METHOD__
185  );
186  foreach ( $res as $row ) {
187  $urlParts = explode( '://', $row->old_text, 2 );
188  if ( count( $urlParts ) !== 2 || $urlParts[1] == '' ) {
189  $this->addError( 'restore text', "Error: invalid URL \"{$row->old_text}\"", $row->old_id );
190  continue;
191  }
192  list( $proto, ) = $urlParts;
193  if ( $proto != 'DB' ) {
194  $this->addError(
195  'restore text',
196  "Error: invalid external protocol \"$proto\"",
197  $row->old_id );
198  continue;
199  }
200  $path = explode( '/', $row->old_text );
201  $cluster = $path[2];
202  $id = $path[3];
203  if ( isset( $path[4] ) ) {
204  $externalConcatBlobs[$cluster][$id][] = $row->old_id;
205  } else {
206  $externalNormalBlobs[$cluster][$id][] = $row->old_id;
207  }
208  }
209  }
210 
211  // Check external concat blobs for the right header
212  $this->checkExternalConcatBlobs( $externalConcatBlobs );
213 
214  // Check external normal blobs for existence
215  if ( count( $externalNormalBlobs ) ) {
216  if ( $this->dbStore === null ) {
217  $esFactory = MediaWikiServices::getInstance()->getExternalStoreFactory();
218  $this->dbStore = $esFactory->getStore( 'DB' );
219  }
220  foreach ( $externalConcatBlobs as $cluster => $xBlobIds ) {
221  $blobIds = array_keys( $xBlobIds );
222  $extDb =& $this->dbStore->getReplica( $cluster );
223  $blobsTable = $this->dbStore->getTable( $extDb );
224  $res = $extDb->select( $blobsTable,
225  [ 'blob_id' ],
226  [ 'blob_id' => $blobIds ],
227  __METHOD__
228  );
229  foreach ( $res as $row ) {
230  unset( $xBlobIds[$row->blob_id] );
231  }
232  // Print errors for missing blobs rows
233  foreach ( $xBlobIds as $blobId => $oldId ) {
234  $this->addError(
235  'restore text',
236  "Error: missing target $blobId for one-part ES URL",
237  $oldId );
238  }
239  }
240  }
241 
242  // Check local objects
243  $dbr->ping();
244  $concatBlobs = [];
245  $curIds = [];
246  if ( count( $objectRevs ) ) {
247  $headerLength = 300;
248  $res = $dbr->select(
249  'text',
250  [ 'old_id', 'old_flags', "LEFT(old_text, $headerLength) AS header" ],
251  [ 'old_id' => $objectRevs ],
252  __METHOD__
253  );
254  foreach ( $res as $row ) {
255  $oldId = $row->old_id;
256  $matches = [];
257  if ( !preg_match( '/^O:(\d+):"(\w+)"/', $row->header, $matches ) ) {
258  $this->addError( 'restore text', "Error: invalid object header", $oldId );
259  continue;
260  }
261 
262  $className = strtolower( $matches[2] );
263  if ( strlen( $className ) != $matches[1] ) {
264  $this->addError(
265  'restore text',
266  "Error: invalid object header, wrong class name length",
267  $oldId
268  );
269  continue;
270  }
271 
272  // @phan-suppress-next-line PhanSuspiciousBinaryAddLists
273  $objectStats += [ $className => 0 ];
274  $objectStats[$className]++;
275 
276  switch ( $className ) {
277  case 'concatenatedgziphistoryblob':
278  // Good
279  break;
280  case 'historyblobstub':
281  case 'historyblobcurstub':
282  if ( strlen( $row->header ) == $headerLength ) {
283  $this->addError( 'unfixable', "Error: overlong stub header", $oldId );
284  break;
285  }
286  $stubObj = unserialize( $row->header );
287  if ( !is_object( $stubObj ) ) {
288  $this->addError( 'restore text', "Error: unable to unserialize stub object", $oldId );
289  break;
290  }
291  if ( $className == 'historyblobstub' ) {
292  $concatBlobs[$stubObj->mOldId][] = $oldId;
293  } else {
294  $curIds[$stubObj->mCurId][] = $oldId;
295  }
296  break;
297  default:
298  $this->addError( 'unfixable', "Error: unrecognised object class \"$className\"", $oldId );
299  }
300  }
301  }
302 
303  // Check local concat blob validity
304  $externalConcatBlobs = [];
305  if ( count( $concatBlobs ) ) {
306  $headerLength = 300;
307  $res = $dbr->select(
308  'text',
309  [ 'old_id', 'old_flags', "LEFT(old_text, $headerLength) AS header" ],
310  [ 'old_id' => array_keys( $concatBlobs ) ],
311  __METHOD__
312  );
313  foreach ( $res as $row ) {
314  $flags = explode( ',', $row->old_flags );
315  if ( in_array( 'external', $flags ) ) {
316  // Concat blob is in external storage?
317  if ( in_array( 'object', $flags ) ) {
318  $urlParts = explode( '/', $row->header );
319  if ( $urlParts[0] != 'DB:' ) {
320  $this->addError(
321  'unfixable',
322  "Error: unrecognised external storage type \"{$urlParts[0]}",
323  $row->old_id
324  );
325  } else {
326  $cluster = $urlParts[2];
327  $id = $urlParts[3];
328  if ( !isset( $externalConcatBlobs[$cluster][$id] ) ) {
329  $externalConcatBlobs[$cluster][$id] = [];
330  }
331  $externalConcatBlobs[$cluster][$id] = array_merge(
332  $externalConcatBlobs[$cluster][$id], $concatBlobs[$row->old_id]
333  );
334  }
335  } else {
336  $this->addError(
337  'unfixable',
338  "Error: invalid flags \"{$row->old_flags}\" on concat bulk row {$row->old_id}",
339  $concatBlobs[$row->old_id] );
340  }
341  } elseif ( strcasecmp(
342  substr( $row->header, 0, strlen( self::CONCAT_HEADER ) ),
343  self::CONCAT_HEADER
344  ) ) {
345  $this->addError(
346  'restore text',
347  "Error: Incorrect object header for concat bulk row {$row->old_id}",
348  $concatBlobs[$row->old_id]
349  );
350  }
351 
352  unset( $concatBlobs[$row->old_id] );
353  }
354  }
355 
356  // Check targets of unresolved stubs
357  $this->checkExternalConcatBlobs( $externalConcatBlobs );
358  // next chunk
359  }
360 
361  print "\n\nErrors:\n";
362  foreach ( $this->errors as $name => $errors ) {
363  // @phan-suppress-next-line PhanImpossibleConditionInLoop
364  if ( count( $errors ) ) {
365  $description = $this->errorDescriptions[$name];
366  echo "$description: " . implode( ',', array_keys( $errors ) ) . "\n";
367  }
368  }
369 
370  // @phan-suppress-next-line PhanImpossibleCondition
371  if ( count( $this->errors['restore text'] ) && $fix ) {
372  if ( (string)$xml !== '' ) {
373  $this->restoreText( array_keys( $this->errors['restore text'] ), $xml );
374  } else {
375  echo "Can't fix text, no XML backup specified\n";
376  }
377  }
378 
379  print "\nFlag statistics:\n";
380  $total = array_sum( $flagStats );
381  foreach ( $flagStats as $flag => $count ) {
382  printf( "%-30s %10d %5.2f%%\n", $flag, $count, $count / $total * 100 );
383  }
384  print "\nLocal object statistics:\n";
385  $total = array_sum( $objectStats );
386  foreach ( $objectStats as $className => $count ) {
387  printf( "%-30s %10d %5.2f%%\n", $className, $count, $count / $total * 100 );
388  }
389  }
390 
391  private function addError( $type, $msg, $ids ) {
392  if ( is_array( $ids ) && count( $ids ) == 1 ) {
393  $ids = reset( $ids );
394  }
395  if ( is_array( $ids ) ) {
396  $revIds = [];
397  foreach ( $ids as $id ) {
398  $revIds = array_unique( array_merge( $revIds, $this->oldIdMap[$id] ) );
399  }
400  print "$msg in text rows " . implode( ', ', $ids ) .
401  ", revisions " . implode( ', ', $revIds ) . "\n";
402  } else {
403  $id = $ids;
404  $revIds = $this->oldIdMap[$id];
405  if ( count( $revIds ) == 1 ) {
406  print "$msg in old_id $id, rev_id {$revIds[0]}\n";
407  } else {
408  print "$msg in old_id $id, revisions " . implode( ', ', $revIds ) . "\n";
409  }
410  }
411  $this->errors[$type] += array_flip( $revIds );
412  }
413 
414  private function checkExternalConcatBlobs( $externalConcatBlobs ) {
415  if ( !count( $externalConcatBlobs ) ) {
416  return;
417  }
418 
419  if ( $this->dbStore === null ) {
420  $esFactory = MediaWikiServices::getInstance()->getExternalStoreFactory();
421  $this->dbStore = $esFactory->getStore( 'DB' );
422  }
423 
424  foreach ( $externalConcatBlobs as $cluster => $oldIds ) {
425  $blobIds = array_keys( $oldIds );
426  $extDb =& $this->dbStore->getReplica( $cluster );
427  $blobsTable = $this->dbStore->getTable( $extDb );
428  $headerLength = strlen( self::CONCAT_HEADER );
429  $res = $extDb->select( $blobsTable,
430  [ 'blob_id', "LEFT(blob_text, $headerLength) AS header" ],
431  [ 'blob_id' => $blobIds ],
432  __METHOD__
433  );
434  foreach ( $res as $row ) {
435  if ( strcasecmp( $row->header, self::CONCAT_HEADER ) ) {
436  $this->addError(
437  'restore text',
438  "Error: invalid header on target $cluster/{$row->blob_id} of two-part ES URL",
439  $oldIds[$row->blob_id]
440  );
441  }
442  unset( $oldIds[$row->blob_id] );
443  }
444 
445  // Print errors for missing blobs rows
446  foreach ( $oldIds as $blobId => $oldIds2 ) {
447  $this->addError(
448  'restore text',
449  "Error: missing target $cluster/$blobId for two-part ES URL",
450  $oldIds2
451  );
452  }
453  }
454  }
455 
456  private function restoreText( $revIds, $xml ) {
457  global $wgDBname;
458  $tmpDir = wfTempDir();
459 
460  if ( !count( $revIds ) ) {
461  return;
462  }
463 
464  print "Restoring text from XML backup...\n";
465 
466  $revFileName = "$tmpDir/broken-revlist-$wgDBname";
467  $filteredXmlFileName = "$tmpDir/filtered-$wgDBname.xml";
468 
469  // Write revision list
470  if ( !file_put_contents( $revFileName, implode( "\n", $revIds ) ) ) {
471  echo "Error writing revision list, can't restore text\n";
472 
473  return;
474  }
475 
476  // Run mwdumper
477  echo "Filtering XML dump...\n";
478  $exitStatus = 0;
479  passthru( 'mwdumper ' .
480  Shell::escape(
481  "--output=file:$filteredXmlFileName",
482  "--filter=revlist:$revFileName",
483  $xml
484  ), $exitStatus
485  );
486 
487  if ( $exitStatus ) {
488  echo "mwdumper died with exit status $exitStatus\n";
489 
490  return;
491  }
492 
493  $file = fopen( $filteredXmlFileName, 'r' );
494  if ( !$file ) {
495  echo "Unable to open filtered XML file\n";
496 
497  return;
498  }
499 
500  $dbr = wfGetDB( DB_REPLICA );
501  $dbw = wfGetDB( DB_MASTER );
502  $dbr->ping();
503  $dbw->ping();
504 
506  $importer = new WikiImporter(
507  $source,
508  MediaWikiServices::getInstance()->getMainConfig()
509  );
510  $importer->setRevisionCallback( [ $this, 'importRevision' ] );
511  $importer->setNoticeCallback( function ( $msg, $params ) {
512  echo wfMessage( $msg, $params )->text() . "\n";
513  } );
514  $importer->doImport();
515  }
516 
517  private function importRevision( &$revision, &$importer ) {
518  $id = $revision->getID();
519  $content = $revision->getContent( RevisionRecord::RAW );
520  $id = $id ?: '';
521 
522  if ( $content === null ) {
523  echo "Revision $id is broken, we have no content available\n";
524 
525  return;
526  }
527 
528  $text = $content->serialize();
529  if ( $text === '' ) {
530  // This is what happens if the revision was broken at the time the
531  // dump was made. Unfortunately, it also happens if the revision was
532  // legitimately blank, so there's no way to tell the difference. To
533  // be safe, we'll skip it and leave it broken
534 
535  echo "Revision $id is blank in the dump, may have been broken before export\n";
536 
537  return;
538  }
539 
540  if ( !$id ) {
541  // No ID, can't import
542  echo "No id tag in revision, can't import\n";
543 
544  return;
545  }
546 
547  // Find text row again
548  $dbr = wfGetDB( DB_REPLICA );
549  $res = $dbr->selectRow(
550  [ 'slots', 'content' ],
551  [ 'content_address' ],
552  [ 'slot_revision_id' => $id ],
553  __METHOD__,
554  [],
555  [ 'content' => [ 'INNER JOIN', [ 'content_id = slot_content_id' ] ] ]
556  );
557 
558  $blobStore = MediaWikiServices::getInstance()
559  ->getBlobStoreFactory()
560  ->newSqlBlobStore();
561  $oldId = $blobStore->getTextIdFromAddress( $res->content_address );
562 
563  if ( !$oldId ) {
564  echo "Missing revision row for rev_id $id\n";
565  return;
566  }
567 
568  // Compress the text
569  $flags = $blobStore->compressData( $text );
570 
571  // Update the text row
572  $dbw = wfGetDB( DB_MASTER );
573  $dbw->update( 'text',
574  [ 'old_flags' => $flags, 'old_text' => $text ],
575  [ 'old_id' => $oldId ],
576  __METHOD__, [ 'LIMIT' => 1 ]
577  );
578 
579  // Remove it from the unfixed list and add it to the fixed list
580  unset( $this->errors['restore text'][$id] );
581  $this->errors['fixed'][$id] = true;
582  }
583 }
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:1989
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:163
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:1220
$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:517
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:2459
$matches
$matches
Definition: NoLocalSettings.php:24
$args
if( $line===false) $args
Definition: mcc.php:124
CheckStorage\addError
addError( $type, $msg, $ids)
Definition: checkStorage.php:391
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:26
CheckStorage\restoreText
restoreText( $revIds, $xml)
Definition: checkStorage.php:456
unserialize
unserialize( $serialized)
Definition: ApiMessageTrait.php:146
wfTempDir
wfTempDir()
Tries to get the system directory for temporary files.
Definition: GlobalFunctions.php:1878
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:414
$type
$type
Definition: testCompression.php:52