5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @ingroup Maintenance ExternalStorage
24 use MediaWiki\Permissions\UltimateAuthority
;
25 use MediaWiki\Shell\Shell
;
26 use MediaWiki\User\User
;
28 // @codeCoverageIgnoreStart
29 require_once __DIR__
. '/../Maintenance.php';
30 // @codeCoverageIgnoreEnd
32 // ----------------------------------------------------------------------------------
35 * Maintenance script to do various checks on external storage.
37 * @fixme this should extend the base Maintenance class
38 * @ingroup Maintenance ExternalStorage
40 class CheckStorage
extends Maintenance
{
41 private const CONCAT_HEADER
= 'O:27:"concatenatedgziphistoryblob"';
43 public array $oldIdMap;
46 /** @var ExternalStoreDB */
47 public $dbStore = null;
49 public function __construct() {
50 parent
::__construct();
52 $this->addOption( 'fix', 'Fix errors if possible' );
53 $this->addArg( 'xml', 'Path to an XML dump', false );
56 public function execute() {
57 $fix = $this->hasOption( 'fix' );
58 $xml = $this->getArg( 'xml', false );
59 $this->check( $fix, $xml );
63 public $errorDescriptions = [
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',
71 public function check( $fix = false, $xml = '' ) {
72 $dbr = $this->getReplicaDB();
74 print "Checking, will fix errors if possible...\n";
76 print "Checking...\n";
78 $maxRevId = $dbr->newSelectQueryBuilder()
79 ->select( 'MAX(rev_id)' )
81 ->caller( __METHOD__
)->fetchField();
85 $knownFlags = [ 'external', 'gzip', 'object', 'utf-8' ];
88 'restore revision' => [],
94 for ( $chunkStart = 1; $chunkStart < $maxRevId; $chunkStart +
= $chunkSize ) {
95 $chunkEnd = $chunkStart +
$chunkSize - 1;
96 // print "$chunkStart of $maxRevId\n";
101 // Fetch revision rows
102 $res = $dbr->newSelectQueryBuilder()
103 ->select( [ 'slot_revision_id', 'content_address' ] )
105 ->join( 'content', null, 'content_id = slot_content_id' )
107 $dbr->expr( 'slot_revision_id', '>=', $chunkStart ),
108 $dbr->expr( 'slot_revision_id', '<=', $chunkEnd ),
110 ->caller( __METHOD__
)->fetchResultSet();
111 /** @var \MediaWiki\Storage\SqlBlobStore $blobStore */
112 $blobStore = $this->getServiceContainer()->getBlobStore();
113 '@phan-var \MediaWiki\Storage\SqlBlobStore $blobStore';
114 foreach ( $res as $row ) {
115 $textId = $blobStore->getTextIdFromAddress( $row->content_address
);
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
;
125 if ( !count( $this->oldIdMap
) ) {
130 $missingTextRows = $this->oldIdMap
;
133 $res = $dbr->newSelectQueryBuilder()
134 ->select( [ 'old_id', 'old_flags' ] )
136 ->where( [ 'old_id' => array_keys( $this->oldIdMap
) ] )
137 ->caller( __METHOD__
)->fetchResultSet();
138 foreach ( $res as $row ) {
142 $flags = $row->old_flags
;
145 // Create flagStats row if it doesn't exist
146 $flagStats +
= [ $flags => 0 ];
148 $flagStats[$flags]++
;
151 unset( $missingTextRows[$row->old_id
] );
153 // Check for external or object
154 if ( $flags == '' ) {
157 $flagArray = explode( ',', $flags );
159 if ( in_array( 'external', $flagArray ) ) {
160 $externalRevs[] = $id;
161 } elseif ( in_array( 'object', $flagArray ) ) {
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
170 $this->addError( 'fixed', "Warning: old_flags set to 0", $id );
171 $dbw = $this->getPrimaryDB();
173 $dbw->newUpdateQueryBuilder()
175 ->set( [ 'old_flags' => '' ] )
176 ->where( [ 'old_id' => $id ] )
177 ->caller( __METHOD__
)
181 $this->addError( 'fixable', "Warning: old_flags set to 0", $id );
183 } elseif ( count( array_diff( $flagArray, $knownFlags ) ) ) {
184 $this->addError( 'unfixable', "Error: invalid flags field \"$flags\"", $id );
188 // Output errors for any missing text rows
189 foreach ( $missingTextRows as $oldId => $revIds ) {
190 $this->addError( 'restore revision', "Error: missing text row", $oldId );
193 // Verify external revisions
194 $externalConcatBlobs = [];
195 $externalNormalBlobs = [];
196 if ( count( $externalRevs ) ) {
197 $res = $dbr->newSelectQueryBuilder()
198 ->select( [ 'old_id', 'old_flags', 'old_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
);
208 [ $proto, ] = $urlParts;
209 if ( $proto != 'DB' ) {
212 "Error: invalid external protocol \"$proto\"",
216 $path = explode( '/', $row->old_text
);
219 if ( isset( $path[4] ) ) {
220 $externalConcatBlobs[$cluster][$id][] = $row->old_id
;
222 $externalNormalBlobs[$cluster][$id][] = $row->old_id
;
227 // Check external concat blobs for the right header
228 $this->checkExternalConcatBlobs( $externalConcatBlobs );
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' );
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
] );
248 // Print errors for missing blobs rows
249 foreach ( $xBlobIds as $blobId => $oldId ) {
252 "Error: missing target $blobId for one-part ES URL",
258 // Check local objects
262 if ( count( $objectRevs ) ) {
264 $res = $dbr->newSelectQueryBuilder()
265 ->select( [ 'old_id', 'old_flags', "LEFT(old_text, $headerLength) AS header" ] )
267 ->where( [ 'old_id' => $objectRevs ] )
268 ->caller( __METHOD__
)->fetchResultSet();
269 foreach ( $res as $row ) {
270 $oldId = $row->old_id
;
272 if ( !preg_match( '/^O:(\d+):"(\w+)"/', $row->header
, $matches ) ) {
273 $this->addError( 'restore text', "Error: invalid object header", $oldId );
277 $className = strtolower( $matches[2] );
278 if ( strlen( $className ) != $matches[1] ) {
281 "Error: invalid object header, wrong class name length",
287 $objectStats +
= [ $className => 0 ];
288 $objectStats[$className]++
;
290 switch ( $className ) {
291 case 'concatenatedgziphistoryblob':
294 case 'historyblobstub':
295 case 'historyblobcurstub':
296 if ( strlen( $row->header
) == $headerLength ) {
297 $this->addError( 'unfixable', "Error: overlong stub header", $oldId );
300 $stubObj = unserialize( $row->header
);
301 if ( !is_object( $stubObj ) ) {
302 $this->addError( 'restore text', "Error: unable to unserialize stub object", $oldId );
305 if ( $className == 'historyblobstub' ) {
306 $concatBlobs[$stubObj->getLocation()][] = $oldId;
308 $curIds[$stubObj->mCurId
][] = $oldId;
312 $this->addError( 'unfixable', "Error: unrecognised object class \"$className\"", $oldId );
317 // Check local concat blob validity
318 $externalConcatBlobs = [];
319 if ( count( $concatBlobs ) ) {
321 $res = $dbr->newSelectQueryBuilder()
322 ->select( [ 'old_id', 'old_flags', "LEFT(old_text, $headerLength) AS header" ] )
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:' ) {
335 "Error: unrecognised external storage type \"{$urlParts[0]}",
339 $cluster = $urlParts[2];
341 if ( !isset( $externalConcatBlobs[$cluster][$id] ) ) {
342 $externalConcatBlobs[$cluster][$id] = [];
344 $externalConcatBlobs[$cluster][$id] = array_merge(
345 $externalConcatBlobs[$cluster][$id], $concatBlobs[$row->old_id
]
351 "Error: invalid flags \"{$row->old_flags}\" on concat bulk row {$row->old_id}",
352 $concatBlobs[$row->old_id
] );
354 } elseif ( strcasecmp(
355 substr( $row->header
, 0, strlen( self
::CONCAT_HEADER
) ),
360 "Error: Incorrect object header for concat bulk row {$row->old_id}",
361 $concatBlobs[$row->old_id
]
365 unset( $concatBlobs[$row->old_id
] );
369 // Check targets of unresolved stubs
370 $this->checkExternalConcatBlobs( $externalConcatBlobs );
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";
382 if ( count( $this->errors
['restore text'] ) && $fix ) {
383 if ( (string)$xml !== '' ) {
384 $this->restoreText( array_keys( $this->errors
['restore text'] ), $xml );
386 echo "Can't fix text, no XML backup specified\n";
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 );
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 );
402 private function addError( $type, $msg, $ids ) {
403 if ( is_array( $ids ) && count( $ids ) == 1 ) {
404 $ids = reset( $ids );
406 if ( is_array( $ids ) ) {
408 foreach ( $ids as $id ) {
409 $revIds = array_unique( array_merge( $revIds, $this->oldIdMap
[$id] ) );
411 print "$msg in text rows " . implode( ', ', $ids ) .
412 ", revisions " . implode( ', ', $revIds ) . "\n";
415 $revIds = $this->oldIdMap
[$id];
416 if ( count( $revIds ) == 1 ) {
417 print "$msg in old_id $id, rev_id {$revIds[0]}\n";
419 print "$msg in old_id $id, revisions " . implode( ', ', $revIds ) . "\n";
422 $this->errors
[$type] +
= array_fill_keys( $revIds, true );
425 private function checkExternalConcatBlobs( $externalConcatBlobs ) {
426 if ( !count( $externalConcatBlobs ) ) {
430 if ( $this->dbStore
=== null ) {
431 $esFactory = $this->getServiceContainer()->getExternalStoreFactory();
432 $this->dbStore
= $esFactory->getStore( 'DB' );
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
) ) {
449 "Error: invalid header on target $cluster/{$row->blob_id} of two-part ES URL",
450 $oldIds[$row->blob_id
]
453 unset( $oldIds[$row->blob_id
] );
456 // Print errors for missing blobs rows
457 foreach ( $oldIds as $blobId => $oldIds2 ) {
460 "Error: missing target $cluster/$blobId for two-part ES URL",
467 private function restoreText( $revIds, $xml ) {
469 $tmpDir = wfTempDir();
471 if ( !count( $revIds ) ) {
475 print "Restoring text from XML backup...\n";
477 $revFileName = "$tmpDir/broken-revlist-$wgDBname";
478 $filteredXmlFileName = "$tmpDir/filtered-$wgDBname.xml";
480 // Write revision list
481 if ( !file_put_contents( $revFileName, implode( "\n", $revIds ) ) ) {
482 echo "Error writing revision list, can't restore text\n";
488 echo "Filtering XML dump...\n";
490 // phpcs:ignore MediaWiki.Usage.ForbiddenFunctions.passthru
491 passthru( 'mwdumper ' .
493 "--output=file:$filteredXmlFileName",
494 "--filter=revlist:$revFileName",
500 echo "mwdumper died with exit status $exitStatus\n";
505 $file = fopen( $filteredXmlFileName, 'r' );
507 echo "Unable to open filtered XML file\n";
512 $dbr = $this->getReplicaDB();
513 $dbw = $this->getPrimaryDB();
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";
526 $importer->doImport();
530 * @param WikiRevision $revision
532 public function importRevision( $revision ) {
533 $id = $revision->getID();
534 $content = $revision->getContent();
537 if ( $content === null ) {
538 echo "Revision $id is broken, we have no content available\n";
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
550 echo "Revision $id is blank in the dump, may have been broken before export\n";
556 // No ID, can't import
557 echo "No id tag in revision, can't import\n";
562 // Find text row again
563 $dbr = $this->getReplicaDB();
564 $res = $dbr->newSelectQueryBuilder()
565 ->select( [ 'content_address' ] )
567 ->join( 'content', null, 'content_id = slot_content_id' )
568 ->where( [ 'slot_revision_id' => $id ] )
569 ->caller( __METHOD__
)->fetchRow();
571 $blobStore = $this->getServiceContainer()
572 ->getBlobStoreFactory()
574 $oldId = $blobStore->getTextIdFromAddress( $res->content_address
);
577 echo "Missing revision row for rev_id $id\n";
582 $flags = $blobStore->compressData( $text );
584 // Update the text row
585 $dbw = $this->getPrimaryDB();
586 $dbw->newUpdateQueryBuilder()
588 ->set( [ 'old_flags' => $flags, 'old_text' => $text ] )
589 ->where( [ 'old_id' => $oldId ] )
590 ->caller( __METHOD__
)
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;
600 // @codeCoverageIgnoreStart
601 $maintClass = CheckStorage
::class;
602 require_once RUN_MAINTENANCE_IF_MAIN
;
603 // @codeCoverageIgnoreEnd