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