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
;
26 if ( !defined( 'MEDIAWIKI' ) ) {
27 $optionsWithoutArgs = [ 'fix' ];
28 require_once __DIR__
. '/../commandLine.inc';
30 $cs = new CheckStorage
;
31 $fix = isset( $options['fix'] );
32 $xml = $args[0] ??
false;
33 $cs->check( $fix, $xml );
36 // ----------------------------------------------------------------------------------
39 * Maintenance script to do various checks on external storage.
41 * @fixme this should extend the base Maintenance class
42 * @ingroup Maintenance ExternalStorage
45 const CONCAT_HEADER
= 'O:27:"concatenatedgziphistoryblob"';
46 public $oldIdMap, $errors;
47 public $dbStore = null;
49 public $errorDescriptions = [
50 'restore text' => 'Damaged text, need to be restored from a backup',
51 'restore revision' => 'Damaged revision row, need to be restored from a backup',
52 'unfixable' => 'Unexpected errors with no automated fixing method',
53 'fixed' => 'Errors already fixed',
54 'fixable' => 'Errors which would already be fixed if --fix was specified',
57 function check( $fix = false, $xml = '' ) {
58 $dbr = wfGetDB( DB_REPLICA
);
60 print "Checking, will fix errors if possible...\n";
62 print "Checking...\n";
64 $maxRevId = $dbr->selectField( 'revision', 'MAX(rev_id)', '', __METHOD__
);
68 $knownFlags = [ 'external', 'gzip', 'object', 'utf-8' ];
71 'restore revision' => [],
77 for ( $chunkStart = 1; $chunkStart < $maxRevId; $chunkStart +
= $chunkSize ) {
78 $chunkEnd = $chunkStart +
$chunkSize - 1;
79 // print "$chunkStart of $maxRevId\n";
81 // Fetch revision rows
84 $res = $dbr->select( 'revision', [ 'rev_id', 'rev_text_id' ],
85 [ "rev_id BETWEEN $chunkStart AND $chunkEnd" ], __METHOD__
);
86 foreach ( $res as $row ) {
87 $this->oldIdMap
[$row->rev_id
] = $row->rev_text_id
;
90 if ( !count( $this->oldIdMap
) ) {
95 $missingTextRows = array_flip( $this->oldIdMap
);
100 [ 'old_id', 'old_flags' ],
101 [ 'old_id' => $this->oldIdMap
],
104 foreach ( $res as $row ) {
108 $flags = $row->old_flags
;
111 // Create flagStats row if it doesn't exist
112 $flagStats = $flagStats +
[ $flags => 0 ];
114 $flagStats[$flags]++
;
117 unset( $missingTextRows[$row->old_id
] );
119 // Check for external or object
120 if ( $flags == '' ) {
123 $flagArray = explode( ',', $flags );
125 if ( in_array( 'external', $flagArray ) ) {
126 $externalRevs[] = $id;
127 } elseif ( in_array( 'object', $flagArray ) ) {
131 // Check for unrecognised flags
132 if ( $flags == '0' ) {
133 // This is a known bug from 2004
134 // It's safe to just erase the old_flags field
136 $this->addError( 'fixed', "Warning: old_flags set to 0", $id );
137 $dbw = wfGetDB( DB_MASTER
);
139 $dbw->update( 'text', [ 'old_flags' => '' ],
140 [ 'old_id' => $id ], __METHOD__
);
143 $this->addError( 'fixable', "Warning: old_flags set to 0", $id );
145 } elseif ( count( array_diff( $flagArray, $knownFlags ) ) ) {
146 $this->addError( 'unfixable', "Error: invalid flags field \"$flags\"", $id );
150 // Output errors for any missing text rows
151 foreach ( $missingTextRows as $oldId => $revId ) {
152 $this->addError( 'restore revision', "Error: missing text row", $oldId );
155 // Verify external revisions
156 $externalConcatBlobs = [];
157 $externalNormalBlobs = [];
158 if ( count( $externalRevs ) ) {
161 [ 'old_id', 'old_flags', 'old_text' ],
162 [ 'old_id' => $externalRevs ],
165 foreach ( $res as $row ) {
166 $urlParts = explode( '://', $row->old_text
, 2 );
167 if ( count( $urlParts ) !== 2 ||
$urlParts[1] == '' ) {
168 $this->addError( 'restore text', "Error: invalid URL \"{$row->old_text}\"", $row->old_id
);
171 list( $proto, ) = $urlParts;
172 if ( $proto != 'DB' ) {
175 "Error: invalid external protocol \"$proto\"",
179 $path = explode( '/', $row->old_text
);
182 if ( isset( $path[4] ) ) {
183 $externalConcatBlobs[$cluster][$id][] = $row->old_id
;
185 $externalNormalBlobs[$cluster][$id][] = $row->old_id
;
190 // Check external concat blobs for the right header
191 $this->checkExternalConcatBlobs( $externalConcatBlobs );
193 // Check external normal blobs for existence
194 if ( count( $externalNormalBlobs ) ) {
195 if ( is_null( $this->dbStore
) ) {
196 $this->dbStore
= new ExternalStoreDB
;
198 foreach ( $externalConcatBlobs as $cluster => $xBlobIds ) {
199 $blobIds = array_keys( $xBlobIds );
200 $extDb =& $this->dbStore
->getSlave( $cluster );
201 $blobsTable = $this->dbStore
->getTable( $extDb );
202 $res = $extDb->select( $blobsTable,
204 [ 'blob_id' => $blobIds ],
207 foreach ( $res as $row ) {
208 unset( $xBlobIds[$row->blob_id
] );
210 // Print errors for missing blobs rows
211 foreach ( $xBlobIds as $blobId => $oldId ) {
214 "Error: missing target $blobId for one-part ES URL",
220 // Check local objects
224 if ( count( $objectRevs ) ) {
228 [ 'old_id', 'old_flags', "LEFT(old_text, $headerLength) AS header" ],
229 [ 'old_id' => $objectRevs ],
232 foreach ( $res as $row ) {
233 $oldId = $row->old_id
;
235 if ( !preg_match( '/^O:(\d+):"(\w+)"/', $row->header
, $matches ) ) {
236 $this->addError( 'restore text', "Error: invalid object header", $oldId );
240 $className = strtolower( $matches[2] );
241 if ( strlen( $className ) != $matches[1] ) {
244 "Error: invalid object header, wrong class name length",
250 $objectStats = $objectStats +
[ $className => 0 ];
251 $objectStats[$className]++
;
253 switch ( $className ) {
254 case 'concatenatedgziphistoryblob':
257 case 'historyblobstub':
258 case 'historyblobcurstub':
259 if ( strlen( $row->header
) == $headerLength ) {
260 $this->addError( 'unfixable', "Error: overlong stub header", $oldId );
263 $stubObj = unserialize( $row->header
);
264 if ( !is_object( $stubObj ) ) {
265 $this->addError( 'restore text', "Error: unable to unserialize stub object", $oldId );
268 if ( $className == 'historyblobstub' ) {
269 $concatBlobs[$stubObj->mOldId
][] = $oldId;
271 $curIds[$stubObj->mCurId
][] = $oldId;
275 $this->addError( 'unfixable', "Error: unrecognised object class \"$className\"", $oldId );
280 // Check local concat blob validity
281 $externalConcatBlobs = [];
282 if ( count( $concatBlobs ) ) {
286 [ 'old_id', 'old_flags', "LEFT(old_text, $headerLength) AS header" ],
287 [ 'old_id' => array_keys( $concatBlobs ) ],
290 foreach ( $res as $row ) {
291 $flags = explode( ',', $row->old_flags
);
292 if ( in_array( 'external', $flags ) ) {
293 // Concat blob is in external storage?
294 if ( in_array( 'object', $flags ) ) {
295 $urlParts = explode( '/', $row->header
);
296 if ( $urlParts[0] != 'DB:' ) {
299 "Error: unrecognised external storage type \"{$urlParts[0]}",
303 $cluster = $urlParts[2];
305 if ( !isset( $externalConcatBlobs[$cluster][$id] ) ) {
306 $externalConcatBlobs[$cluster][$id] = [];
308 $externalConcatBlobs[$cluster][$id] = array_merge(
309 $externalConcatBlobs[$cluster][$id], $concatBlobs[$row->old_id
]
315 "Error: invalid flags \"{$row->old_flags}\" on concat bulk row {$row->old_id}",
316 $concatBlobs[$row->old_id
] );
318 } elseif ( strcasecmp(
319 substr( $row->header
, 0, strlen( self
::CONCAT_HEADER
) ),
324 "Error: Incorrect object header for concat bulk row {$row->old_id}",
325 $concatBlobs[$row->old_id
]
329 unset( $concatBlobs[$row->old_id
] );
333 // Check targets of unresolved stubs
334 $this->checkExternalConcatBlobs( $externalConcatBlobs );
338 print "\n\nErrors:\n";
339 foreach ( $this->errors
as $name => $errors ) {
340 if ( count( $errors ) ) {
341 $description = $this->errorDescriptions
[$name];
342 echo "$description: " . implode( ',', array_keys( $errors ) ) . "\n";
346 if ( count( $this->errors
['restore text'] ) && $fix ) {
347 if ( (string)$xml !== '' ) {
348 $this->restoreText( array_keys( $this->errors
['restore text'] ), $xml );
350 echo "Can't fix text, no XML backup specified\n";
354 print "\nFlag statistics:\n";
355 $total = array_sum( $flagStats );
356 foreach ( $flagStats as $flag => $count ) {
357 printf( "%-30s %10d %5.2f%%\n", $flag, $count, $count / $total * 100 );
359 print "\nLocal object statistics:\n";
360 $total = array_sum( $objectStats );
361 foreach ( $objectStats as $className => $count ) {
362 printf( "%-30s %10d %5.2f%%\n", $className, $count, $count / $total * 100 );
366 function addError( $type, $msg, $ids ) {
367 if ( is_array( $ids ) && count( $ids ) == 1 ) {
368 $ids = reset( $ids );
370 if ( is_array( $ids ) ) {
372 foreach ( $ids as $id ) {
373 $revIds = array_merge( $revIds, array_keys( $this->oldIdMap
, $id ) );
375 print "$msg in text rows " . implode( ', ', $ids ) .
376 ", revisions " . implode( ', ', $revIds ) . "\n";
379 $revIds = array_keys( $this->oldIdMap
, $id );
380 if ( count( $revIds ) == 1 ) {
381 print "$msg in old_id $id, rev_id {$revIds[0]}\n";
383 print "$msg in old_id $id, revisions " . implode( ', ', $revIds ) . "\n";
386 $this->errors
[$type] = $this->errors
[$type] +
array_flip( $revIds );
389 function checkExternalConcatBlobs( $externalConcatBlobs ) {
390 if ( !count( $externalConcatBlobs ) ) {
394 if ( is_null( $this->dbStore
) ) {
395 $this->dbStore
= new ExternalStoreDB
;
398 foreach ( $externalConcatBlobs as $cluster => $oldIds ) {
399 $blobIds = array_keys( $oldIds );
400 $extDb =& $this->dbStore
->getSlave( $cluster );
401 $blobsTable = $this->dbStore
->getTable( $extDb );
402 $headerLength = strlen( self
::CONCAT_HEADER
);
403 $res = $extDb->select( $blobsTable,
404 [ 'blob_id', "LEFT(blob_text, $headerLength) AS header" ],
405 [ 'blob_id' => $blobIds ],
408 foreach ( $res as $row ) {
409 if ( strcasecmp( $row->header
, self
::CONCAT_HEADER
) ) {
412 "Error: invalid header on target $cluster/{$row->blob_id} of two-part ES URL",
413 $oldIds[$row->blob_id
]
416 unset( $oldIds[$row->blob_id
] );
419 // Print errors for missing blobs rows
420 foreach ( $oldIds as $blobId => $oldIds2 ) {
423 "Error: missing target $cluster/$blobId for two-part ES URL",
430 function restoreText( $revIds, $xml ) {
432 $tmpDir = wfTempDir();
434 if ( !count( $revIds ) ) {
438 print "Restoring text from XML backup...\n";
440 $revFileName = "$tmpDir/broken-revlist-$wgDBname";
441 $filteredXmlFileName = "$tmpDir/filtered-$wgDBname.xml";
443 // Write revision list
444 if ( !file_put_contents( $revFileName, implode( "\n", $revIds ) ) ) {
445 echo "Error writing revision list, can't restore text\n";
451 echo "Filtering XML dump...\n";
453 passthru( 'mwdumper ' .
455 "--output=file:$filteredXmlFileName",
456 "--filter=revlist:$revFileName",
462 echo "mwdumper died with exit status $exitStatus\n";
467 $file = fopen( $filteredXmlFileName, 'r' );
469 echo "Unable to open filtered XML file\n";
474 $dbr = wfGetDB( DB_REPLICA
);
475 $dbw = wfGetDB( DB_MASTER
);
479 $source = new ImportStreamSource( $file );
480 $importer = new WikiImporter(
482 MediaWikiServices
::getInstance()->getMainConfig()
484 $importer->setRevisionCallback( [ $this, 'importRevision' ] );
485 $importer->setNoticeCallback( function ( $msg, $params ) {
486 echo wfMessage( $msg, $params )->text() . "\n";
488 $importer->doImport();
491 function importRevision( &$revision, &$importer ) {
492 $id = $revision->getID();
493 $content = $revision->getContent( Revision
::RAW
);
496 if ( $content === null ) {
497 echo "Revision $id is broken, we have no content available\n";
502 $text = $content->serialize();
503 if ( $text === '' ) {
504 // This is what happens if the revision was broken at the time the
505 // dump was made. Unfortunately, it also happens if the revision was
506 // legitimately blank, so there's no way to tell the difference. To
507 // be safe, we'll skip it and leave it broken
509 echo "Revision $id is blank in the dump, may have been broken before export\n";
515 // No ID, can't import
516 echo "No id tag in revision, can't import\n";
521 // Find text row again
522 $dbr = wfGetDB( DB_REPLICA
);
523 $oldId = $dbr->selectField( 'revision', 'rev_text_id', [ 'rev_id' => $id ], __METHOD__
);
525 echo "Missing revision row for rev_id $id\n";
531 $flags = Revision
::compressRevisionText( $text );
533 // Update the text row
534 $dbw = wfGetDB( DB_MASTER
);
535 $dbw->update( 'text',
536 [ 'old_flags' => $flags, 'old_text' => $text ],
537 [ 'old_id' => $oldId ],
538 __METHOD__
, [ 'LIMIT' => 1 ]
541 // Remove it from the unfixed list and add it to the fixed list
542 unset( $this->errors
['restore text'][$id] );
543 $this->errors
['fixed'][$id] = true;