MediaWiki master
checkStorage.php
Go to the documentation of this file.
1<?php
14
15// @codeCoverageIgnoreStart
16require_once __DIR__ . '/../Maintenance.php';
17// @codeCoverageIgnoreEnd
18
19// ----------------------------------------------------------------------------------
20
28 private const CONCAT_HEADER = 'O:27:"concatenatedgziphistoryblob"';
29
30 public array $oldIdMap;
31 public array $errors;
32
34 public $dbStore = null;
35
36 public function __construct() {
37 parent::__construct();
38
39 $this->addOption( 'fix', 'Fix errors if possible' );
40 $this->addArg( 'xml', 'Path to an XML dump', false );
41 }
42
43 public function execute() {
44 $fix = $this->hasOption( 'fix' );
45 $xml = $this->getArg( 'xml', false );
46 $this->check( $fix, $xml );
47 }
48
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',
56 ];
57
58 public function check( bool $fix = false, string|false $xml = '' ) {
59 $dbr = $this->getReplicaDB();
60 if ( $fix ) {
61 print "Checking, will fix errors if possible...\n";
62 } else {
63 print "Checking...\n";
64 }
65 $maxRevId = $dbr->newSelectQueryBuilder()
66 ->select( 'MAX(rev_id)' )
67 ->from( 'revision' )
68 ->caller( __METHOD__ )->fetchField();
69 $chunkSize = 1000;
70 $flagStats = [];
71 $objectStats = [];
72 $knownFlags = [ 'external', 'gzip', 'object', 'utf-8' ];
73 $this->errors = [
74 'restore text' => [],
75 'restore revision' => [],
76 'unfixable' => [],
77 'fixed' => [],
78 'fixable' => [],
79 ];
80
81 for ( $chunkStart = 1; $chunkStart < $maxRevId; $chunkStart += $chunkSize ) {
82 $chunkEnd = $chunkStart + $chunkSize - 1;
83 // print "$chunkStart of $maxRevId\n";
84
85 $this->oldIdMap = [];
86 $dbr->ping();
87
88 // Fetch revision rows
89 $res = $dbr->newSelectQueryBuilder()
90 ->select( [ 'slot_revision_id', 'content_address' ] )
91 ->from( 'slots' )
92 ->join( 'content', null, 'content_id = slot_content_id' )
93 ->where( [
94 $dbr->expr( 'slot_revision_id', '>=', $chunkStart ),
95 $dbr->expr( 'slot_revision_id', '<=', $chunkEnd ),
96 ] )
97 ->caller( __METHOD__ )->fetchResultSet();
99 $blobStore = $this->getServiceContainer()->getBlobStore();
100 '@phan-var \MediaWiki\Storage\SqlBlobStore $blobStore';
101 foreach ( $res as $row ) {
102 $textId = $blobStore->getTextIdFromAddress( $row->content_address );
103 if ( $textId ) {
104 if ( !isset( $this->oldIdMap[$textId] ) ) {
105 $this->oldIdMap[ $textId ] = [ $row->slot_revision_id ];
106 } elseif ( !in_array( $row->slot_revision_id, $this->oldIdMap[$textId] ) ) {
107 $this->oldIdMap[ $textId ][] = $row->slot_revision_id;
108 }
109 }
110 }
111
112 if ( !count( $this->oldIdMap ) ) {
113 continue;
114 }
115
116 // Fetch old_flags
117 $missingTextRows = $this->oldIdMap;
118 $externalRevs = [];
119 $objectRevs = [];
120 $res = $dbr->newSelectQueryBuilder()
121 ->select( [ 'old_id', 'old_flags' ] )
122 ->from( 'text' )
123 ->where( [ 'old_id' => array_keys( $this->oldIdMap ) ] )
124 ->caller( __METHOD__ )->fetchResultSet();
125 foreach ( $res as $row ) {
129 $flags = $row->old_flags;
130 $id = $row->old_id;
131
132 // Create flagStats row if it doesn't exist
133 $flagStats += [ $flags => 0 ];
134 // Increment counter
135 $flagStats[$flags]++;
136
137 // Not missing
138 unset( $missingTextRows[$row->old_id] );
139
140 // Check for external or object
141 if ( $flags == '' ) {
142 $flagArray = [];
143 } else {
144 $flagArray = explode( ',', $flags );
145 }
146 if ( in_array( 'external', $flagArray ) ) {
147 $externalRevs[] = $id;
148 } elseif ( in_array( 'object', $flagArray ) ) {
149 $objectRevs[] = $id;
150 }
151
152 // Check for unrecognised flags
153 if ( $flags == '0' ) {
154 // This is a known bug from 2004
155 // It's safe to just erase the old_flags field
156 if ( $fix ) {
157 $this->addError( 'fixed', "Warning: old_flags set to 0", $id );
158 $dbw = $this->getPrimaryDB();
159 $dbw->ping();
160 $dbw->newUpdateQueryBuilder()
161 ->update( 'text' )
162 ->set( [ 'old_flags' => '' ] )
163 ->where( [ 'old_id' => $id ] )
164 ->caller( __METHOD__ )
165 ->execute();
166 echo "Fixed\n";
167 } else {
168 $this->addError( 'fixable', "Warning: old_flags set to 0", $id );
169 }
170 } elseif ( count( array_diff( $flagArray, $knownFlags ) ) ) {
171 $this->addError( 'unfixable', "Error: invalid flags field \"$flags\"", $id );
172 }
173 }
174
175 // Output errors for any missing text rows
176 foreach ( $missingTextRows as $oldId => $revIds ) {
177 $this->addError( 'restore revision', "Error: missing text row", $oldId );
178 }
179
180 // Verify external revisions
181 $externalConcatBlobs = [];
182 $externalNormalBlobs = [];
183 if ( count( $externalRevs ) ) {
184 $res = $dbr->newSelectQueryBuilder()
185 ->select( [ 'old_id', 'old_flags', 'old_text' ] )
186 ->from( 'text' )
187 ->where( [ 'old_id' => $externalRevs ] )
188 ->caller( __METHOD__ )->fetchResultSet();
189 foreach ( $res as $row ) {
190 $urlParts = explode( '://', $row->old_text, 2 );
191 if ( count( $urlParts ) !== 2 || $urlParts[1] == '' ) {
192 $this->addError( 'restore text', "Error: invalid URL \"{$row->old_text}\"", $row->old_id );
193 continue;
194 }
195 [ $proto, ] = $urlParts;
196 if ( $proto != 'DB' ) {
197 $this->addError(
198 'restore text',
199 "Error: invalid external protocol \"$proto\"",
200 $row->old_id );
201 continue;
202 }
203 $path = explode( '/', $row->old_text );
204 $cluster = $path[2];
205 $id = $path[3];
206 if ( isset( $path[4] ) ) {
207 $externalConcatBlobs[$cluster][$id][] = $row->old_id;
208 } else {
209 $externalNormalBlobs[$cluster][$id][] = $row->old_id;
210 }
211 }
212 }
213
214 // Check external concat blobs for the right header
215 $this->checkExternalConcatBlobs( $externalConcatBlobs );
216
217 // Check external normal blobs for existence
218 if ( count( $externalNormalBlobs ) ) {
219 if ( $this->dbStore === null ) {
220 $esFactory = $this->getServiceContainer()->getExternalStoreFactory();
221 $this->dbStore = $esFactory->getDatabaseStore();
222 }
223 foreach ( $externalConcatBlobs as $cluster => $xBlobIds ) {
224 $blobIds = array_keys( $xBlobIds );
225 $extDb = $this->dbStore->getReplica( $cluster );
226 $blobsTable = $this->dbStore->getTable( $cluster );
227 $res = $extDb->newSelectQueryBuilder()
228 ->select( [ 'blob_id' ] )
229 ->from( $blobsTable )
230 ->where( [ 'blob_id' => $blobIds ] )
231 ->caller( __METHOD__ )->fetchResultSet();
232 foreach ( $res as $row ) {
233 unset( $xBlobIds[$row->blob_id] );
234 }
235 // Print errors for missing blobs rows
236 foreach ( $xBlobIds as $blobId => $oldId ) {
237 $this->addError(
238 'restore text',
239 "Error: missing target $blobId for one-part ES URL",
240 $oldId );
241 }
242 }
243 }
244
245 // Check local objects
246 $dbr->ping();
247 $concatBlobs = [];
248 $curIds = [];
249 if ( count( $objectRevs ) ) {
250 $headerLength = 300;
251 $res = $dbr->newSelectQueryBuilder()
252 ->select( [ 'old_id', 'old_flags', "LEFT(old_text, $headerLength) AS header" ] )
253 ->from( 'text' )
254 ->where( [ 'old_id' => $objectRevs ] )
255 ->caller( __METHOD__ )->fetchResultSet();
256 foreach ( $res as $row ) {
257 $oldId = $row->old_id;
258 $matches = [];
259 if ( !preg_match( '/^O:(\d+):"(\w+)"/', $row->header, $matches ) ) {
260 $this->addError( 'restore text', "Error: invalid object header", $oldId );
261 continue;
262 }
263
264 $className = strtolower( $matches[2] );
265 if ( strlen( $className ) != $matches[1] ) {
266 $this->addError(
267 'restore text',
268 "Error: invalid object header, wrong class name length",
269 $oldId
270 );
271 continue;
272 }
273
274 $objectStats += [ $className => 0 ];
275 $objectStats[$className]++;
276
277 switch ( $className ) {
278 case 'concatenatedgziphistoryblob':
279 // Good
280 break;
281 case 'historyblobstub':
282 case 'historyblobcurstub':
283 if ( strlen( $row->header ) == $headerLength ) {
284 $this->addError( 'unfixable', "Error: overlong stub header", $oldId );
285 break;
286 }
287 $stubObj = unserialize( $row->header );
288 if ( !is_object( $stubObj ) ) {
289 $this->addError( 'restore text', "Error: unable to unserialize stub object", $oldId );
290 break;
291 }
292 if ( $className == 'historyblobstub' ) {
293 $concatBlobs[$stubObj->getLocation()][] = $oldId;
294 } else {
295 $curIds[$stubObj->mCurId][] = $oldId;
296 }
297 break;
298 default:
299 $this->addError( 'unfixable', "Error: unrecognised object class \"$className\"", $oldId );
300 }
301 }
302 }
303
304 // Check local concat blob validity
305 $externalConcatBlobs = [];
306 if ( count( $concatBlobs ) ) {
307 $headerLength = 300;
308 $res = $dbr->newSelectQueryBuilder()
309 ->select( [ 'old_id', 'old_flags', "LEFT(old_text, $headerLength) AS header" ] )
310 ->from( 'text' )
311 ->where( [ 'old_id' => array_keys( $concatBlobs ) ] )
312 ->caller( __METHOD__ )->fetchResultSet();
313 foreach ( $res as $row ) {
314 $flags = explode( ',', $row->old_flags );
315 if ( in_array( 'external', $flags ) ) {
316 // Concat blob is in external storage?
317 if ( in_array( 'object', $flags ) ) {
318 $urlParts = explode( '/', $row->header );
319 if ( $urlParts[0] != 'DB:' ) {
320 $this->addError(
321 'unfixable',
322 "Error: unrecognised external storage type \"{$urlParts[0]}",
323 $row->old_id
324 );
325 } else {
326 $cluster = $urlParts[2];
327 $id = $urlParts[3];
328 if ( !isset( $externalConcatBlobs[$cluster][$id] ) ) {
329 $externalConcatBlobs[$cluster][$id] = [];
330 }
331 $externalConcatBlobs[$cluster][$id] = array_merge(
332 $externalConcatBlobs[$cluster][$id], $concatBlobs[$row->old_id]
333 );
334 }
335 } else {
336 $this->addError(
337 'unfixable',
338 "Error: invalid flags \"{$row->old_flags}\" on concat bulk row {$row->old_id}",
339 $concatBlobs[$row->old_id] );
340 }
341 } elseif ( strcasecmp(
342 substr( $row->header, 0, strlen( self::CONCAT_HEADER ) ),
343 self::CONCAT_HEADER
344 ) ) {
345 $this->addError(
346 'restore text',
347 "Error: Incorrect object header for concat bulk row {$row->old_id}",
348 $concatBlobs[$row->old_id]
349 );
350 }
351
352 unset( $concatBlobs[$row->old_id] );
353 }
354 }
355
356 // Check targets of unresolved stubs
357 $this->checkExternalConcatBlobs( $externalConcatBlobs );
358 // next chunk
359 }
360
361 print "\n\nErrors:\n";
362 foreach ( $this->errors as $name => $errors ) {
363 if ( count( $errors ) ) {
364 $description = $this->errorDescriptions[$name];
365 echo "$description: " . implode( ',', array_keys( $errors ) ) . "\n";
366 }
367 }
368
369 if ( count( $this->errors['restore text'] ) && $fix ) {
370 if ( (string)$xml !== '' ) {
371 $this->restoreText( array_keys( $this->errors['restore text'] ), $xml );
372 } else {
373 echo "Can't fix text, no XML backup specified\n";
374 }
375 }
376
377 print "\nFlag statistics:\n";
378 $total = array_sum( $flagStats );
379 foreach ( $flagStats as $flag => $count ) {
380 printf( "%-30s %10d %5.2f%%\n", $flag, $count, $count / $total * 100 );
381 }
382 print "\nLocal object statistics:\n";
383 $total = array_sum( $objectStats );
384 foreach ( $objectStats as $className => $count ) {
385 printf( "%-30s %10d %5.2f%%\n", $className, $count, $count / $total * 100 );
386 }
387 }
388
394 private function addError( string $type, string $msg, $ids ) {
395 if ( is_array( $ids ) && count( $ids ) == 1 ) {
396 $ids = reset( $ids );
397 }
398 if ( is_array( $ids ) ) {
399 $revIds = [];
400 foreach ( $ids as $id ) {
401 $revIds = array_unique( array_merge( $revIds, $this->oldIdMap[$id] ) );
402 }
403 print "$msg in text rows " . implode( ', ', $ids ) .
404 ", revisions " . implode( ', ', $revIds ) . "\n";
405 } else {
406 $id = $ids;
407 $revIds = $this->oldIdMap[$id];
408 if ( count( $revIds ) == 1 ) {
409 print "$msg in old_id $id, rev_id {$revIds[0]}\n";
410 } else {
411 print "$msg in old_id $id, revisions " . implode( ', ', $revIds ) . "\n";
412 }
413 }
414 $this->errors[$type] += array_fill_keys( $revIds, true );
415 }
416
417 private function checkExternalConcatBlobs( array $externalConcatBlobs ) {
418 if ( !count( $externalConcatBlobs ) ) {
419 return;
420 }
421
422 if ( $this->dbStore === null ) {
423 $esFactory = $this->getServiceContainer()->getExternalStoreFactory();
424 $this->dbStore = $esFactory->getDatabaseStore();
425 }
426
427 foreach ( $externalConcatBlobs as $cluster => $oldIds ) {
428 $blobIds = array_keys( $oldIds );
429 $extDb = $this->dbStore->getReplica( $cluster );
430 $blobsTable = $this->dbStore->getTable( $cluster );
431 $headerLength = strlen( self::CONCAT_HEADER );
432 $res = $extDb->newSelectQueryBuilder()
433 ->select( [ 'blob_id', "LEFT(blob_text, $headerLength) AS header" ] )
434 ->from( $blobsTable )
435 ->where( [ 'blob_id' => $blobIds ] )
436 ->caller( __METHOD__ )->fetchResultSet();
437 foreach ( $res as $row ) {
438 if ( strcasecmp( $row->header, self::CONCAT_HEADER ) ) {
439 $this->addError(
440 'restore text',
441 "Error: invalid header on target $cluster/{$row->blob_id} of two-part ES URL",
442 $oldIds[$row->blob_id]
443 );
444 }
445 unset( $oldIds[$row->blob_id] );
446 }
447
448 // Print errors for missing blobs rows
449 foreach ( $oldIds as $blobId => $oldIds2 ) {
450 $this->addError(
451 'restore text',
452 "Error: missing target $cluster/$blobId for two-part ES URL",
453 $oldIds2
454 );
455 }
456 }
457 }
458
459 private function restoreText( array $revIds, string $xml ) {
460 global $wgDBname;
461 $tmpDir = wfTempDir();
462
463 if ( !count( $revIds ) ) {
464 return;
465 }
466
467 print "Restoring text from XML backup...\n";
468
469 $revFileName = "$tmpDir/broken-revlist-$wgDBname";
470 $filteredXmlFileName = "$tmpDir/filtered-$wgDBname.xml";
471
472 // Write revision list
473 if ( !file_put_contents( $revFileName, implode( "\n", $revIds ) ) ) {
474 echo "Error writing revision list, can't restore text\n";
475
476 return;
477 }
478
479 // Run mwdumper
480 echo "Filtering XML dump...\n";
481 $exitStatus = 0;
482 // phpcs:ignore MediaWiki.Usage.ForbiddenFunctions.passthru
483 passthru( 'mwdumper ' .
484 Shell::escape(
485 "--output=file:$filteredXmlFileName",
486 "--filter=revlist:$revFileName",
487 $xml
488 ), $exitStatus
489 );
490
491 if ( $exitStatus ) {
492 echo "mwdumper died with exit status $exitStatus\n";
493
494 return;
495 }
496
497 $file = fopen( $filteredXmlFileName, 'r' );
498 if ( !$file ) {
499 echo "Unable to open filtered XML file\n";
500
501 return;
502 }
503
504 $dbr = $this->getReplicaDB();
505 $dbw = $this->getPrimaryDB();
506 $dbr->ping();
507 $dbw->ping();
508
509 $source = new ImportStreamSource( $file );
510 $user = User::newSystemUser( User::MAINTENANCE_SCRIPT_USER, [ 'steal' => true ] );
511 $importer = $this->getServiceContainer()
512 ->getWikiImporterFactory()
513 ->getWikiImporter( $source, new UltimateAuthority( $user ) );
514 $importer->setRevisionCallback( $this->importRevision( ... ) );
515 $importer->setNoticeCallback( static function ( $msg, $params ) {
516 echo wfMessage( $msg, $params )->text() . "\n";
517 } );
518 $importer->doImport();
519 }
520
524 private function importRevision( $revision ) {
525 $id = $revision->getID();
526 $content = $revision->getContent();
527 $id = $id ?: '';
528
529 if ( $content === null ) {
530 echo "Revision $id is broken, we have no content available\n";
531
532 return;
533 }
534
535 $text = $content->serialize();
536 if ( $text === '' ) {
537 // This is what happens if the revision was broken at the time the
538 // dump was made. Unfortunately, it also happens if the revision was
539 // legitimately blank, so there's no way to tell the difference. To
540 // be safe, we'll skip it and leave it broken
541
542 echo "Revision $id is blank in the dump, may have been broken before export\n";
543
544 return;
545 }
546
547 if ( !$id ) {
548 // No ID, can't import
549 echo "No id tag in revision, can't import\n";
550
551 return;
552 }
553
554 // Find text row again
555 $dbr = $this->getReplicaDB();
556 $address = $dbr->newSelectQueryBuilder()
557 ->select( 'content_address' )
558 ->from( 'slots' )
559 ->join( 'content', null, 'content_id = slot_content_id' )
560 ->where( [ 'slot_revision_id' => $id ] )
561 ->caller( __METHOD__ )
562 ->fetchField();
563
564 $blobStore = $this->getServiceContainer()
565 ->getBlobStoreFactory()
566 ->newSqlBlobStore();
567 $oldId = $blobStore->getTextIdFromAddress( $address );
568
569 if ( !$oldId ) {
570 echo "Missing revision row for rev_id $id\n";
571 return;
572 }
573
574 // Compress the text
575 $flags = $blobStore->compressData( $text );
576
577 // Update the text row
578 $dbw = $this->getPrimaryDB();
579 $dbw->newUpdateQueryBuilder()
580 ->update( 'text' )
581 ->set( [ 'old_flags' => $flags, 'old_text' => $text ] )
582 ->where( [ 'old_id' => $oldId ] )
583 ->caller( __METHOD__ )
584 ->execute();
585
586 // Remove it from the unfixed list and add it to the fixed list
587 unset( $this->errors['restore text'][$id] );
588 $this->errors['fixed'][$id] = true;
589 }
590
591}
592
593// @codeCoverageIgnoreStart
594$maintClass = CheckStorage::class;
595require_once RUN_MAINTENANCE_IF_MAIN;
596// @codeCoverageIgnoreEnd
wfTempDir()
Tries to get the system directory for temporary files.
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
$maintClass
Maintenance script to do various checks on external storage.
check(bool $fix=false, string|false $xml='')
__construct()
Default constructor.
string[] $errorDescriptions
execute()
Do the actual work.
ExternalStoreDB $dbStore
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
addArg( $arg, $description, $required=true, $multi=false)
Add some args that are needed.
getArg( $argId=0, $default=null)
Get an argument.
addOption( $name, $description, $required=false, $withArg=false, $shortName=false, $multiOccurrence=false)
Add a parameter to the script.
hasOption( $name)
Checks to see if a particular option was set.
getReplicaDB(string|false $virtualDomain=false)
getServiceContainer()
Returns the main service container.
getPrimaryDB(string|false $virtualDomain=false)
Represents an authority that has all permissions.
Executes shell commands.
Definition Shell.php:32
User class for the MediaWiki software.
Definition User.php:130
$wgDBname
Config variable stub for the DBname setting, for use by phpdoc and IDEs.
$source