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\MediaWikiServices
;
25 use MediaWiki\Shell\Shell
;
27 if ( !defined( 'MEDIAWIKI' ) ) {
28 $optionsWithoutArgs = [ 'fix' ];
29 require_once __DIR__
. '/../commandLine.inc';
31 $cs = new CheckStorage
;
32 $fix = isset( $options['fix'] );
33 $xml = $args[0] ??
false;
34 $cs->check( $fix, $xml );
37 // ----------------------------------------------------------------------------------
40 * Maintenance script to do various checks on external storage.
42 * @fixme this should extend the base Maintenance class
43 * @ingroup Maintenance ExternalStorage
46 const CONCAT_HEADER
= 'O:27:"concatenatedgziphistoryblob"';
47 public $oldIdMap, $errors;
48 /** @var ExternalStoreDB */
49 public $dbStore = null;
51 public $errorDescriptions = [
52 'restore text' => 'Damaged text, need to be restored from a backup',
53 'restore revision' => 'Damaged revision row, need to be restored from a backup',
54 'unfixable' => 'Unexpected errors with no automated fixing method',
55 'fixed' => 'Errors already fixed',
56 'fixable' => 'Errors which would already be fixed if --fix was specified',
59 function check( $fix = false, $xml = '' ) {
60 global $wgMultiContentRevisionSchemaMigrationStage;
62 $dbr = wfGetDB( DB_REPLICA
);
64 print "Checking, will fix errors if possible...\n";
66 print "Checking...\n";
68 $maxRevId = $dbr->selectField( 'revision', 'MAX(rev_id)', '', __METHOD__
);
72 $knownFlags = [ 'external', 'gzip', 'object', 'utf-8' ];
75 'restore revision' => [],
81 for ( $chunkStart = 1; $chunkStart < $maxRevId; $chunkStart +
= $chunkSize ) {
82 $chunkEnd = $chunkStart +
$chunkSize - 1;
83 // print "$chunkStart of $maxRevId\n";
88 // Fetch revision rows
89 if ( $wgMultiContentRevisionSchemaMigrationStage & SCHEMA_COMPAT_READ_OLD
) {
90 $res = $dbr->select( 'revision', [ 'rev_id', 'rev_text_id' ],
91 [ "rev_id BETWEEN $chunkStart AND $chunkEnd" ], __METHOD__
);
92 foreach ( $res as $row ) {
93 if ( !isset( $this->oldIdMap
[ $row->rev_text_id
] ) ) {
94 $this->oldIdMap
[ $row->rev_text_id
] = [ $row->rev_id
];
95 } elseif ( !in_array( $row->rev_id
, $this->oldIdMap
[ $row->rev_text_id
] ) ) {
96 $this->oldIdMap
[ $row->rev_text_id
][] = $row->rev_id
;
101 [ 'slots', 'content' ],
102 [ 'slot_revision_id', 'content_address' ],
103 [ "slot_revision_id BETWEEN $chunkStart AND $chunkEnd" ],
106 [ 'content' => [ 'INNER JOIN', [ 'content_id = slot_content_id' ] ] ]
108 $blobStore = MediaWikiServices
::getInstance()->getBlobStore();
109 foreach ( $res as $row ) {
110 $textId = $blobStore->getTextIdFromAddress( $row->content_address
);
112 if ( !isset( $this->oldIdMap
[$textId] ) ) {
113 $this->oldIdMap
[ $textId ] = [ $row->slot_revision_id
];
114 } elseif ( !in_array( $row->slot_revision_id
, $this->oldIdMap
[$textId] ) ) {
115 $this->oldIdMap
[ $textId ][] = $row->slot_revision_id
;
121 if ( !count( $this->oldIdMap
) ) {
126 $missingTextRows = $this->oldIdMap
;
131 [ 'old_id', 'old_flags' ],
132 [ 'old_id' => array_keys( $this->oldIdMap
) ],
135 foreach ( $res as $row ) {
139 $flags = $row->old_flags
;
142 // Create flagStats row if it doesn't exist
143 $flagStats = $flagStats +
[ $flags => 0 ];
145 $flagStats[$flags]++
;
148 unset( $missingTextRows[$row->old_id
] );
150 // Check for external or object
151 if ( $flags == '' ) {
154 $flagArray = explode( ',', $flags );
156 if ( in_array( 'external', $flagArray ) ) {
157 $externalRevs[] = $id;
158 } elseif ( in_array( 'object', $flagArray ) ) {
162 // Check for unrecognised flags
163 if ( $flags == '0' ) {
164 // This is a known bug from 2004
165 // It's safe to just erase the old_flags field
167 $this->addError( 'fixed', "Warning: old_flags set to 0", $id );
168 $dbw = wfGetDB( DB_MASTER
);
170 $dbw->update( 'text', [ 'old_flags' => '' ],
171 [ 'old_id' => $id ], __METHOD__
);
174 $this->addError( 'fixable', "Warning: old_flags set to 0", $id );
176 } elseif ( count( array_diff( $flagArray, $knownFlags ) ) ) {
177 $this->addError( 'unfixable', "Error: invalid flags field \"$flags\"", $id );
181 // Output errors for any missing text rows
182 foreach ( $missingTextRows as $oldId => $revIds ) {
183 $this->addError( 'restore revision', "Error: missing text row", $oldId );
186 // Verify external revisions
187 $externalConcatBlobs = [];
188 $externalNormalBlobs = [];
189 if ( count( $externalRevs ) ) {
192 [ 'old_id', 'old_flags', 'old_text' ],
193 [ 'old_id' => $externalRevs ],
196 foreach ( $res as $row ) {
197 $urlParts = explode( '://', $row->old_text
, 2 );
198 if ( count( $urlParts ) !== 2 ||
$urlParts[1] == '' ) {
199 $this->addError( 'restore text', "Error: invalid URL \"{$row->old_text}\"", $row->old_id
);
202 list( $proto, ) = $urlParts;
203 if ( $proto != 'DB' ) {
206 "Error: invalid external protocol \"$proto\"",
210 $path = explode( '/', $row->old_text
);
213 if ( isset( $path[4] ) ) {
214 $externalConcatBlobs[$cluster][$id][] = $row->old_id
;
216 $externalNormalBlobs[$cluster][$id][] = $row->old_id
;
221 // Check external concat blobs for the right header
222 $this->checkExternalConcatBlobs( $externalConcatBlobs );
224 // Check external normal blobs for existence
225 if ( count( $externalNormalBlobs ) ) {
226 if ( is_null( $this->dbStore
) ) {
227 $esFactory = MediaWikiServices
::getInstance()->getExternalStoreFactory();
228 $this->dbStore
= $esFactory->getStore( 'DB' );
230 foreach ( $externalConcatBlobs as $cluster => $xBlobIds ) {
231 $blobIds = array_keys( $xBlobIds );
232 $extDb =& $this->dbStore
->getSlave( $cluster );
233 $blobsTable = $this->dbStore
->getTable( $extDb );
234 $res = $extDb->select( $blobsTable,
236 [ 'blob_id' => $blobIds ],
239 foreach ( $res as $row ) {
240 unset( $xBlobIds[$row->blob_id
] );
242 // Print errors for missing blobs rows
243 foreach ( $xBlobIds as $blobId => $oldId ) {
246 "Error: missing target $blobId for one-part ES URL",
252 // Check local objects
256 if ( count( $objectRevs ) ) {
260 [ 'old_id', 'old_flags', "LEFT(old_text, $headerLength) AS header" ],
261 [ 'old_id' => $objectRevs ],
264 foreach ( $res as $row ) {
265 $oldId = $row->old_id
;
267 if ( !preg_match( '/^O:(\d+):"(\w+)"/', $row->header
, $matches ) ) {
268 $this->addError( 'restore text', "Error: invalid object header", $oldId );
272 $className = strtolower( $matches[2] );
273 if ( strlen( $className ) != $matches[1] ) {
276 "Error: invalid object header, wrong class name length",
282 $objectStats = $objectStats +
[ $className => 0 ];
283 $objectStats[$className]++
;
285 switch ( $className ) {
286 case 'concatenatedgziphistoryblob':
289 case 'historyblobstub':
290 case 'historyblobcurstub':
291 if ( strlen( $row->header
) == $headerLength ) {
292 $this->addError( 'unfixable', "Error: overlong stub header", $oldId );
295 $stubObj = unserialize( $row->header
);
296 if ( !is_object( $stubObj ) ) {
297 $this->addError( 'restore text', "Error: unable to unserialize stub object", $oldId );
300 if ( $className == 'historyblobstub' ) {
301 $concatBlobs[$stubObj->mOldId
][] = $oldId;
303 $curIds[$stubObj->mCurId
][] = $oldId;
307 $this->addError( 'unfixable', "Error: unrecognised object class \"$className\"", $oldId );
312 // Check local concat blob validity
313 $externalConcatBlobs = [];
314 if ( count( $concatBlobs ) ) {
318 [ 'old_id', 'old_flags', "LEFT(old_text, $headerLength) AS header" ],
319 [ 'old_id' => array_keys( $concatBlobs ) ],
322 foreach ( $res as $row ) {
323 $flags = explode( ',', $row->old_flags
);
324 if ( in_array( 'external', $flags ) ) {
325 // Concat blob is in external storage?
326 if ( in_array( 'object', $flags ) ) {
327 $urlParts = explode( '/', $row->header
);
328 if ( $urlParts[0] != 'DB:' ) {
331 "Error: unrecognised external storage type \"{$urlParts[0]}",
335 $cluster = $urlParts[2];
337 if ( !isset( $externalConcatBlobs[$cluster][$id] ) ) {
338 $externalConcatBlobs[$cluster][$id] = [];
340 $externalConcatBlobs[$cluster][$id] = array_merge(
341 $externalConcatBlobs[$cluster][$id], $concatBlobs[$row->old_id
]
347 "Error: invalid flags \"{$row->old_flags}\" on concat bulk row {$row->old_id}",
348 $concatBlobs[$row->old_id
] );
350 } elseif ( strcasecmp(
351 substr( $row->header
, 0, strlen( self
::CONCAT_HEADER
) ),
356 "Error: Incorrect object header for concat bulk row {$row->old_id}",
357 $concatBlobs[$row->old_id
]
361 unset( $concatBlobs[$row->old_id
] );
365 // Check targets of unresolved stubs
366 $this->checkExternalConcatBlobs( $externalConcatBlobs );
370 print "\n\nErrors:\n";
371 foreach ( $this->errors
as $name => $errors ) {
372 if ( count( $errors ) ) {
373 $description = $this->errorDescriptions
[$name];
374 echo "$description: " . implode( ',', array_keys( $errors ) ) . "\n";
378 if ( count( $this->errors
['restore text'] ) && $fix ) {
379 if ( (string)$xml !== '' ) {
380 $this->restoreText( array_keys( $this->errors
['restore text'] ), $xml );
382 echo "Can't fix text, no XML backup specified\n";
386 print "\nFlag statistics:\n";
387 $total = array_sum( $flagStats );
388 foreach ( $flagStats as $flag => $count ) {
389 printf( "%-30s %10d %5.2f%%\n", $flag, $count, $count / $total * 100 );
391 print "\nLocal object statistics:\n";
392 $total = array_sum( $objectStats );
393 foreach ( $objectStats as $className => $count ) {
394 printf( "%-30s %10d %5.2f%%\n", $className, $count, $count / $total * 100 );
398 function addError( $type, $msg, $ids ) {
399 if ( is_array( $ids ) && count( $ids ) == 1 ) {
400 $ids = reset( $ids );
402 if ( is_array( $ids ) ) {
404 foreach ( $ids as $id ) {
405 $revIds = array_unique( array_merge( $revIds, $this->oldIdMap
[$id] ) );
407 print "$msg in text rows " . implode( ', ', $ids ) .
408 ", revisions " . implode( ', ', $revIds ) . "\n";
411 $revIds = $this->oldIdMap
[$id];
412 if ( count( $revIds ) == 1 ) {
413 print "$msg in old_id $id, rev_id {$revIds[0]}\n";
415 print "$msg in old_id $id, revisions " . implode( ', ', $revIds ) . "\n";
418 $this->errors
[$type] = $this->errors
[$type] +
array_flip( $revIds );
421 function checkExternalConcatBlobs( $externalConcatBlobs ) {
422 if ( !count( $externalConcatBlobs ) ) {
426 if ( is_null( $this->dbStore
) ) {
427 $esFactory = MediaWikiServices
::getInstance()->getExternalStoreFactory();
428 $this->dbStore
= $esFactory->getStore( 'DB' );
431 foreach ( $externalConcatBlobs as $cluster => $oldIds ) {
432 $blobIds = array_keys( $oldIds );
433 $extDb =& $this->dbStore
->getSlave( $cluster );
434 $blobsTable = $this->dbStore
->getTable( $extDb );
435 $headerLength = strlen( self
::CONCAT_HEADER
);
436 $res = $extDb->select( $blobsTable,
437 [ 'blob_id', "LEFT(blob_text, $headerLength) AS header" ],
438 [ 'blob_id' => $blobIds ],
441 foreach ( $res as $row ) {
442 if ( strcasecmp( $row->header
, self
::CONCAT_HEADER
) ) {
445 "Error: invalid header on target $cluster/{$row->blob_id} of two-part ES URL",
446 $oldIds[$row->blob_id
]
449 unset( $oldIds[$row->blob_id
] );
452 // Print errors for missing blobs rows
453 foreach ( $oldIds as $blobId => $oldIds2 ) {
456 "Error: missing target $cluster/$blobId for two-part ES URL",
463 function restoreText( $revIds, $xml ) {
465 $tmpDir = wfTempDir();
467 if ( !count( $revIds ) ) {
471 print "Restoring text from XML backup...\n";
473 $revFileName = "$tmpDir/broken-revlist-$wgDBname";
474 $filteredXmlFileName = "$tmpDir/filtered-$wgDBname.xml";
476 // Write revision list
477 if ( !file_put_contents( $revFileName, implode( "\n", $revIds ) ) ) {
478 echo "Error writing revision list, can't restore text\n";
484 echo "Filtering XML dump...\n";
486 passthru( 'mwdumper ' .
488 "--output=file:$filteredXmlFileName",
489 "--filter=revlist:$revFileName",
495 echo "mwdumper died with exit status $exitStatus\n";
500 $file = fopen( $filteredXmlFileName, 'r' );
502 echo "Unable to open filtered XML file\n";
507 $dbr = wfGetDB( DB_REPLICA
);
508 $dbw = wfGetDB( DB_MASTER
);
512 $source = new ImportStreamSource( $file );
513 $importer = new WikiImporter(
515 MediaWikiServices
::getInstance()->getMainConfig()
517 $importer->setRevisionCallback( [ $this, 'importRevision' ] );
518 $importer->setNoticeCallback( function ( $msg, $params ) {
519 echo wfMessage( $msg, $params )->text() . "\n";
521 $importer->doImport();
524 function importRevision( &$revision, &$importer ) {
525 $id = $revision->getID();
526 $content = $revision->getContent( Revision
::RAW
);
529 if ( $content === null ) {
530 echo "Revision $id is broken, we have no content available\n";
535 $text = $content->serialize();
536 if ( $text === '' ) {
537 // This is what happens if the revision was broken at the time the
538 // dump was made. Unfortunately, it also happens if the revision was
539 // legitimately blank, so there's no way to tell the difference. To
540 // be safe, we'll skip it and leave it broken
542 echo "Revision $id is blank in the dump, may have been broken before export\n";
548 // No ID, can't import
549 echo "No id tag in revision, can't import\n";
554 // Find text row again
555 $dbr = wfGetDB( DB_REPLICA
);
556 $oldId = $dbr->selectField( 'revision', 'rev_text_id', [ 'rev_id' => $id ], __METHOD__
);
558 echo "Missing revision row for rev_id $id\n";
564 $flags = Revision
::compressRevisionText( $text );
566 // Update the text row
567 $dbw = wfGetDB( DB_MASTER
);
568 $dbw->update( 'text',
569 [ 'old_flags' => $flags, 'old_text' => $text ],
570 [ 'old_id' => $oldId ],
571 __METHOD__
, [ 'LIMIT' => 1 ]
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;