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 /** @var \MediaWiki\Storage\SqlBlobStore $blobStore */
110 $blobStore = MediaWikiServices
::getInstance()->getBlobStore();
111 '@phan-var \MediaWiki\Storage\SqlBlobStore $blobStore';
112 foreach ( $res as $row ) {
113 $textId = $blobStore->getTextIdFromAddress( $row->content_address
);
115 if ( !isset( $this->oldIdMap
[$textId] ) ) {
116 $this->oldIdMap
[ $textId ] = [ $row->slot_revision_id
];
117 } elseif ( !in_array( $row->slot_revision_id
, $this->oldIdMap
[$textId] ) ) {
118 $this->oldIdMap
[ $textId ][] = $row->slot_revision_id
;
124 if ( !count( $this->oldIdMap
) ) {
129 $missingTextRows = $this->oldIdMap
;
134 [ 'old_id', 'old_flags' ],
135 [ 'old_id' => array_keys( $this->oldIdMap
) ],
138 foreach ( $res as $row ) {
142 $flags = $row->old_flags
;
145 // Create flagStats row if it doesn't exist
146 $flagStats = $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 = wfGetDB( DB_MASTER
);
173 $dbw->update( 'text', [ 'old_flags' => '' ],
174 [ 'old_id' => $id ], __METHOD__
);
177 $this->addError( 'fixable', "Warning: old_flags set to 0", $id );
179 } elseif ( count( array_diff( $flagArray, $knownFlags ) ) ) {
180 $this->addError( 'unfixable', "Error: invalid flags field \"$flags\"", $id );
184 // Output errors for any missing text rows
185 foreach ( $missingTextRows as $oldId => $revIds ) {
186 $this->addError( 'restore revision', "Error: missing text row", $oldId );
189 // Verify external revisions
190 $externalConcatBlobs = [];
191 $externalNormalBlobs = [];
192 if ( count( $externalRevs ) ) {
195 [ 'old_id', 'old_flags', 'old_text' ],
196 [ 'old_id' => $externalRevs ],
199 foreach ( $res as $row ) {
200 $urlParts = explode( '://', $row->old_text
, 2 );
201 if ( count( $urlParts ) !== 2 ||
$urlParts[1] == '' ) {
202 $this->addError( 'restore text', "Error: invalid URL \"{$row->old_text}\"", $row->old_id
);
205 list( $proto, ) = $urlParts;
206 if ( $proto != 'DB' ) {
209 "Error: invalid external protocol \"$proto\"",
213 $path = explode( '/', $row->old_text
);
216 if ( isset( $path[4] ) ) {
217 $externalConcatBlobs[$cluster][$id][] = $row->old_id
;
219 $externalNormalBlobs[$cluster][$id][] = $row->old_id
;
224 // Check external concat blobs for the right header
225 $this->checkExternalConcatBlobs( $externalConcatBlobs );
227 // Check external normal blobs for existence
228 if ( count( $externalNormalBlobs ) ) {
229 if ( is_null( $this->dbStore
) ) {
230 $esFactory = MediaWikiServices
::getInstance()->getExternalStoreFactory();
231 $this->dbStore
= $esFactory->getStore( 'DB' );
233 foreach ( $externalConcatBlobs as $cluster => $xBlobIds ) {
234 $blobIds = array_keys( $xBlobIds );
235 $extDb =& $this->dbStore
->getReplica( $cluster );
236 $blobsTable = $this->dbStore
->getTable( $extDb );
237 $res = $extDb->select( $blobsTable,
239 [ 'blob_id' => $blobIds ],
242 foreach ( $res as $row ) {
243 unset( $xBlobIds[$row->blob_id
] );
245 // Print errors for missing blobs rows
246 foreach ( $xBlobIds as $blobId => $oldId ) {
249 "Error: missing target $blobId for one-part ES URL",
255 // Check local objects
259 if ( count( $objectRevs ) ) {
263 [ 'old_id', 'old_flags', "LEFT(old_text, $headerLength) AS header" ],
264 [ 'old_id' => $objectRevs ],
267 foreach ( $res as $row ) {
268 $oldId = $row->old_id
;
270 if ( !preg_match( '/^O:(\d+):"(\w+)"/', $row->header
, $matches ) ) {
271 $this->addError( 'restore text', "Error: invalid object header", $oldId );
275 $className = strtolower( $matches[2] );
276 if ( strlen( $className ) != $matches[1] ) {
279 "Error: invalid object header, wrong class name length",
285 $objectStats = $objectStats +
[ $className => 0 ];
286 $objectStats[$className]++
;
288 switch ( $className ) {
289 case 'concatenatedgziphistoryblob':
292 case 'historyblobstub':
293 case 'historyblobcurstub':
294 if ( strlen( $row->header
) == $headerLength ) {
295 $this->addError( 'unfixable', "Error: overlong stub header", $oldId );
298 $stubObj = unserialize( $row->header
);
299 if ( !is_object( $stubObj ) ) {
300 $this->addError( 'restore text', "Error: unable to unserialize stub object", $oldId );
303 if ( $className == 'historyblobstub' ) {
304 $concatBlobs[$stubObj->mOldId
][] = $oldId;
306 $curIds[$stubObj->mCurId
][] = $oldId;
310 $this->addError( 'unfixable', "Error: unrecognised object class \"$className\"", $oldId );
315 // Check local concat blob validity
316 $externalConcatBlobs = [];
317 if ( count( $concatBlobs ) ) {
321 [ 'old_id', 'old_flags', "LEFT(old_text, $headerLength) AS header" ],
322 [ 'old_id' => array_keys( $concatBlobs ) ],
325 foreach ( $res as $row ) {
326 $flags = explode( ',', $row->old_flags
);
327 if ( in_array( 'external', $flags ) ) {
328 // Concat blob is in external storage?
329 if ( in_array( 'object', $flags ) ) {
330 $urlParts = explode( '/', $row->header
);
331 if ( $urlParts[0] != 'DB:' ) {
334 "Error: unrecognised external storage type \"{$urlParts[0]}",
338 $cluster = $urlParts[2];
340 if ( !isset( $externalConcatBlobs[$cluster][$id] ) ) {
341 $externalConcatBlobs[$cluster][$id] = [];
343 $externalConcatBlobs[$cluster][$id] = array_merge(
344 $externalConcatBlobs[$cluster][$id], $concatBlobs[$row->old_id
]
350 "Error: invalid flags \"{$row->old_flags}\" on concat bulk row {$row->old_id}",
351 $concatBlobs[$row->old_id
] );
353 } elseif ( strcasecmp(
354 substr( $row->header
, 0, strlen( self
::CONCAT_HEADER
) ),
359 "Error: Incorrect object header for concat bulk row {$row->old_id}",
360 $concatBlobs[$row->old_id
]
364 unset( $concatBlobs[$row->old_id
] );
368 // Check targets of unresolved stubs
369 $this->checkExternalConcatBlobs( $externalConcatBlobs );
373 print "\n\nErrors:\n";
374 foreach ( $this->errors
as $name => $errors ) {
375 if ( count( $errors ) ) {
376 $description = $this->errorDescriptions
[$name];
377 echo "$description: " . implode( ',', array_keys( $errors ) ) . "\n";
381 if ( count( $this->errors
['restore text'] ) && $fix ) {
382 if ( (string)$xml !== '' ) {
383 $this->restoreText( array_keys( $this->errors
['restore text'] ), $xml );
385 echo "Can't fix text, no XML backup specified\n";
389 print "\nFlag statistics:\n";
390 $total = array_sum( $flagStats );
391 foreach ( $flagStats as $flag => $count ) {
392 printf( "%-30s %10d %5.2f%%\n", $flag, $count, $count / $total * 100 );
394 print "\nLocal object statistics:\n";
395 $total = array_sum( $objectStats );
396 foreach ( $objectStats as $className => $count ) {
397 printf( "%-30s %10d %5.2f%%\n", $className, $count, $count / $total * 100 );
401 function addError( $type, $msg, $ids ) {
402 if ( is_array( $ids ) && count( $ids ) == 1 ) {
403 $ids = reset( $ids );
405 if ( is_array( $ids ) ) {
407 foreach ( $ids as $id ) {
408 $revIds = array_unique( array_merge( $revIds, $this->oldIdMap
[$id] ) );
410 print "$msg in text rows " . implode( ', ', $ids ) .
411 ", revisions " . implode( ', ', $revIds ) . "\n";
414 $revIds = $this->oldIdMap
[$id];
415 if ( count( $revIds ) == 1 ) {
416 print "$msg in old_id $id, rev_id {$revIds[0]}\n";
418 print "$msg in old_id $id, revisions " . implode( ', ', $revIds ) . "\n";
421 $this->errors
[$type] = $this->errors
[$type] +
array_flip( $revIds );
424 function checkExternalConcatBlobs( $externalConcatBlobs ) {
425 if ( !count( $externalConcatBlobs ) ) {
429 if ( is_null( $this->dbStore
) ) {
430 $esFactory = MediaWikiServices
::getInstance()->getExternalStoreFactory();
431 $this->dbStore
= $esFactory->getStore( 'DB' );
434 foreach ( $externalConcatBlobs as $cluster => $oldIds ) {
435 $blobIds = array_keys( $oldIds );
436 $extDb =& $this->dbStore
->getReplica( $cluster );
437 $blobsTable = $this->dbStore
->getTable( $extDb );
438 $headerLength = strlen( self
::CONCAT_HEADER
);
439 $res = $extDb->select( $blobsTable,
440 [ 'blob_id', "LEFT(blob_text, $headerLength) AS header" ],
441 [ 'blob_id' => $blobIds ],
444 foreach ( $res as $row ) {
445 if ( strcasecmp( $row->header
, self
::CONCAT_HEADER
) ) {
448 "Error: invalid header on target $cluster/{$row->blob_id} of two-part ES URL",
449 $oldIds[$row->blob_id
]
452 unset( $oldIds[$row->blob_id
] );
455 // Print errors for missing blobs rows
456 foreach ( $oldIds as $blobId => $oldIds2 ) {
459 "Error: missing target $cluster/$blobId for two-part ES URL",
466 function restoreText( $revIds, $xml ) {
468 $tmpDir = wfTempDir();
470 if ( !count( $revIds ) ) {
474 print "Restoring text from XML backup...\n";
476 $revFileName = "$tmpDir/broken-revlist-$wgDBname";
477 $filteredXmlFileName = "$tmpDir/filtered-$wgDBname.xml";
479 // Write revision list
480 if ( !file_put_contents( $revFileName, implode( "\n", $revIds ) ) ) {
481 echo "Error writing revision list, can't restore text\n";
487 echo "Filtering XML dump...\n";
489 passthru( 'mwdumper ' .
491 "--output=file:$filteredXmlFileName",
492 "--filter=revlist:$revFileName",
498 echo "mwdumper died with exit status $exitStatus\n";
503 $file = fopen( $filteredXmlFileName, 'r' );
505 echo "Unable to open filtered XML file\n";
510 $dbr = wfGetDB( DB_REPLICA
);
511 $dbw = wfGetDB( DB_MASTER
);
515 $source = new ImportStreamSource( $file );
516 $importer = new WikiImporter(
518 MediaWikiServices
::getInstance()->getMainConfig()
520 $importer->setRevisionCallback( [ $this, 'importRevision' ] );
521 $importer->setNoticeCallback( function ( $msg, $params ) {
522 echo wfMessage( $msg, $params )->text() . "\n";
524 $importer->doImport();
527 function importRevision( &$revision, &$importer ) {
528 $id = $revision->getID();
529 $content = $revision->getContent( RevisionRecord
::RAW
);
532 if ( $content === null ) {
533 echo "Revision $id is broken, we have no content available\n";
538 $text = $content->serialize();
539 if ( $text === '' ) {
540 // This is what happens if the revision was broken at the time the
541 // dump was made. Unfortunately, it also happens if the revision was
542 // legitimately blank, so there's no way to tell the difference. To
543 // be safe, we'll skip it and leave it broken
545 echo "Revision $id is blank in the dump, may have been broken before export\n";
551 // No ID, can't import
552 echo "No id tag in revision, can't import\n";
557 // Find text row again
558 $dbr = wfGetDB( DB_REPLICA
);
559 $oldId = $dbr->selectField( 'revision', 'rev_text_id', [ 'rev_id' => $id ], __METHOD__
);
561 echo "Missing revision row for rev_id $id\n";
567 $flags = Revision
::compressRevisionText( $text );
569 // Update the text row
570 $dbw = wfGetDB( DB_MASTER
);
571 $dbw->update( 'text',
572 [ 'old_flags' => $flags, 'old_text' => $text ],
573 [ 'old_id' => $oldId ],
574 __METHOD__
, [ 'LIMIT' => 1 ]
577 // Remove it from the unfixed list and add it to the fixed list
578 unset( $this->errors
['restore text'][$id] );
579 $this->errors
['fixed'][$id] = true;