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