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