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 $dbr = wfGetDB( DB_REPLICA
);
61 print "Checking, will fix errors if possible...\n";
63 print "Checking...\n";
65 $maxRevId = $dbr->selectField( 'revision', 'MAX(rev_id)', '', __METHOD__
);
69 $knownFlags = [ 'external', 'gzip', 'object', 'utf-8' ];
72 'restore revision' => [],
78 for ( $chunkStart = 1; $chunkStart < $maxRevId; $chunkStart +
= $chunkSize ) {
79 $chunkEnd = $chunkStart +
$chunkSize - 1;
80 // print "$chunkStart of $maxRevId\n";
82 // Fetch revision rows
85 $res = $dbr->select( 'revision', [ 'rev_id', 'rev_text_id' ],
86 [ "rev_id BETWEEN $chunkStart AND $chunkEnd" ], __METHOD__
);
87 foreach ( $res as $row ) {
88 $this->oldIdMap
[$row->rev_id
] = $row->rev_text_id
;
91 if ( !count( $this->oldIdMap
) ) {
96 $missingTextRows = array_flip( $this->oldIdMap
);
101 [ 'old_id', 'old_flags' ],
102 [ 'old_id' => $this->oldIdMap
],
105 foreach ( $res as $row ) {
109 $flags = $row->old_flags
;
112 // Create flagStats row if it doesn't exist
113 $flagStats = $flagStats +
[ $flags => 0 ];
115 $flagStats[$flags]++
;
118 unset( $missingTextRows[$row->old_id
] );
120 // Check for external or object
121 if ( $flags == '' ) {
124 $flagArray = explode( ',', $flags );
126 if ( in_array( 'external', $flagArray ) ) {
127 $externalRevs[] = $id;
128 } elseif ( in_array( 'object', $flagArray ) ) {
132 // Check for unrecognised flags
133 if ( $flags == '0' ) {
134 // This is a known bug from 2004
135 // It's safe to just erase the old_flags field
137 $this->addError( 'fixed', "Warning: old_flags set to 0", $id );
138 $dbw = wfGetDB( DB_MASTER
);
140 $dbw->update( 'text', [ 'old_flags' => '' ],
141 [ 'old_id' => $id ], __METHOD__
);
144 $this->addError( 'fixable', "Warning: old_flags set to 0", $id );
146 } elseif ( count( array_diff( $flagArray, $knownFlags ) ) ) {
147 $this->addError( 'unfixable', "Error: invalid flags field \"$flags\"", $id );
151 // Output errors for any missing text rows
152 foreach ( $missingTextRows as $oldId => $revId ) {
153 $this->addError( 'restore revision', "Error: missing text row", $oldId );
156 // Verify external revisions
157 $externalConcatBlobs = [];
158 $externalNormalBlobs = [];
159 if ( count( $externalRevs ) ) {
162 [ 'old_id', 'old_flags', 'old_text' ],
163 [ 'old_id' => $externalRevs ],
166 foreach ( $res as $row ) {
167 $urlParts = explode( '://', $row->old_text
, 2 );
168 if ( count( $urlParts ) !== 2 ||
$urlParts[1] == '' ) {
169 $this->addError( 'restore text', "Error: invalid URL \"{$row->old_text}\"", $row->old_id
);
172 list( $proto, ) = $urlParts;
173 if ( $proto != 'DB' ) {
176 "Error: invalid external protocol \"$proto\"",
180 $path = explode( '/', $row->old_text
);
183 if ( isset( $path[4] ) ) {
184 $externalConcatBlobs[$cluster][$id][] = $row->old_id
;
186 $externalNormalBlobs[$cluster][$id][] = $row->old_id
;
191 // Check external concat blobs for the right header
192 $this->checkExternalConcatBlobs( $externalConcatBlobs );
194 // Check external normal blobs for existence
195 if ( count( $externalNormalBlobs ) ) {
196 if ( is_null( $this->dbStore
) ) {
197 $this->dbStore
= new ExternalStoreDB
;
199 foreach ( $externalConcatBlobs as $cluster => $xBlobIds ) {
200 $blobIds = array_keys( $xBlobIds );
201 $extDb =& $this->dbStore
->getSlave( $cluster );
202 $blobsTable = $this->dbStore
->getTable( $extDb );
203 $res = $extDb->select( $blobsTable,
205 [ 'blob_id' => $blobIds ],
208 foreach ( $res as $row ) {
209 unset( $xBlobIds[$row->blob_id
] );
211 // Print errors for missing blobs rows
212 foreach ( $xBlobIds as $blobId => $oldId ) {
215 "Error: missing target $blobId for one-part ES URL",
221 // Check local objects
225 if ( count( $objectRevs ) ) {
229 [ 'old_id', 'old_flags', "LEFT(old_text, $headerLength) AS header" ],
230 [ 'old_id' => $objectRevs ],
233 foreach ( $res as $row ) {
234 $oldId = $row->old_id
;
236 if ( !preg_match( '/^O:(\d+):"(\w+)"/', $row->header
, $matches ) ) {
237 $this->addError( 'restore text', "Error: invalid object header", $oldId );
241 $className = strtolower( $matches[2] );
242 if ( strlen( $className ) != $matches[1] ) {
245 "Error: invalid object header, wrong class name length",
251 $objectStats = $objectStats +
[ $className => 0 ];
252 $objectStats[$className]++
;
254 switch ( $className ) {
255 case 'concatenatedgziphistoryblob':
258 case 'historyblobstub':
259 case 'historyblobcurstub':
260 if ( strlen( $row->header
) == $headerLength ) {
261 $this->addError( 'unfixable', "Error: overlong stub header", $oldId );
264 $stubObj = unserialize( $row->header
);
265 if ( !is_object( $stubObj ) ) {
266 $this->addError( 'restore text', "Error: unable to unserialize stub object", $oldId );
269 if ( $className == 'historyblobstub' ) {
270 $concatBlobs[$stubObj->mOldId
][] = $oldId;
272 $curIds[$stubObj->mCurId
][] = $oldId;
276 $this->addError( 'unfixable', "Error: unrecognised object class \"$className\"", $oldId );
281 // Check local concat blob validity
282 $externalConcatBlobs = [];
283 if ( count( $concatBlobs ) ) {
287 [ 'old_id', 'old_flags', "LEFT(old_text, $headerLength) AS header" ],
288 [ 'old_id' => array_keys( $concatBlobs ) ],
291 foreach ( $res as $row ) {
292 $flags = explode( ',', $row->old_flags
);
293 if ( in_array( 'external', $flags ) ) {
294 // Concat blob is in external storage?
295 if ( in_array( 'object', $flags ) ) {
296 $urlParts = explode( '/', $row->header
);
297 if ( $urlParts[0] != 'DB:' ) {
300 "Error: unrecognised external storage type \"{$urlParts[0]}",
304 $cluster = $urlParts[2];
306 if ( !isset( $externalConcatBlobs[$cluster][$id] ) ) {
307 $externalConcatBlobs[$cluster][$id] = [];
309 $externalConcatBlobs[$cluster][$id] = array_merge(
310 $externalConcatBlobs[$cluster][$id], $concatBlobs[$row->old_id
]
316 "Error: invalid flags \"{$row->old_flags}\" on concat bulk row {$row->old_id}",
317 $concatBlobs[$row->old_id
] );
319 } elseif ( strcasecmp(
320 substr( $row->header
, 0, strlen( self
::CONCAT_HEADER
) ),
325 "Error: Incorrect object header for concat bulk row {$row->old_id}",
326 $concatBlobs[$row->old_id
]
330 unset( $concatBlobs[$row->old_id
] );
334 // Check targets of unresolved stubs
335 $this->checkExternalConcatBlobs( $externalConcatBlobs );
339 print "\n\nErrors:\n";
340 foreach ( $this->errors
as $name => $errors ) {
341 if ( count( $errors ) ) {
342 $description = $this->errorDescriptions
[$name];
343 echo "$description: " . implode( ',', array_keys( $errors ) ) . "\n";
347 if ( count( $this->errors
['restore text'] ) && $fix ) {
348 if ( (string)$xml !== '' ) {
349 $this->restoreText( array_keys( $this->errors
['restore text'] ), $xml );
351 echo "Can't fix text, no XML backup specified\n";
355 print "\nFlag statistics:\n";
356 $total = array_sum( $flagStats );
357 foreach ( $flagStats as $flag => $count ) {
358 printf( "%-30s %10d %5.2f%%\n", $flag, $count, $count / $total * 100 );
360 print "\nLocal object statistics:\n";
361 $total = array_sum( $objectStats );
362 foreach ( $objectStats as $className => $count ) {
363 printf( "%-30s %10d %5.2f%%\n", $className, $count, $count / $total * 100 );
367 function addError( $type, $msg, $ids ) {
368 if ( is_array( $ids ) && count( $ids ) == 1 ) {
369 $ids = reset( $ids );
371 if ( is_array( $ids ) ) {
373 foreach ( $ids as $id ) {
374 $revIds = array_merge( $revIds, array_keys( $this->oldIdMap
, $id ) );
376 print "$msg in text rows " . implode( ', ', $ids ) .
377 ", revisions " . implode( ', ', $revIds ) . "\n";
380 $revIds = array_keys( $this->oldIdMap
, $id );
381 if ( count( $revIds ) == 1 ) {
382 print "$msg in old_id $id, rev_id {$revIds[0]}\n";
384 print "$msg in old_id $id, revisions " . implode( ', ', $revIds ) . "\n";
387 $this->errors
[$type] = $this->errors
[$type] +
array_flip( $revIds );
390 function checkExternalConcatBlobs( $externalConcatBlobs ) {
391 if ( !count( $externalConcatBlobs ) ) {
395 if ( is_null( $this->dbStore
) ) {
396 $this->dbStore
= new ExternalStoreDB
;
399 foreach ( $externalConcatBlobs as $cluster => $oldIds ) {
400 $blobIds = array_keys( $oldIds );
401 $extDb =& $this->dbStore
->getSlave( $cluster );
402 $blobsTable = $this->dbStore
->getTable( $extDb );
403 $headerLength = strlen( self
::CONCAT_HEADER
);
404 $res = $extDb->select( $blobsTable,
405 [ 'blob_id', "LEFT(blob_text, $headerLength) AS header" ],
406 [ 'blob_id' => $blobIds ],
409 foreach ( $res as $row ) {
410 if ( strcasecmp( $row->header
, self
::CONCAT_HEADER
) ) {
413 "Error: invalid header on target $cluster/{$row->blob_id} of two-part ES URL",
414 $oldIds[$row->blob_id
]
417 unset( $oldIds[$row->blob_id
] );
420 // Print errors for missing blobs rows
421 foreach ( $oldIds as $blobId => $oldIds2 ) {
424 "Error: missing target $cluster/$blobId for two-part ES URL",
431 function restoreText( $revIds, $xml ) {
433 $tmpDir = wfTempDir();
435 if ( !count( $revIds ) ) {
439 print "Restoring text from XML backup...\n";
441 $revFileName = "$tmpDir/broken-revlist-$wgDBname";
442 $filteredXmlFileName = "$tmpDir/filtered-$wgDBname.xml";
444 // Write revision list
445 if ( !file_put_contents( $revFileName, implode( "\n", $revIds ) ) ) {
446 echo "Error writing revision list, can't restore text\n";
452 echo "Filtering XML dump...\n";
454 passthru( 'mwdumper ' .
456 "--output=file:$filteredXmlFileName",
457 "--filter=revlist:$revFileName",
463 echo "mwdumper died with exit status $exitStatus\n";
468 $file = fopen( $filteredXmlFileName, 'r' );
470 echo "Unable to open filtered XML file\n";
475 $dbr = wfGetDB( DB_REPLICA
);
476 $dbw = wfGetDB( DB_MASTER
);
480 $source = new ImportStreamSource( $file );
481 $importer = new WikiImporter(
483 MediaWikiServices
::getInstance()->getMainConfig()
485 $importer->setRevisionCallback( [ $this, 'importRevision' ] );
486 $importer->setNoticeCallback( function ( $msg, $params ) {
487 echo wfMessage( $msg, $params )->text() . "\n";
489 $importer->doImport();
492 function importRevision( &$revision, &$importer ) {
493 $id = $revision->getID();
494 $content = $revision->getContent( Revision
::RAW
);
497 if ( $content === null ) {
498 echo "Revision $id is broken, we have no content available\n";
503 $text = $content->serialize();
504 if ( $text === '' ) {
505 // This is what happens if the revision was broken at the time the
506 // dump was made. Unfortunately, it also happens if the revision was
507 // legitimately blank, so there's no way to tell the difference. To
508 // be safe, we'll skip it and leave it broken
510 echo "Revision $id is blank in the dump, may have been broken before export\n";
516 // No ID, can't import
517 echo "No id tag in revision, can't import\n";
522 // Find text row again
523 $dbr = wfGetDB( DB_REPLICA
);
524 $oldId = $dbr->selectField( 'revision', 'rev_text_id', [ 'rev_id' => $id ], __METHOD__
);
526 echo "Missing revision row for rev_id $id\n";
532 $flags = Revision
::compressRevisionText( $text );
534 // Update the text row
535 $dbw = wfGetDB( DB_MASTER
);
536 $dbw->update( 'text',
537 [ 'old_flags' => $flags, 'old_text' => $text ],
538 [ 'old_id' => $oldId ],
539 __METHOD__
, [ 'LIMIT' => 1 ]
542 // Remove it from the unfixed list and add it to the fixed list
543 unset( $this->errors
['restore text'][$id] );
544 $this->errors
['fixed'][$id] = true;