MediaWiki master
checkStorage.php
Go to the documentation of this file.
1<?php
26
27require_once __DIR__ . '/../Maintenance.php';
28
29// ----------------------------------------------------------------------------------
30
38 private const CONCAT_HEADER = 'O:27:"concatenatedgziphistoryblob"';
39
41
43 public $dbStore = null;
44
45 public function __construct() {
46 parent::__construct();
47
48 $this->addOption( 'fix', 'Fix errors if possible' );
49 $this->addArg( 'xml', 'Path to an XML dump', false );
50 }
51
52 public function execute() {
53 $fix = $this->hasOption( 'fix' );
54 $xml = $this->getArg( 'xml', false );
55 $this->check( $fix, $xml );
56 }
57
59 'restore text' => 'Damaged text, need to be restored from a backup',
60 'restore revision' => 'Damaged revision row, need to be restored from a backup',
61 'unfixable' => 'Unexpected errors with no automated fixing method',
62 'fixed' => 'Errors already fixed',
63 'fixable' => 'Errors which would already be fixed if --fix was specified',
64 ];
65
66 public function check( $fix = false, $xml = '' ) {
67 $dbr = $this->getReplicaDB();
68 if ( $fix ) {
69 print "Checking, will fix errors if possible...\n";
70 } else {
71 print "Checking...\n";
72 }
73 $maxRevId = $dbr->newSelectQueryBuilder()
74 ->select( 'MAX(rev_id)' )
75 ->from( 'revision' )
76 ->caller( __METHOD__ )->fetchField();
77 $chunkSize = 1000;
78 $flagStats = [];
79 $objectStats = [];
80 $knownFlags = [ 'external', 'gzip', 'object', 'utf-8' ];
81 $this->errors = [
82 'restore text' => [],
83 'restore revision' => [],
84 'unfixable' => [],
85 'fixed' => [],
86 'fixable' => [],
87 ];
88
89 for ( $chunkStart = 1; $chunkStart < $maxRevId; $chunkStart += $chunkSize ) {
90 $chunkEnd = $chunkStart + $chunkSize - 1;
91 // print "$chunkStart of $maxRevId\n";
92
93 $this->oldIdMap = [];
94 $dbr->ping();
95
96 // Fetch revision rows
97 $res = $dbr->newSelectQueryBuilder()
98 ->select( [ 'slot_revision_id', 'content_address' ] )
99 ->from( 'slots' )
100 ->join( 'content', null, 'content_id = slot_content_id' )
101 ->where( [ "slot_revision_id BETWEEN $chunkStart AND $chunkEnd" ] )
102 ->caller( __METHOD__ )->fetchResultSet();
104 $blobStore = $this->getServiceContainer()->getBlobStore();
105 '@phan-var \MediaWiki\Storage\SqlBlobStore $blobStore';
106 foreach ( $res as $row ) {
107 $textId = $blobStore->getTextIdFromAddress( $row->content_address );
108 if ( $textId ) {
109 if ( !isset( $this->oldIdMap[$textId] ) ) {
110 $this->oldIdMap[ $textId ] = [ $row->slot_revision_id ];
111 } elseif ( !in_array( $row->slot_revision_id, $this->oldIdMap[$textId] ) ) {
112 $this->oldIdMap[ $textId ][] = $row->slot_revision_id;
113 }
114 }
115 }
116
117 if ( !count( $this->oldIdMap ) ) {
118 continue;
119 }
120
121 // Fetch old_flags
122 $missingTextRows = $this->oldIdMap;
123 $externalRevs = [];
124 $objectRevs = [];
125 $res = $dbr->newSelectQueryBuilder()
126 ->select( [ 'old_id', 'old_flags' ] )
127 ->from( 'text' )
128 ->where( [ 'old_id' => array_keys( $this->oldIdMap ) ] )
129 ->caller( __METHOD__ )->fetchResultSet();
130 foreach ( $res as $row ) {
134 $flags = $row->old_flags;
135 $id = $row->old_id;
136
137 // Create flagStats row if it doesn't exist
138 $flagStats += [ $flags => 0 ];
139 // Increment counter
140 $flagStats[$flags]++;
141
142 // Not missing
143 unset( $missingTextRows[$row->old_id] );
144
145 // Check for external or object
146 if ( $flags == '' ) {
147 $flagArray = [];
148 } else {
149 $flagArray = explode( ',', $flags );
150 }
151 if ( in_array( 'external', $flagArray ) ) {
152 $externalRevs[] = $id;
153 } elseif ( in_array( 'object', $flagArray ) ) {
154 $objectRevs[] = $id;
155 }
156
157 // Check for unrecognised flags
158 if ( $flags == '0' ) {
159 // This is a known bug from 2004
160 // It's safe to just erase the old_flags field
161 if ( $fix ) {
162 $this->addError( 'fixed', "Warning: old_flags set to 0", $id );
163 $dbw = $this->getPrimaryDB();
164 $dbw->ping();
165 $dbw->newUpdateQueryBuilder()
166 ->update( 'text' )
167 ->set( [ 'old_flags' => '' ] )
168 ->where( [ 'old_id' => $id ] )
169 ->caller( __METHOD__ )
170 ->execute();
171 echo "Fixed\n";
172 } else {
173 $this->addError( 'fixable', "Warning: old_flags set to 0", $id );
174 }
175 } elseif ( count( array_diff( $flagArray, $knownFlags ) ) ) {
176 $this->addError( 'unfixable', "Error: invalid flags field \"$flags\"", $id );
177 }
178 }
179
180 // Output errors for any missing text rows
181 foreach ( $missingTextRows as $oldId => $revIds ) {
182 $this->addError( 'restore revision', "Error: missing text row", $oldId );
183 }
184
185 // Verify external revisions
186 $externalConcatBlobs = [];
187 $externalNormalBlobs = [];
188 if ( count( $externalRevs ) ) {
189 $res = $dbr->newSelectQueryBuilder()
190 ->select( [ 'old_id', 'old_flags', 'old_text' ] )
191 ->from( 'text' )
192 ->where( [ 'old_id' => $externalRevs ] )
193 ->caller( __METHOD__ )->fetchResultSet();
194 foreach ( $res as $row ) {
195 $urlParts = explode( '://', $row->old_text, 2 );
196 if ( count( $urlParts ) !== 2 || $urlParts[1] == '' ) {
197 $this->addError( 'restore text', "Error: invalid URL \"{$row->old_text}\"", $row->old_id );
198 continue;
199 }
200 [ $proto, ] = $urlParts;
201 if ( $proto != 'DB' ) {
202 $this->addError(
203 'restore text',
204 "Error: invalid external protocol \"$proto\"",
205 $row->old_id );
206 continue;
207 }
208 $path = explode( '/', $row->old_text );
209 $cluster = $path[2];
210 $id = $path[3];
211 if ( isset( $path[4] ) ) {
212 $externalConcatBlobs[$cluster][$id][] = $row->old_id;
213 } else {
214 $externalNormalBlobs[$cluster][$id][] = $row->old_id;
215 }
216 }
217 }
218
219 // Check external concat blobs for the right header
220 $this->checkExternalConcatBlobs( $externalConcatBlobs );
221
222 // Check external normal blobs for existence
223 if ( count( $externalNormalBlobs ) ) {
224 if ( $this->dbStore === null ) {
225 $esFactory = $this->getServiceContainer()->getExternalStoreFactory();
226 $this->dbStore = $esFactory->getStore( 'DB' );
227 }
228 foreach ( $externalConcatBlobs as $cluster => $xBlobIds ) {
229 $blobIds = array_keys( $xBlobIds );
230 $extDb = $this->dbStore->getReplica( $cluster );
231 $blobsTable = $this->dbStore->getTable( $extDb );
232 $res = $extDb->newSelectQueryBuilder()
233 ->select( [ 'blob_id' ] )
234 ->from( $blobsTable )
235 ->where( [ 'blob_id' => $blobIds ] )
236 ->caller( __METHOD__ )->fetchResultSet();
237 foreach ( $res as $row ) {
238 unset( $xBlobIds[$row->blob_id] );
239 }
240 // Print errors for missing blobs rows
241 foreach ( $xBlobIds as $blobId => $oldId ) {
242 $this->addError(
243 'restore text',
244 "Error: missing target $blobId for one-part ES URL",
245 $oldId );
246 }
247 }
248 }
249
250 // Check local objects
251 $dbr->ping();
252 $concatBlobs = [];
253 $curIds = [];
254 if ( count( $objectRevs ) ) {
255 $headerLength = 300;
256 $res = $dbr->newSelectQueryBuilder()
257 ->select( [ 'old_id', 'old_flags', "LEFT(old_text, $headerLength) AS header" ] )
258 ->from( 'text' )
259 ->where( [ 'old_id' => $objectRevs ] )
260 ->caller( __METHOD__ )->fetchResultSet();
261 foreach ( $res as $row ) {
262 $oldId = $row->old_id;
263 $matches = [];
264 if ( !preg_match( '/^O:(\d+):"(\w+)"/', $row->header, $matches ) ) {
265 $this->addError( 'restore text', "Error: invalid object header", $oldId );
266 continue;
267 }
268
269 $className = strtolower( $matches[2] );
270 if ( strlen( $className ) != $matches[1] ) {
271 $this->addError(
272 'restore text',
273 "Error: invalid object header, wrong class name length",
274 $oldId
275 );
276 continue;
277 }
278
279 $objectStats += [ $className => 0 ];
280 $objectStats[$className]++;
281
282 switch ( $className ) {
283 case 'concatenatedgziphistoryblob':
284 // Good
285 break;
286 case 'historyblobstub':
287 case 'historyblobcurstub':
288 if ( strlen( $row->header ) == $headerLength ) {
289 $this->addError( 'unfixable', "Error: overlong stub header", $oldId );
290 break;
291 }
292 $stubObj = unserialize( $row->header );
293 if ( !is_object( $stubObj ) ) {
294 $this->addError( 'restore text', "Error: unable to unserialize stub object", $oldId );
295 break;
296 }
297 if ( $className == 'historyblobstub' ) {
298 $concatBlobs[$stubObj->getLocation()][] = $oldId;
299 } else {
300 $curIds[$stubObj->mCurId][] = $oldId;
301 }
302 break;
303 default:
304 $this->addError( 'unfixable', "Error: unrecognised object class \"$className\"", $oldId );
305 }
306 }
307 }
308
309 // Check local concat blob validity
310 $externalConcatBlobs = [];
311 if ( count( $concatBlobs ) ) {
312 $headerLength = 300;
313 $res = $dbr->newSelectQueryBuilder()
314 ->select( [ 'old_id', 'old_flags', "LEFT(old_text, $headerLength) AS header" ] )
315 ->from( 'text' )
316 ->where( [ 'old_id' => array_keys( $concatBlobs ) ] )
317 ->caller( __METHOD__ )->fetchResultSet();
318 foreach ( $res as $row ) {
319 $flags = explode( ',', $row->old_flags );
320 if ( in_array( 'external', $flags ) ) {
321 // Concat blob is in external storage?
322 if ( in_array( 'object', $flags ) ) {
323 $urlParts = explode( '/', $row->header );
324 if ( $urlParts[0] != 'DB:' ) {
325 $this->addError(
326 'unfixable',
327 "Error: unrecognised external storage type \"{$urlParts[0]}",
328 $row->old_id
329 );
330 } else {
331 $cluster = $urlParts[2];
332 $id = $urlParts[3];
333 if ( !isset( $externalConcatBlobs[$cluster][$id] ) ) {
334 $externalConcatBlobs[$cluster][$id] = [];
335 }
336 $externalConcatBlobs[$cluster][$id] = array_merge(
337 $externalConcatBlobs[$cluster][$id], $concatBlobs[$row->old_id]
338 );
339 }
340 } else {
341 $this->addError(
342 'unfixable',
343 "Error: invalid flags \"{$row->old_flags}\" on concat bulk row {$row->old_id}",
344 $concatBlobs[$row->old_id] );
345 }
346 } elseif ( strcasecmp(
347 substr( $row->header, 0, strlen( self::CONCAT_HEADER ) ),
348 self::CONCAT_HEADER
349 ) ) {
350 $this->addError(
351 'restore text',
352 "Error: Incorrect object header for concat bulk row {$row->old_id}",
353 $concatBlobs[$row->old_id]
354 );
355 }
356
357 unset( $concatBlobs[$row->old_id] );
358 }
359 }
360
361 // Check targets of unresolved stubs
362 $this->checkExternalConcatBlobs( $externalConcatBlobs );
363 // next chunk
364 }
365
366 print "\n\nErrors:\n";
367 foreach ( $this->errors as $name => $errors ) {
368 if ( count( $errors ) ) {
369 $description = $this->errorDescriptions[$name];
370 echo "$description: " . implode( ',', array_keys( $errors ) ) . "\n";
371 }
372 }
373
374 if ( count( $this->errors['restore text'] ) && $fix ) {
375 if ( (string)$xml !== '' ) {
376 $this->restoreText( array_keys( $this->errors['restore text'] ), $xml );
377 } else {
378 echo "Can't fix text, no XML backup specified\n";
379 }
380 }
381
382 print "\nFlag statistics:\n";
383 $total = array_sum( $flagStats );
384 foreach ( $flagStats as $flag => $count ) {
385 printf( "%-30s %10d %5.2f%%\n", $flag, $count, $count / $total * 100 );
386 }
387 print "\nLocal object statistics:\n";
388 $total = array_sum( $objectStats );
389 foreach ( $objectStats as $className => $count ) {
390 printf( "%-30s %10d %5.2f%%\n", $className, $count, $count / $total * 100 );
391 }
392 }
393
394 private function addError( $type, $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( $externalConcatBlobs ) {
418 if ( !count( $externalConcatBlobs ) ) {
419 return;
420 }
421
422 if ( $this->dbStore === null ) {
423 $esFactory = $this->getServiceContainer()->getExternalStoreFactory();
424 $this->dbStore = $esFactory->getStore( 'DB' );
425 }
426
427 foreach ( $externalConcatBlobs as $cluster => $oldIds ) {
428 $blobIds = array_keys( $oldIds );
429 $extDb = $this->dbStore->getReplica( $cluster );
430 $blobsTable = $this->dbStore->getTable( $extDb );
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( $revIds, $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 public 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 $res = $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__ )->fetchRow();
562
563 $blobStore = $this->getServiceContainer()
564 ->getBlobStoreFactory()
565 ->newSqlBlobStore();
566 $oldId = $blobStore->getTextIdFromAddress( $res->content_address );
567
568 if ( !$oldId ) {
569 echo "Missing revision row for rev_id $id\n";
570 return;
571 }
572
573 // Compress the text
574 $flags = $blobStore->compressData( $text );
575
576 // Update the text row
577 $dbw = $this->getPrimaryDB();
578 $dbw->newUpdateQueryBuilder()
579 ->update( 'text' )
580 ->set( [ 'old_flags' => $flags, 'old_text' => $text ] )
581 ->where( [ 'old_id' => $oldId ] )
582 ->caller( __METHOD__ )
583 ->execute();
584
585 // Remove it from the unfixed list and add it to the fixed list
586 unset( $this->errors['restore text'][$id] );
587 $this->errors['fixed'][$id] = true;
588 }
589
590}
591
592$maintClass = CheckStorage::class;
593require_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
$wgDBname
Config variable stub for the DBname setting, for use by phpdoc and IDEs.
$source