Merge "SpecialBlock [Vue]: add NamespacesField and PagesField components"
[mediawiki.git] / maintenance / storage / checkStorage.php
blob75c6c722db7fed04b391446af1d5f85f4772ef62
1 <?php
2 /**
3 * Fsck for MediaWiki
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
20 * @file
21 * @ingroup Maintenance ExternalStorage
24 use MediaWiki\Permissions\UltimateAuthority;
25 use MediaWiki\Shell\Shell;
26 use MediaWiki\User\User;
28 // @codeCoverageIgnoreStart
29 require_once __DIR__ . '/../Maintenance.php';
30 // @codeCoverageIgnoreEnd
32 // ----------------------------------------------------------------------------------
34 /**
35 * Maintenance script to do various checks on external storage.
37 * @fixme this should extend the base Maintenance class
38 * @ingroup Maintenance ExternalStorage
40 class CheckStorage extends Maintenance {
41 private const CONCAT_HEADER = 'O:27:"concatenatedgziphistoryblob"';
43 public array $oldIdMap;
44 public array $errors;
46 /** @var ExternalStoreDB */
47 public $dbStore = null;
49 public function __construct() {
50 parent::__construct();
52 $this->addOption( 'fix', 'Fix errors if possible' );
53 $this->addArg( 'xml', 'Path to an XML dump', false );
56 public function execute() {
57 $fix = $this->hasOption( 'fix' );
58 $xml = $this->getArg( 'xml', false );
59 $this->check( $fix, $xml );
62 /** @var string[] */
63 public $errorDescriptions = [
64 'restore text' => 'Damaged text, need to be restored from a backup',
65 'restore revision' => 'Damaged revision row, need to be restored from a backup',
66 'unfixable' => 'Unexpected errors with no automated fixing method',
67 'fixed' => 'Errors already fixed',
68 'fixable' => 'Errors which would already be fixed if --fix was specified',
71 public function check( $fix = false, $xml = '' ) {
72 $dbr = $this->getReplicaDB();
73 if ( $fix ) {
74 print "Checking, will fix errors if possible...\n";
75 } else {
76 print "Checking...\n";
78 $maxRevId = $dbr->newSelectQueryBuilder()
79 ->select( 'MAX(rev_id)' )
80 ->from( 'revision' )
81 ->caller( __METHOD__ )->fetchField();
82 $chunkSize = 1000;
83 $flagStats = [];
84 $objectStats = [];
85 $knownFlags = [ 'external', 'gzip', 'object', 'utf-8' ];
86 $this->errors = [
87 'restore text' => [],
88 'restore revision' => [],
89 'unfixable' => [],
90 'fixed' => [],
91 'fixable' => [],
94 for ( $chunkStart = 1; $chunkStart < $maxRevId; $chunkStart += $chunkSize ) {
95 $chunkEnd = $chunkStart + $chunkSize - 1;
96 // print "$chunkStart of $maxRevId\n";
98 $this->oldIdMap = [];
99 $dbr->ping();
101 // Fetch revision rows
102 $res = $dbr->newSelectQueryBuilder()
103 ->select( [ 'slot_revision_id', 'content_address' ] )
104 ->from( 'slots' )
105 ->join( 'content', null, 'content_id = slot_content_id' )
106 ->where( [
107 $dbr->expr( 'slot_revision_id', '>=', $chunkStart ),
108 $dbr->expr( 'slot_revision_id', '<=', $chunkEnd ),
110 ->caller( __METHOD__ )->fetchResultSet();
111 /** @var \MediaWiki\Storage\SqlBlobStore $blobStore */
112 $blobStore = $this->getServiceContainer()->getBlobStore();
113 '@phan-var \MediaWiki\Storage\SqlBlobStore $blobStore';
114 foreach ( $res as $row ) {
115 $textId = $blobStore->getTextIdFromAddress( $row->content_address );
116 if ( $textId ) {
117 if ( !isset( $this->oldIdMap[$textId] ) ) {
118 $this->oldIdMap[ $textId ] = [ $row->slot_revision_id ];
119 } elseif ( !in_array( $row->slot_revision_id, $this->oldIdMap[$textId] ) ) {
120 $this->oldIdMap[ $textId ][] = $row->slot_revision_id;
125 if ( !count( $this->oldIdMap ) ) {
126 continue;
129 // Fetch old_flags
130 $missingTextRows = $this->oldIdMap;
131 $externalRevs = [];
132 $objectRevs = [];
133 $res = $dbr->newSelectQueryBuilder()
134 ->select( [ 'old_id', 'old_flags' ] )
135 ->from( 'text' )
136 ->where( [ 'old_id' => array_keys( $this->oldIdMap ) ] )
137 ->caller( __METHOD__ )->fetchResultSet();
138 foreach ( $res as $row ) {
140 * @var int $flags
142 $flags = $row->old_flags;
143 $id = $row->old_id;
145 // Create flagStats row if it doesn't exist
146 $flagStats += [ $flags => 0 ];
147 // Increment counter
148 $flagStats[$flags]++;
150 // Not missing
151 unset( $missingTextRows[$row->old_id] );
153 // Check for external or object
154 if ( $flags == '' ) {
155 $flagArray = [];
156 } else {
157 $flagArray = explode( ',', $flags );
159 if ( in_array( 'external', $flagArray ) ) {
160 $externalRevs[] = $id;
161 } elseif ( in_array( 'object', $flagArray ) ) {
162 $objectRevs[] = $id;
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
169 if ( $fix ) {
170 $this->addError( 'fixed', "Warning: old_flags set to 0", $id );
171 $dbw = $this->getPrimaryDB();
172 $dbw->ping();
173 $dbw->newUpdateQueryBuilder()
174 ->update( 'text' )
175 ->set( [ 'old_flags' => '' ] )
176 ->where( [ 'old_id' => $id ] )
177 ->caller( __METHOD__ )
178 ->execute();
179 echo "Fixed\n";
180 } else {
181 $this->addError( 'fixable', "Warning: old_flags set to 0", $id );
183 } elseif ( count( array_diff( $flagArray, $knownFlags ) ) ) {
184 $this->addError( 'unfixable', "Error: invalid flags field \"$flags\"", $id );
188 // Output errors for any missing text rows
189 foreach ( $missingTextRows as $oldId => $revIds ) {
190 $this->addError( 'restore revision', "Error: missing text row", $oldId );
193 // Verify external revisions
194 $externalConcatBlobs = [];
195 $externalNormalBlobs = [];
196 if ( count( $externalRevs ) ) {
197 $res = $dbr->newSelectQueryBuilder()
198 ->select( [ 'old_id', 'old_flags', 'old_text' ] )
199 ->from( 'text' )
200 ->where( [ 'old_id' => $externalRevs ] )
201 ->caller( __METHOD__ )->fetchResultSet();
202 foreach ( $res as $row ) {
203 $urlParts = explode( '://', $row->old_text, 2 );
204 if ( count( $urlParts ) !== 2 || $urlParts[1] == '' ) {
205 $this->addError( 'restore text', "Error: invalid URL \"{$row->old_text}\"", $row->old_id );
206 continue;
208 [ $proto, ] = $urlParts;
209 if ( $proto != 'DB' ) {
210 $this->addError(
211 'restore text',
212 "Error: invalid external protocol \"$proto\"",
213 $row->old_id );
214 continue;
216 $path = explode( '/', $row->old_text );
217 $cluster = $path[2];
218 $id = $path[3];
219 if ( isset( $path[4] ) ) {
220 $externalConcatBlobs[$cluster][$id][] = $row->old_id;
221 } else {
222 $externalNormalBlobs[$cluster][$id][] = $row->old_id;
227 // Check external concat blobs for the right header
228 $this->checkExternalConcatBlobs( $externalConcatBlobs );
230 // Check external normal blobs for existence
231 if ( count( $externalNormalBlobs ) ) {
232 if ( $this->dbStore === null ) {
233 $esFactory = $this->getServiceContainer()->getExternalStoreFactory();
234 $this->dbStore = $esFactory->getStore( 'DB' );
236 foreach ( $externalConcatBlobs as $cluster => $xBlobIds ) {
237 $blobIds = array_keys( $xBlobIds );
238 $extDb = $this->dbStore->getReplica( $cluster );
239 $blobsTable = $this->dbStore->getTable( $cluster );
240 $res = $extDb->newSelectQueryBuilder()
241 ->select( [ 'blob_id' ] )
242 ->from( $blobsTable )
243 ->where( [ 'blob_id' => $blobIds ] )
244 ->caller( __METHOD__ )->fetchResultSet();
245 foreach ( $res as $row ) {
246 unset( $xBlobIds[$row->blob_id] );
248 // Print errors for missing blobs rows
249 foreach ( $xBlobIds as $blobId => $oldId ) {
250 $this->addError(
251 'restore text',
252 "Error: missing target $blobId for one-part ES URL",
253 $oldId );
258 // Check local objects
259 $dbr->ping();
260 $concatBlobs = [];
261 $curIds = [];
262 if ( count( $objectRevs ) ) {
263 $headerLength = 300;
264 $res = $dbr->newSelectQueryBuilder()
265 ->select( [ 'old_id', 'old_flags', "LEFT(old_text, $headerLength) AS header" ] )
266 ->from( 'text' )
267 ->where( [ 'old_id' => $objectRevs ] )
268 ->caller( __METHOD__ )->fetchResultSet();
269 foreach ( $res as $row ) {
270 $oldId = $row->old_id;
271 $matches = [];
272 if ( !preg_match( '/^O:(\d+):"(\w+)"/', $row->header, $matches ) ) {
273 $this->addError( 'restore text', "Error: invalid object header", $oldId );
274 continue;
277 $className = strtolower( $matches[2] );
278 if ( strlen( $className ) != $matches[1] ) {
279 $this->addError(
280 'restore text',
281 "Error: invalid object header, wrong class name length",
282 $oldId
284 continue;
287 $objectStats += [ $className => 0 ];
288 $objectStats[$className]++;
290 switch ( $className ) {
291 case 'concatenatedgziphistoryblob':
292 // Good
293 break;
294 case 'historyblobstub':
295 case 'historyblobcurstub':
296 if ( strlen( $row->header ) == $headerLength ) {
297 $this->addError( 'unfixable', "Error: overlong stub header", $oldId );
298 break;
300 $stubObj = unserialize( $row->header );
301 if ( !is_object( $stubObj ) ) {
302 $this->addError( 'restore text', "Error: unable to unserialize stub object", $oldId );
303 break;
305 if ( $className == 'historyblobstub' ) {
306 $concatBlobs[$stubObj->getLocation()][] = $oldId;
307 } else {
308 $curIds[$stubObj->mCurId][] = $oldId;
310 break;
311 default:
312 $this->addError( 'unfixable', "Error: unrecognised object class \"$className\"", $oldId );
317 // Check local concat blob validity
318 $externalConcatBlobs = [];
319 if ( count( $concatBlobs ) ) {
320 $headerLength = 300;
321 $res = $dbr->newSelectQueryBuilder()
322 ->select( [ 'old_id', 'old_flags', "LEFT(old_text, $headerLength) AS header" ] )
323 ->from( 'text' )
324 ->where( [ 'old_id' => array_keys( $concatBlobs ) ] )
325 ->caller( __METHOD__ )->fetchResultSet();
326 foreach ( $res as $row ) {
327 $flags = explode( ',', $row->old_flags );
328 if ( in_array( 'external', $flags ) ) {
329 // Concat blob is in external storage?
330 if ( in_array( 'object', $flags ) ) {
331 $urlParts = explode( '/', $row->header );
332 if ( $urlParts[0] != 'DB:' ) {
333 $this->addError(
334 'unfixable',
335 "Error: unrecognised external storage type \"{$urlParts[0]}",
336 $row->old_id
338 } else {
339 $cluster = $urlParts[2];
340 $id = $urlParts[3];
341 if ( !isset( $externalConcatBlobs[$cluster][$id] ) ) {
342 $externalConcatBlobs[$cluster][$id] = [];
344 $externalConcatBlobs[$cluster][$id] = array_merge(
345 $externalConcatBlobs[$cluster][$id], $concatBlobs[$row->old_id]
348 } else {
349 $this->addError(
350 'unfixable',
351 "Error: invalid flags \"{$row->old_flags}\" on concat bulk row {$row->old_id}",
352 $concatBlobs[$row->old_id] );
354 } elseif ( strcasecmp(
355 substr( $row->header, 0, strlen( self::CONCAT_HEADER ) ),
356 self::CONCAT_HEADER
357 ) ) {
358 $this->addError(
359 'restore text',
360 "Error: Incorrect object header for concat bulk row {$row->old_id}",
361 $concatBlobs[$row->old_id]
365 unset( $concatBlobs[$row->old_id] );
369 // Check targets of unresolved stubs
370 $this->checkExternalConcatBlobs( $externalConcatBlobs );
371 // next chunk
374 print "\n\nErrors:\n";
375 foreach ( $this->errors as $name => $errors ) {
376 if ( count( $errors ) ) {
377 $description = $this->errorDescriptions[$name];
378 echo "$description: " . implode( ',', array_keys( $errors ) ) . "\n";
382 if ( count( $this->errors['restore text'] ) && $fix ) {
383 if ( (string)$xml !== '' ) {
384 $this->restoreText( array_keys( $this->errors['restore text'] ), $xml );
385 } else {
386 echo "Can't fix text, no XML backup specified\n";
390 print "\nFlag statistics:\n";
391 $total = array_sum( $flagStats );
392 foreach ( $flagStats as $flag => $count ) {
393 printf( "%-30s %10d %5.2f%%\n", $flag, $count, $count / $total * 100 );
395 print "\nLocal object statistics:\n";
396 $total = array_sum( $objectStats );
397 foreach ( $objectStats as $className => $count ) {
398 printf( "%-30s %10d %5.2f%%\n", $className, $count, $count / $total * 100 );
402 private function addError( $type, $msg, $ids ) {
403 if ( is_array( $ids ) && count( $ids ) == 1 ) {
404 $ids = reset( $ids );
406 if ( is_array( $ids ) ) {
407 $revIds = [];
408 foreach ( $ids as $id ) {
409 $revIds = array_unique( array_merge( $revIds, $this->oldIdMap[$id] ) );
411 print "$msg in text rows " . implode( ', ', $ids ) .
412 ", revisions " . implode( ', ', $revIds ) . "\n";
413 } else {
414 $id = $ids;
415 $revIds = $this->oldIdMap[$id];
416 if ( count( $revIds ) == 1 ) {
417 print "$msg in old_id $id, rev_id {$revIds[0]}\n";
418 } else {
419 print "$msg in old_id $id, revisions " . implode( ', ', $revIds ) . "\n";
422 $this->errors[$type] += array_fill_keys( $revIds, true );
425 private function checkExternalConcatBlobs( $externalConcatBlobs ) {
426 if ( !count( $externalConcatBlobs ) ) {
427 return;
430 if ( $this->dbStore === null ) {
431 $esFactory = $this->getServiceContainer()->getExternalStoreFactory();
432 $this->dbStore = $esFactory->getStore( 'DB' );
435 foreach ( $externalConcatBlobs as $cluster => $oldIds ) {
436 $blobIds = array_keys( $oldIds );
437 $extDb = $this->dbStore->getReplica( $cluster );
438 $blobsTable = $this->dbStore->getTable( $cluster );
439 $headerLength = strlen( self::CONCAT_HEADER );
440 $res = $extDb->newSelectQueryBuilder()
441 ->select( [ 'blob_id', "LEFT(blob_text, $headerLength) AS header" ] )
442 ->from( $blobsTable )
443 ->where( [ 'blob_id' => $blobIds ] )
444 ->caller( __METHOD__ )->fetchResultSet();
445 foreach ( $res as $row ) {
446 if ( strcasecmp( $row->header, self::CONCAT_HEADER ) ) {
447 $this->addError(
448 'restore text',
449 "Error: invalid header on target $cluster/{$row->blob_id} of two-part ES URL",
450 $oldIds[$row->blob_id]
453 unset( $oldIds[$row->blob_id] );
456 // Print errors for missing blobs rows
457 foreach ( $oldIds as $blobId => $oldIds2 ) {
458 $this->addError(
459 'restore text',
460 "Error: missing target $cluster/$blobId for two-part ES URL",
461 $oldIds2
467 private function restoreText( $revIds, $xml ) {
468 global $wgDBname;
469 $tmpDir = wfTempDir();
471 if ( !count( $revIds ) ) {
472 return;
475 print "Restoring text from XML backup...\n";
477 $revFileName = "$tmpDir/broken-revlist-$wgDBname";
478 $filteredXmlFileName = "$tmpDir/filtered-$wgDBname.xml";
480 // Write revision list
481 if ( !file_put_contents( $revFileName, implode( "\n", $revIds ) ) ) {
482 echo "Error writing revision list, can't restore text\n";
484 return;
487 // Run mwdumper
488 echo "Filtering XML dump...\n";
489 $exitStatus = 0;
490 // phpcs:ignore MediaWiki.Usage.ForbiddenFunctions.passthru
491 passthru( 'mwdumper ' .
492 Shell::escape(
493 "--output=file:$filteredXmlFileName",
494 "--filter=revlist:$revFileName",
495 $xml
496 ), $exitStatus
499 if ( $exitStatus ) {
500 echo "mwdumper died with exit status $exitStatus\n";
502 return;
505 $file = fopen( $filteredXmlFileName, 'r' );
506 if ( !$file ) {
507 echo "Unable to open filtered XML file\n";
509 return;
512 $dbr = $this->getReplicaDB();
513 $dbw = $this->getPrimaryDB();
514 $dbr->ping();
515 $dbw->ping();
517 $source = new ImportStreamSource( $file );
518 $user = User::newSystemUser( User::MAINTENANCE_SCRIPT_USER, [ 'steal' => true ] );
519 $importer = $this->getServiceContainer()
520 ->getWikiImporterFactory()
521 ->getWikiImporter( $source, new UltimateAuthority( $user ) );
522 $importer->setRevisionCallback( [ $this, 'importRevision' ] );
523 $importer->setNoticeCallback( static function ( $msg, $params ) {
524 echo wfMessage( $msg, $params )->text() . "\n";
525 } );
526 $importer->doImport();
530 * @param WikiRevision $revision
532 public function importRevision( $revision ) {
533 $id = $revision->getID();
534 $content = $revision->getContent();
535 $id = $id ?: '';
537 if ( $content === null ) {
538 echo "Revision $id is broken, we have no content available\n";
540 return;
543 $text = $content->serialize();
544 if ( $text === '' ) {
545 // This is what happens if the revision was broken at the time the
546 // dump was made. Unfortunately, it also happens if the revision was
547 // legitimately blank, so there's no way to tell the difference. To
548 // be safe, we'll skip it and leave it broken
550 echo "Revision $id is blank in the dump, may have been broken before export\n";
552 return;
555 if ( !$id ) {
556 // No ID, can't import
557 echo "No id tag in revision, can't import\n";
559 return;
562 // Find text row again
563 $dbr = $this->getReplicaDB();
564 $res = $dbr->newSelectQueryBuilder()
565 ->select( [ 'content_address' ] )
566 ->from( 'slots' )
567 ->join( 'content', null, 'content_id = slot_content_id' )
568 ->where( [ 'slot_revision_id' => $id ] )
569 ->caller( __METHOD__ )->fetchRow();
571 $blobStore = $this->getServiceContainer()
572 ->getBlobStoreFactory()
573 ->newSqlBlobStore();
574 $oldId = $blobStore->getTextIdFromAddress( $res->content_address );
576 if ( !$oldId ) {
577 echo "Missing revision row for rev_id $id\n";
578 return;
581 // Compress the text
582 $flags = $blobStore->compressData( $text );
584 // Update the text row
585 $dbw = $this->getPrimaryDB();
586 $dbw->newUpdateQueryBuilder()
587 ->update( 'text' )
588 ->set( [ 'old_flags' => $flags, 'old_text' => $text ] )
589 ->where( [ 'old_id' => $oldId ] )
590 ->caller( __METHOD__ )
591 ->execute();
593 // Remove it from the unfixed list and add it to the fixed list
594 unset( $this->errors['restore text'][$id] );
595 $this->errors['fixed'][$id] = true;
600 // @codeCoverageIgnoreStart
601 $maintClass = CheckStorage::class;
602 require_once RUN_MAINTENANCE_IF_MAIN;
603 // @codeCoverageIgnoreEnd