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 public $dbStore = null;
50 public $errorDescriptions = [
51 'restore text' => 'Damaged text, need to be restored from a backup',
52 'restore revision' => 'Damaged revision row, need to be restored from a backup',
53 'unfixable' => 'Unexpected errors with no automated fixing method',
54 'fixed' => 'Errors already fixed',
55 'fixable' => 'Errors which would already be fixed if --fix was specified',
58 function check( $fix = false, $xml = '' ) {
59 global $wgMultiContentRevisionSchemaMigrationStage;
61 $dbr = wfGetDB( DB_REPLICA
);
63 print "Checking, will fix errors if possible...\n";
65 print "Checking...\n";
67 $maxRevId = $dbr->selectField( 'revision', 'MAX(rev_id)', '', __METHOD__
);
71 $knownFlags = [ 'external', 'gzip', 'object', 'utf-8' ];
74 'restore revision' => [],
80 for ( $chunkStart = 1; $chunkStart < $maxRevId; $chunkStart +
= $chunkSize ) {
81 $chunkEnd = $chunkStart +
$chunkSize - 1;
82 // print "$chunkStart of $maxRevId\n";
87 // Fetch revision rows
88 if ( $wgMultiContentRevisionSchemaMigrationStage & SCHEMA_COMPAT_READ_OLD
) {
89 $res = $dbr->select( 'revision', [ 'rev_id', 'rev_text_id' ],
90 [ "rev_id BETWEEN $chunkStart AND $chunkEnd" ], __METHOD__
);
91 foreach ( $res as $row ) {
92 if ( !isset( $this->oldIdMap
[ $row->rev_text_id
] ) ) {
93 $this->oldIdMap
[ $row->rev_text_id
] = [ $row->rev_id
];
94 } elseif ( !in_array( $row->rev_id
, $this->oldIdMap
[ $row->rev_text_id
] ) ) {
95 $this->oldIdMap
[ $row->rev_text_id
][] = $row->rev_id
;
100 [ 'slots', 'content' ],
101 [ 'slot_revision_id', 'content_address' ],
102 [ "slot_revision_id BETWEEN $chunkStart AND $chunkEnd" ],
105 [ 'content' => [ 'INNER JOIN', [ 'content_id = slot_content_id' ] ] ]
107 $blobStore = MediaWikiServices
::getInstance()->getBlobStore();
108 foreach ( $res as $row ) {
109 $textId = $blobStore->getTextIdFromAddress( $row->content_address
);
111 if ( !isset( $this->oldIdMap
[$textId] ) ) {
112 $this->oldIdMap
[ $textId ] = [ $row->slot_revision_id
];
113 } elseif ( !in_array( $row->slot_revision_id
, $this->oldIdMap
[$textId] ) ) {
114 $this->oldIdMap
[ $textId ][] = $row->slot_revision_id
;
120 if ( !count( $this->oldIdMap
) ) {
125 $missingTextRows = $this->oldIdMap
;
130 [ 'old_id', 'old_flags' ],
131 [ 'old_id' => array_keys( $this->oldIdMap
) ],
134 foreach ( $res as $row ) {
138 $flags = $row->old_flags
;
141 // Create flagStats row if it doesn't exist
142 $flagStats = $flagStats +
[ $flags => 0 ];
144 $flagStats[$flags]++
;
147 unset( $missingTextRows[$row->old_id
] );
149 // Check for external or object
150 if ( $flags == '' ) {
153 $flagArray = explode( ',', $flags );
155 if ( in_array( 'external', $flagArray ) ) {
156 $externalRevs[] = $id;
157 } elseif ( in_array( 'object', $flagArray ) ) {
161 // Check for unrecognised flags
162 if ( $flags == '0' ) {
163 // This is a known bug from 2004
164 // It's safe to just erase the old_flags field
166 $this->addError( 'fixed', "Warning: old_flags set to 0", $id );
167 $dbw = wfGetDB( DB_MASTER
);
169 $dbw->update( 'text', [ 'old_flags' => '' ],
170 [ 'old_id' => $id ], __METHOD__
);
173 $this->addError( 'fixable', "Warning: old_flags set to 0", $id );
175 } elseif ( count( array_diff( $flagArray, $knownFlags ) ) ) {
176 $this->addError( 'unfixable', "Error: invalid flags field \"$flags\"", $id );
180 // Output errors for any missing text rows
181 foreach ( $missingTextRows as $oldId => $revIds ) {
182 $this->addError( 'restore revision', "Error: missing text row", $oldId );
185 // Verify external revisions
186 $externalConcatBlobs = [];
187 $externalNormalBlobs = [];
188 if ( count( $externalRevs ) ) {
191 [ 'old_id', 'old_flags', 'old_text' ],
192 [ 'old_id' => $externalRevs ],
195 foreach ( $res as $row ) {
196 $urlParts = explode( '://', $row->old_text
, 2 );
197 if ( count( $urlParts ) !== 2 ||
$urlParts[1] == '' ) {
198 $this->addError( 'restore text', "Error: invalid URL \"{$row->old_text}\"", $row->old_id
);
201 list( $proto, ) = $urlParts;
202 if ( $proto != 'DB' ) {
205 "Error: invalid external protocol \"$proto\"",
209 $path = explode( '/', $row->old_text
);
212 if ( isset( $path[4] ) ) {
213 $externalConcatBlobs[$cluster][$id][] = $row->old_id
;
215 $externalNormalBlobs[$cluster][$id][] = $row->old_id
;
220 // Check external concat blobs for the right header
221 $this->checkExternalConcatBlobs( $externalConcatBlobs );
223 // Check external normal blobs for existence
224 if ( count( $externalNormalBlobs ) ) {
225 if ( is_null( $this->dbStore
) ) {
226 $this->dbStore
= new ExternalStoreDB
;
228 foreach ( $externalConcatBlobs as $cluster => $xBlobIds ) {
229 $blobIds = array_keys( $xBlobIds );
230 $extDb =& $this->dbStore
->getSlave( $cluster );
231 $blobsTable = $this->dbStore
->getTable( $extDb );
232 $res = $extDb->select( $blobsTable,
234 [ 'blob_id' => $blobIds ],
237 foreach ( $res as $row ) {
238 unset( $xBlobIds[$row->blob_id
] );
240 // Print errors for missing blobs rows
241 foreach ( $xBlobIds as $blobId => $oldId ) {
244 "Error: missing target $blobId for one-part ES URL",
250 // Check local objects
254 if ( count( $objectRevs ) ) {
258 [ 'old_id', 'old_flags', "LEFT(old_text, $headerLength) AS header" ],
259 [ 'old_id' => $objectRevs ],
262 foreach ( $res as $row ) {
263 $oldId = $row->old_id
;
265 if ( !preg_match( '/^O:(\d+):"(\w+)"/', $row->header
, $matches ) ) {
266 $this->addError( 'restore text', "Error: invalid object header", $oldId );
270 $className = strtolower( $matches[2] );
271 if ( strlen( $className ) != $matches[1] ) {
274 "Error: invalid object header, wrong class name length",
280 $objectStats = $objectStats +
[ $className => 0 ];
281 $objectStats[$className]++
;
283 switch ( $className ) {
284 case 'concatenatedgziphistoryblob':
287 case 'historyblobstub':
288 case 'historyblobcurstub':
289 if ( strlen( $row->header
) == $headerLength ) {
290 $this->addError( 'unfixable', "Error: overlong stub header", $oldId );
293 $stubObj = unserialize( $row->header
);
294 if ( !is_object( $stubObj ) ) {
295 $this->addError( 'restore text', "Error: unable to unserialize stub object", $oldId );
298 if ( $className == 'historyblobstub' ) {
299 $concatBlobs[$stubObj->mOldId
][] = $oldId;
301 $curIds[$stubObj->mCurId
][] = $oldId;
305 $this->addError( 'unfixable', "Error: unrecognised object class \"$className\"", $oldId );
310 // Check local concat blob validity
311 $externalConcatBlobs = [];
312 if ( count( $concatBlobs ) ) {
316 [ 'old_id', 'old_flags', "LEFT(old_text, $headerLength) AS header" ],
317 [ 'old_id' => array_keys( $concatBlobs ) ],
320 foreach ( $res as $row ) {
321 $flags = explode( ',', $row->old_flags
);
322 if ( in_array( 'external', $flags ) ) {
323 // Concat blob is in external storage?
324 if ( in_array( 'object', $flags ) ) {
325 $urlParts = explode( '/', $row->header
);
326 if ( $urlParts[0] != 'DB:' ) {
329 "Error: unrecognised external storage type \"{$urlParts[0]}",
333 $cluster = $urlParts[2];
335 if ( !isset( $externalConcatBlobs[$cluster][$id] ) ) {
336 $externalConcatBlobs[$cluster][$id] = [];
338 $externalConcatBlobs[$cluster][$id] = array_merge(
339 $externalConcatBlobs[$cluster][$id], $concatBlobs[$row->old_id
]
345 "Error: invalid flags \"{$row->old_flags}\" on concat bulk row {$row->old_id}",
346 $concatBlobs[$row->old_id
] );
348 } elseif ( strcasecmp(
349 substr( $row->header
, 0, strlen( self
::CONCAT_HEADER
) ),
354 "Error: Incorrect object header for concat bulk row {$row->old_id}",
355 $concatBlobs[$row->old_id
]
359 unset( $concatBlobs[$row->old_id
] );
363 // Check targets of unresolved stubs
364 $this->checkExternalConcatBlobs( $externalConcatBlobs );
368 print "\n\nErrors:\n";
369 foreach ( $this->errors
as $name => $errors ) {
370 if ( count( $errors ) ) {
371 $description = $this->errorDescriptions
[$name];
372 echo "$description: " . implode( ',', array_keys( $errors ) ) . "\n";
376 if ( count( $this->errors
['restore text'] ) && $fix ) {
377 if ( (string)$xml !== '' ) {
378 $this->restoreText( array_keys( $this->errors
['restore text'] ), $xml );
380 echo "Can't fix text, no XML backup specified\n";
384 print "\nFlag statistics:\n";
385 $total = array_sum( $flagStats );
386 foreach ( $flagStats as $flag => $count ) {
387 printf( "%-30s %10d %5.2f%%\n", $flag, $count, $count / $total * 100 );
389 print "\nLocal object statistics:\n";
390 $total = array_sum( $objectStats );
391 foreach ( $objectStats as $className => $count ) {
392 printf( "%-30s %10d %5.2f%%\n", $className, $count, $count / $total * 100 );
396 function addError( $type, $msg, $ids ) {
397 if ( is_array( $ids ) && count( $ids ) == 1 ) {
398 $ids = reset( $ids );
400 if ( is_array( $ids ) ) {
402 foreach ( $ids as $id ) {
403 $revIds = array_unique( array_merge( $revIds, $this->oldIdMap
[$id] ) );
405 print "$msg in text rows " . implode( ', ', $ids ) .
406 ", revisions " . implode( ', ', $revIds ) . "\n";
409 $revIds = $this->oldIdMap
[$id];
410 if ( count( $revIds ) == 1 ) {
411 print "$msg in old_id $id, rev_id {$revIds[0]}\n";
413 print "$msg in old_id $id, revisions " . implode( ', ', $revIds ) . "\n";
416 $this->errors
[$type] = $this->errors
[$type] +
array_flip( $revIds );
419 function checkExternalConcatBlobs( $externalConcatBlobs ) {
420 if ( !count( $externalConcatBlobs ) ) {
424 if ( is_null( $this->dbStore
) ) {
425 $this->dbStore
= new ExternalStoreDB
;
428 foreach ( $externalConcatBlobs as $cluster => $oldIds ) {
429 $blobIds = array_keys( $oldIds );
430 $extDb =& $this->dbStore
->getSlave( $cluster );
431 $blobsTable = $this->dbStore
->getTable( $extDb );
432 $headerLength = strlen( self
::CONCAT_HEADER
);
433 $res = $extDb->select( $blobsTable,
434 [ 'blob_id', "LEFT(blob_text, $headerLength) AS header" ],
435 [ 'blob_id' => $blobIds ],
438 foreach ( $res as $row ) {
439 if ( strcasecmp( $row->header
, self
::CONCAT_HEADER
) ) {
442 "Error: invalid header on target $cluster/{$row->blob_id} of two-part ES URL",
443 $oldIds[$row->blob_id
]
446 unset( $oldIds[$row->blob_id
] );
449 // Print errors for missing blobs rows
450 foreach ( $oldIds as $blobId => $oldIds2 ) {
453 "Error: missing target $cluster/$blobId for two-part ES URL",
460 function restoreText( $revIds, $xml ) {
462 $tmpDir = wfTempDir();
464 if ( !count( $revIds ) ) {
468 print "Restoring text from XML backup...\n";
470 $revFileName = "$tmpDir/broken-revlist-$wgDBname";
471 $filteredXmlFileName = "$tmpDir/filtered-$wgDBname.xml";
473 // Write revision list
474 if ( !file_put_contents( $revFileName, implode( "\n", $revIds ) ) ) {
475 echo "Error writing revision list, can't restore text\n";
481 echo "Filtering XML dump...\n";
483 passthru( 'mwdumper ' .
485 "--output=file:$filteredXmlFileName",
486 "--filter=revlist:$revFileName",
492 echo "mwdumper died with exit status $exitStatus\n";
497 $file = fopen( $filteredXmlFileName, 'r' );
499 echo "Unable to open filtered XML file\n";
504 $dbr = wfGetDB( DB_REPLICA
);
505 $dbw = wfGetDB( DB_MASTER
);
509 $source = new ImportStreamSource( $file );
510 $importer = new WikiImporter(
512 MediaWikiServices
::getInstance()->getMainConfig()
514 $importer->setRevisionCallback( [ $this, 'importRevision' ] );
515 $importer->setNoticeCallback( function ( $msg, $params ) {
516 echo wfMessage( $msg, $params )->text() . "\n";
518 $importer->doImport();
521 function importRevision( &$revision, &$importer ) {
522 $id = $revision->getID();
523 $content = $revision->getContent( Revision
::RAW
);
526 if ( $content === null ) {
527 echo "Revision $id is broken, we have no content available\n";
532 $text = $content->serialize();
533 if ( $text === '' ) {
534 // This is what happens if the revision was broken at the time the
535 // dump was made. Unfortunately, it also happens if the revision was
536 // legitimately blank, so there's no way to tell the difference. To
537 // be safe, we'll skip it and leave it broken
539 echo "Revision $id is blank in the dump, may have been broken before export\n";
545 // No ID, can't import
546 echo "No id tag in revision, can't import\n";
551 // Find text row again
552 $dbr = wfGetDB( DB_REPLICA
);
553 $oldId = $dbr->selectField( 'revision', 'rev_text_id', [ 'rev_id' => $id ], __METHOD__
);
555 echo "Missing revision row for rev_id $id\n";
561 $flags = Revision
::compressRevisionText( $text );
563 // Update the text row
564 $dbw = wfGetDB( DB_MASTER
);
565 $dbw->update( 'text',
566 [ 'old_flags' => $flags, 'old_text' => $text ],
567 [ 'old_id' => $oldId ],
568 __METHOD__
, [ 'LIMIT' => 1 ]
571 // Remove it from the unfixed list and add it to the fixed list
572 unset( $this->errors
['restore text'][$id] );
573 $this->errors
['fixed'][$id] = true;