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\Revision\RevisionRecord
;
26 use MediaWiki\Shell\Shell
;
28 if ( !defined( 'MEDIAWIKI' ) ) {
29 $optionsWithoutArgs = [ 'fix' ];
30 require_once __DIR__
. '/../commandLine.inc';
32 $cs = new CheckStorage
;
33 $fix = isset( $options['fix'] );
34 $xml = $args[0] ??
false;
35 $cs->check( $fix, $xml );
38 // ----------------------------------------------------------------------------------
41 * Maintenance script to do various checks on external storage.
43 * @fixme this should extend the base Maintenance class
44 * @ingroup Maintenance ExternalStorage
47 const CONCAT_HEADER
= 'O:27:"concatenatedgziphistoryblob"';
48 public $oldIdMap, $errors;
49 /** @var ExternalStoreDB */
50 public $dbStore = null;
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',
60 function check( $fix = false, $xml = '' ) {
61 global $wgMultiContentRevisionSchemaMigrationStage;
63 $dbr = wfGetDB( DB_REPLICA
);
65 print "Checking, will fix errors if possible...\n";
67 print "Checking...\n";
69 $maxRevId = $dbr->selectField( 'revision', 'MAX(rev_id)', '', __METHOD__
);
73 $knownFlags = [ 'external', 'gzip', 'object', 'utf-8' ];
76 'restore revision' => [],
82 for ( $chunkStart = 1; $chunkStart < $maxRevId; $chunkStart +
= $chunkSize ) {
83 $chunkEnd = $chunkStart +
$chunkSize - 1;
84 // print "$chunkStart of $maxRevId\n";
89 // Fetch revision rows
90 if ( $wgMultiContentRevisionSchemaMigrationStage & SCHEMA_COMPAT_READ_OLD
) {
91 $res = $dbr->select( 'revision', [ 'rev_id', 'rev_text_id' ],
92 [ "rev_id BETWEEN $chunkStart AND $chunkEnd" ], __METHOD__
);
93 foreach ( $res as $row ) {
94 if ( !isset( $this->oldIdMap
[ $row->rev_text_id
] ) ) {
95 $this->oldIdMap
[ $row->rev_text_id
] = [ $row->rev_id
];
96 } elseif ( !in_array( $row->rev_id
, $this->oldIdMap
[ $row->rev_text_id
] ) ) {
97 $this->oldIdMap
[ $row->rev_text_id
][] = $row->rev_id
;
102 [ 'slots', 'content' ],
103 [ 'slot_revision_id', 'content_address' ],
104 [ "slot_revision_id BETWEEN $chunkStart AND $chunkEnd" ],
107 [ 'content' => [ 'INNER JOIN', [ 'content_id = slot_content_id' ] ] ]
109 $blobStore = MediaWikiServices
::getInstance()->getBlobStore();
110 foreach ( $res as $row ) {
111 $textId = $blobStore->getTextIdFromAddress( $row->content_address
);
113 if ( !isset( $this->oldIdMap
[$textId] ) ) {
114 $this->oldIdMap
[ $textId ] = [ $row->slot_revision_id
];
115 } elseif ( !in_array( $row->slot_revision_id
, $this->oldIdMap
[$textId] ) ) {
116 $this->oldIdMap
[ $textId ][] = $row->slot_revision_id
;
122 if ( !count( $this->oldIdMap
) ) {
127 $missingTextRows = $this->oldIdMap
;
132 [ 'old_id', 'old_flags' ],
133 [ 'old_id' => array_keys( $this->oldIdMap
) ],
136 foreach ( $res as $row ) {
140 $flags = $row->old_flags
;
143 // Create flagStats row if it doesn't exist
144 $flagStats = $flagStats +
[ $flags => 0 ];
146 $flagStats[$flags]++
;
149 unset( $missingTextRows[$row->old_id
] );
151 // Check for external or object
152 if ( $flags == '' ) {
155 $flagArray = explode( ',', $flags );
157 if ( in_array( 'external', $flagArray ) ) {
158 $externalRevs[] = $id;
159 } elseif ( in_array( 'object', $flagArray ) ) {
163 // Check for unrecognised flags
164 if ( $flags == '0' ) {
165 // This is a known bug from 2004
166 // It's safe to just erase the old_flags field
168 $this->addError( 'fixed', "Warning: old_flags set to 0", $id );
169 $dbw = wfGetDB( DB_MASTER
);
171 $dbw->update( 'text', [ 'old_flags' => '' ],
172 [ 'old_id' => $id ], __METHOD__
);
175 $this->addError( 'fixable', "Warning: old_flags set to 0", $id );
177 } elseif ( count( array_diff( $flagArray, $knownFlags ) ) ) {
178 $this->addError( 'unfixable', "Error: invalid flags field \"$flags\"", $id );
182 // Output errors for any missing text rows
183 foreach ( $missingTextRows as $oldId => $revIds ) {
184 $this->addError( 'restore revision', "Error: missing text row", $oldId );
187 // Verify external revisions
188 $externalConcatBlobs = [];
189 $externalNormalBlobs = [];
190 if ( count( $externalRevs ) ) {
193 [ 'old_id', 'old_flags', 'old_text' ],
194 [ 'old_id' => $externalRevs ],
197 foreach ( $res as $row ) {
198 $urlParts = explode( '://', $row->old_text
, 2 );
199 if ( count( $urlParts ) !== 2 ||
$urlParts[1] == '' ) {
200 $this->addError( 'restore text', "Error: invalid URL \"{$row->old_text}\"", $row->old_id
);
203 list( $proto, ) = $urlParts;
204 if ( $proto != 'DB' ) {
207 "Error: invalid external protocol \"$proto\"",
211 $path = explode( '/', $row->old_text
);
214 if ( isset( $path[4] ) ) {
215 $externalConcatBlobs[$cluster][$id][] = $row->old_id
;
217 $externalNormalBlobs[$cluster][$id][] = $row->old_id
;
222 // Check external concat blobs for the right header
223 $this->checkExternalConcatBlobs( $externalConcatBlobs );
225 // Check external normal blobs for existence
226 if ( count( $externalNormalBlobs ) ) {
227 if ( is_null( $this->dbStore
) ) {
228 $esFactory = MediaWikiServices
::getInstance()->getExternalStoreFactory();
229 $this->dbStore
= $esFactory->getStore( 'DB' );
231 foreach ( $externalConcatBlobs as $cluster => $xBlobIds ) {
232 $blobIds = array_keys( $xBlobIds );
233 $extDb =& $this->dbStore
->getSlave( $cluster );
234 $blobsTable = $this->dbStore
->getTable( $extDb );
235 $res = $extDb->select( $blobsTable,
237 [ 'blob_id' => $blobIds ],
240 foreach ( $res as $row ) {
241 unset( $xBlobIds[$row->blob_id
] );
243 // Print errors for missing blobs rows
244 foreach ( $xBlobIds as $blobId => $oldId ) {
247 "Error: missing target $blobId for one-part ES URL",
253 // Check local objects
257 if ( count( $objectRevs ) ) {
261 [ 'old_id', 'old_flags', "LEFT(old_text, $headerLength) AS header" ],
262 [ 'old_id' => $objectRevs ],
265 foreach ( $res as $row ) {
266 $oldId = $row->old_id
;
268 if ( !preg_match( '/^O:(\d+):"(\w+)"/', $row->header
, $matches ) ) {
269 $this->addError( 'restore text', "Error: invalid object header", $oldId );
273 $className = strtolower( $matches[2] );
274 if ( strlen( $className ) != $matches[1] ) {
277 "Error: invalid object header, wrong class name length",
283 $objectStats = $objectStats +
[ $className => 0 ];
284 $objectStats[$className]++
;
286 switch ( $className ) {
287 case 'concatenatedgziphistoryblob':
290 case 'historyblobstub':
291 case 'historyblobcurstub':
292 if ( strlen( $row->header
) == $headerLength ) {
293 $this->addError( 'unfixable', "Error: overlong stub header", $oldId );
296 $stubObj = unserialize( $row->header
);
297 if ( !is_object( $stubObj ) ) {
298 $this->addError( 'restore text', "Error: unable to unserialize stub object", $oldId );
301 if ( $className == 'historyblobstub' ) {
302 $concatBlobs[$stubObj->mOldId
][] = $oldId;
304 $curIds[$stubObj->mCurId
][] = $oldId;
308 $this->addError( 'unfixable', "Error: unrecognised object class \"$className\"", $oldId );
313 // Check local concat blob validity
314 $externalConcatBlobs = [];
315 if ( count( $concatBlobs ) ) {
319 [ 'old_id', 'old_flags', "LEFT(old_text, $headerLength) AS header" ],
320 [ 'old_id' => array_keys( $concatBlobs ) ],
323 foreach ( $res as $row ) {
324 $flags = explode( ',', $row->old_flags
);
325 if ( in_array( 'external', $flags ) ) {
326 // Concat blob is in external storage?
327 if ( in_array( 'object', $flags ) ) {
328 $urlParts = explode( '/', $row->header
);
329 if ( $urlParts[0] != 'DB:' ) {
332 "Error: unrecognised external storage type \"{$urlParts[0]}",
336 $cluster = $urlParts[2];
338 if ( !isset( $externalConcatBlobs[$cluster][$id] ) ) {
339 $externalConcatBlobs[$cluster][$id] = [];
341 $externalConcatBlobs[$cluster][$id] = array_merge(
342 $externalConcatBlobs[$cluster][$id], $concatBlobs[$row->old_id
]
348 "Error: invalid flags \"{$row->old_flags}\" on concat bulk row {$row->old_id}",
349 $concatBlobs[$row->old_id
] );
351 } elseif ( strcasecmp(
352 substr( $row->header
, 0, strlen( self
::CONCAT_HEADER
) ),
357 "Error: Incorrect object header for concat bulk row {$row->old_id}",
358 $concatBlobs[$row->old_id
]
362 unset( $concatBlobs[$row->old_id
] );
366 // Check targets of unresolved stubs
367 $this->checkExternalConcatBlobs( $externalConcatBlobs );
371 print "\n\nErrors:\n";
372 foreach ( $this->errors
as $name => $errors ) {
373 if ( count( $errors ) ) {
374 $description = $this->errorDescriptions
[$name];
375 echo "$description: " . implode( ',', array_keys( $errors ) ) . "\n";
379 if ( count( $this->errors
['restore text'] ) && $fix ) {
380 if ( (string)$xml !== '' ) {
381 $this->restoreText( array_keys( $this->errors
['restore text'] ), $xml );
383 echo "Can't fix text, no XML backup specified\n";
387 print "\nFlag statistics:\n";
388 $total = array_sum( $flagStats );
389 foreach ( $flagStats as $flag => $count ) {
390 printf( "%-30s %10d %5.2f%%\n", $flag, $count, $count / $total * 100 );
392 print "\nLocal object statistics:\n";
393 $total = array_sum( $objectStats );
394 foreach ( $objectStats as $className => $count ) {
395 printf( "%-30s %10d %5.2f%%\n", $className, $count, $count / $total * 100 );
399 function addError( $type, $msg, $ids ) {
400 if ( is_array( $ids ) && count( $ids ) == 1 ) {
401 $ids = reset( $ids );
403 if ( is_array( $ids ) ) {
405 foreach ( $ids as $id ) {
406 $revIds = array_unique( array_merge( $revIds, $this->oldIdMap
[$id] ) );
408 print "$msg in text rows " . implode( ', ', $ids ) .
409 ", revisions " . implode( ', ', $revIds ) . "\n";
412 $revIds = $this->oldIdMap
[$id];
413 if ( count( $revIds ) == 1 ) {
414 print "$msg in old_id $id, rev_id {$revIds[0]}\n";
416 print "$msg in old_id $id, revisions " . implode( ', ', $revIds ) . "\n";
419 $this->errors
[$type] = $this->errors
[$type] +
array_flip( $revIds );
422 function checkExternalConcatBlobs( $externalConcatBlobs ) {
423 if ( !count( $externalConcatBlobs ) ) {
427 if ( is_null( $this->dbStore
) ) {
428 $esFactory = MediaWikiServices
::getInstance()->getExternalStoreFactory();
429 $this->dbStore
= $esFactory->getStore( 'DB' );
432 foreach ( $externalConcatBlobs as $cluster => $oldIds ) {
433 $blobIds = array_keys( $oldIds );
434 $extDb =& $this->dbStore
->getSlave( $cluster );
435 $blobsTable = $this->dbStore
->getTable( $extDb );
436 $headerLength = strlen( self
::CONCAT_HEADER
);
437 $res = $extDb->select( $blobsTable,
438 [ 'blob_id', "LEFT(blob_text, $headerLength) AS header" ],
439 [ 'blob_id' => $blobIds ],
442 foreach ( $res as $row ) {
443 if ( strcasecmp( $row->header
, self
::CONCAT_HEADER
) ) {
446 "Error: invalid header on target $cluster/{$row->blob_id} of two-part ES URL",
447 $oldIds[$row->blob_id
]
450 unset( $oldIds[$row->blob_id
] );
453 // Print errors for missing blobs rows
454 foreach ( $oldIds as $blobId => $oldIds2 ) {
457 "Error: missing target $cluster/$blobId for two-part ES URL",
464 function restoreText( $revIds, $xml ) {
466 $tmpDir = wfTempDir();
468 if ( !count( $revIds ) ) {
472 print "Restoring text from XML backup...\n";
474 $revFileName = "$tmpDir/broken-revlist-$wgDBname";
475 $filteredXmlFileName = "$tmpDir/filtered-$wgDBname.xml";
477 // Write revision list
478 if ( !file_put_contents( $revFileName, implode( "\n", $revIds ) ) ) {
479 echo "Error writing revision list, can't restore text\n";
485 echo "Filtering XML dump...\n";
487 passthru( 'mwdumper ' .
489 "--output=file:$filteredXmlFileName",
490 "--filter=revlist:$revFileName",
496 echo "mwdumper died with exit status $exitStatus\n";
501 $file = fopen( $filteredXmlFileName, 'r' );
503 echo "Unable to open filtered XML file\n";
508 $dbr = wfGetDB( DB_REPLICA
);
509 $dbw = wfGetDB( DB_MASTER
);
513 $source = new ImportStreamSource( $file );
514 $importer = new WikiImporter(
516 MediaWikiServices
::getInstance()->getMainConfig()
518 $importer->setRevisionCallback( [ $this, 'importRevision' ] );
519 $importer->setNoticeCallback( function ( $msg, $params ) {
520 echo wfMessage( $msg, $params )->text() . "\n";
522 $importer->doImport();
525 function importRevision( &$revision, &$importer ) {
526 $id = $revision->getID();
527 $content = $revision->getContent( RevisionRecord
::RAW
);
530 if ( $content === null ) {
531 echo "Revision $id is broken, we have no content available\n";
536 $text = $content->serialize();
537 if ( $text === '' ) {
538 // This is what happens if the revision was broken at the time the
539 // dump was made. Unfortunately, it also happens if the revision was
540 // legitimately blank, so there's no way to tell the difference. To
541 // be safe, we'll skip it and leave it broken
543 echo "Revision $id is blank in the dump, may have been broken before export\n";
549 // No ID, can't import
550 echo "No id tag in revision, can't import\n";
555 // Find text row again
556 $dbr = wfGetDB( DB_REPLICA
);
557 $oldId = $dbr->selectField( 'revision', 'rev_text_id', [ 'rev_id' => $id ], __METHOD__
);
559 echo "Missing revision row for rev_id $id\n";
565 $flags = Revision
::compressRevisionText( $text );
567 // Update the text row
568 $dbw = wfGetDB( DB_MASTER
);
569 $dbw->update( 'text',
570 [ 'old_flags' => $flags, 'old_text' => $text ],
571 [ 'old_id' => $oldId ],
572 __METHOD__
, [ 'LIMIT' => 1 ]
575 // Remove it from the unfixed list and add it to the fixed list
576 unset( $this->errors
['restore text'][$id] );
577 $this->errors
['fixed'][$id] = true;