26 require_once __DIR__ .
'/../Maintenance.php';
37 private const CONCAT_HEADER =
'O:27:"concatenatedgziphistoryblob"';
45 parent::__construct();
47 $this->
addOption(
'fix',
'Fix errors if possible' );
48 $this->
addArg(
'xml',
'Path to an XML dump',
false );
53 $xml = $this->
getArg(
'xml',
false );
54 $this->
check( $fix, $xml );
58 'restore text' =>
'Damaged text, need to be restored from a backup',
59 'restore revision' =>
'Damaged revision row, need to be restored from a backup',
60 'unfixable' =>
'Unexpected errors with no automated fixing method',
61 'fixed' =>
'Errors already fixed',
62 'fixable' =>
'Errors which would already be fixed if --fix was specified',
65 public function check( $fix =
false, $xml =
'' ) {
68 print
"Checking, will fix errors if possible...\n";
70 print
"Checking...\n";
72 $maxRevId = $dbr->newSelectQueryBuilder()
73 ->select(
'MAX(rev_id)' )
75 ->caller( __METHOD__ )->fetchField();
79 $knownFlags = [
'external',
'gzip',
'object',
'utf-8' ];
82 'restore revision' => [],
88 for ( $chunkStart = 1; $chunkStart < $maxRevId; $chunkStart += $chunkSize ) {
89 $chunkEnd = $chunkStart + $chunkSize - 1;
96 $res = $dbr->newSelectQueryBuilder()
97 ->select( [
'slot_revision_id',
'content_address' ] )
99 ->join(
'content',
null,
'content_id = slot_content_id' )
100 ->where( [
"slot_revision_id BETWEEN $chunkStart AND $chunkEnd" ] )
101 ->caller( __METHOD__ )->fetchResultSet();
104 '@phan-var \MediaWiki\Storage\SqlBlobStore $blobStore';
105 foreach ( $res as $row ) {
106 $textId = $blobStore->getTextIdFromAddress( $row->content_address );
108 if ( !isset( $this->oldIdMap[$textId] ) ) {
109 $this->oldIdMap[ $textId ] = [ $row->slot_revision_id ];
110 } elseif ( !in_array( $row->slot_revision_id, $this->oldIdMap[$textId] ) ) {
111 $this->oldIdMap[ $textId ][] = $row->slot_revision_id;
116 if ( !count( $this->oldIdMap ) ) {
124 $res = $dbr->newSelectQueryBuilder()
125 ->select( [
'old_id',
'old_flags' ] )
127 ->where( [
'old_id' => array_keys( $this->oldIdMap ) ] )
128 ->caller( __METHOD__ )->fetchResultSet();
129 foreach ( $res as $row ) {
133 $flags = $row->old_flags;
137 $flagStats += [ $flags => 0 ];
139 $flagStats[$flags]++;
142 unset( $missingTextRows[$row->old_id] );
145 if ( $flags ==
'' ) {
148 $flagArray = explode(
',', $flags );
150 if ( in_array(
'external', $flagArray ) ) {
151 $externalRevs[] = $id;
152 } elseif ( in_array(
'object', $flagArray ) ) {
157 if ( $flags ==
'0' ) {
161 $this->addError(
'fixed',
"Warning: old_flags set to 0", $id );
164 $dbw->update(
'text', [
'old_flags' =>
'' ],
165 [
'old_id' => $id ], __METHOD__ );
168 $this->addError(
'fixable',
"Warning: old_flags set to 0", $id );
170 } elseif ( count( array_diff( $flagArray, $knownFlags ) ) ) {
171 $this->addError(
'unfixable',
"Error: invalid flags field \"$flags\"", $id );
176 foreach ( $missingTextRows as $oldId => $revIds ) {
177 $this->addError(
'restore revision',
"Error: missing text row", $oldId );
181 $externalConcatBlobs = [];
182 $externalNormalBlobs = [];
183 if ( count( $externalRevs ) ) {
184 $res = $dbr->newSelectQueryBuilder()
185 ->select( [
'old_id',
'old_flags',
'old_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 );
195 [ $proto, ] = $urlParts;
196 if ( $proto !=
'DB' ) {
199 "Error: invalid external protocol \"$proto\"",
203 $path = explode(
'/', $row->old_text );
206 if ( isset(
$path[4] ) ) {
207 $externalConcatBlobs[$cluster][$id][] = $row->old_id;
209 $externalNormalBlobs[$cluster][$id][] = $row->old_id;
215 $this->checkExternalConcatBlobs( $externalConcatBlobs );
218 if ( count( $externalNormalBlobs ) ) {
219 if ( $this->dbStore ===
null ) {
221 $this->dbStore = $esFactory->getStore(
'DB' );
223 foreach ( $externalConcatBlobs as $cluster => $xBlobIds ) {
224 $blobIds = array_keys( $xBlobIds );
225 $extDb = $this->dbStore->getReplica( $cluster );
226 $blobsTable = $this->dbStore->getTable( $extDb );
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] );
236 foreach ( $xBlobIds as $blobId => $oldId ) {
239 "Error: missing target $blobId for one-part ES URL",
249 if ( count( $objectRevs ) ) {
251 $res = $dbr->newSelectQueryBuilder()
252 ->select( [
'old_id',
'old_flags',
"LEFT(old_text, $headerLength) AS header" ] )
254 ->where( [
'old_id' => $objectRevs ] )
255 ->caller( __METHOD__ )->fetchResultSet();
256 foreach ( $res as $row ) {
257 $oldId = $row->old_id;
259 if ( !preg_match(
'/^O:(\d+):"(\w+)"/', $row->header,
$matches ) ) {
260 $this->addError(
'restore text',
"Error: invalid object header", $oldId );
264 $className = strtolower(
$matches[2] );
265 if ( strlen( $className ) !=
$matches[1] ) {
268 "Error: invalid object header, wrong class name length",
274 $objectStats += [ $className => 0 ];
275 $objectStats[$className]++;
277 switch ( $className ) {
278 case 'concatenatedgziphistoryblob':
281 case 'historyblobstub':
282 case 'historyblobcurstub':
283 if ( strlen( $row->header ) == $headerLength ) {
284 $this->addError(
'unfixable',
"Error: overlong stub header", $oldId );
287 $stubObj = unserialize( $row->header );
288 if ( !is_object( $stubObj ) ) {
289 $this->addError(
'restore text',
"Error: unable to unserialize stub object", $oldId );
292 if ( $className ==
'historyblobstub' ) {
293 $concatBlobs[$stubObj->getLocation()][] = $oldId;
295 $curIds[$stubObj->mCurId][] = $oldId;
299 $this->addError(
'unfixable',
"Error: unrecognised object class \"$className\"", $oldId );
305 $externalConcatBlobs = [];
306 if ( count( $concatBlobs ) ) {
308 $res = $dbr->newSelectQueryBuilder()
309 ->select( [
'old_id',
'old_flags',
"LEFT(old_text, $headerLength) AS header" ] )
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 ) ) {
317 if ( in_array(
'object', $flags ) ) {
318 $urlParts = explode(
'/', $row->header );
319 if ( $urlParts[0] !=
'DB:' ) {
322 "Error: unrecognised external storage type \"{$urlParts[0]}",
326 $cluster = $urlParts[2];
328 if ( !isset( $externalConcatBlobs[$cluster][$id] ) ) {
329 $externalConcatBlobs[$cluster][$id] = [];
331 $externalConcatBlobs[$cluster][$id] = array_merge(
332 $externalConcatBlobs[$cluster][$id], $concatBlobs[$row->old_id]
338 "Error: invalid flags \"{$row->old_flags}\" on concat bulk row {$row->old_id}",
339 $concatBlobs[$row->old_id] );
341 } elseif ( strcasecmp(
342 substr( $row->header, 0, strlen( self::CONCAT_HEADER ) ),
347 "Error: Incorrect object header for concat bulk row {$row->old_id}",
348 $concatBlobs[$row->old_id]
352 unset( $concatBlobs[$row->old_id] );
357 $this->checkExternalConcatBlobs( $externalConcatBlobs );
361 print
"\n\nErrors:\n";
362 foreach ( $this->errors as $name =>
$errors ) {
364 $description = $this->errorDescriptions[$name];
365 echo
"$description: " . implode(
',', array_keys(
$errors ) ) .
"\n";
369 if ( count( $this->errors[
'restore text'] ) && $fix ) {
370 if ( (
string)$xml !==
'' ) {
371 $this->restoreText( array_keys( $this->errors[
'restore text'] ), $xml );
373 echo
"Can't fix text, no XML backup specified\n";
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 );
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 );
389 private function addError( $type, $msg, $ids ) {
390 if ( is_array( $ids ) && count( $ids ) == 1 ) {
391 $ids = reset( $ids );
393 if ( is_array( $ids ) ) {
395 foreach ( $ids as $id ) {
396 $revIds = array_unique( array_merge( $revIds, $this->oldIdMap[$id] ) );
398 print
"$msg in text rows " . implode(
', ', $ids ) .
399 ", revisions " . implode(
', ', $revIds ) .
"\n";
402 $revIds = $this->oldIdMap[$id];
403 if ( count( $revIds ) == 1 ) {
404 print
"$msg in old_id $id, rev_id {$revIds[0]}\n";
406 print
"$msg in old_id $id, revisions " . implode(
', ', $revIds ) .
"\n";
409 $this->errors[$type] += array_fill_keys( $revIds,
true );
412 private function checkExternalConcatBlobs( $externalConcatBlobs ) {
413 if ( !count( $externalConcatBlobs ) ) {
417 if ( $this->dbStore ===
null ) {
419 $this->dbStore = $esFactory->getStore(
'DB' );
422 foreach ( $externalConcatBlobs as $cluster => $oldIds ) {
423 $blobIds = array_keys( $oldIds );
424 $extDb = $this->dbStore->getReplica( $cluster );
425 $blobsTable = $this->dbStore->getTable( $extDb );
426 $headerLength = strlen( self::CONCAT_HEADER );
427 $res = $extDb->newSelectQueryBuilder()
428 ->select( [
'blob_id',
"LEFT(blob_text, $headerLength) AS header" ] )
429 ->from( $blobsTable )
430 ->where( [
'blob_id' => $blobIds ] )
431 ->caller( __METHOD__ )->fetchResultSet();
432 foreach ( $res as $row ) {
433 if ( strcasecmp( $row->header, self::CONCAT_HEADER ) ) {
436 "Error: invalid header on target $cluster/{$row->blob_id} of two-part ES URL",
437 $oldIds[$row->blob_id]
440 unset( $oldIds[$row->blob_id] );
444 foreach ( $oldIds as $blobId => $oldIds2 ) {
447 "Error: missing target $cluster/$blobId for two-part ES URL",
454 private function restoreText( $revIds, $xml ) {
458 if ( !count( $revIds ) ) {
462 print
"Restoring text from XML backup...\n";
464 $revFileName =
"$tmpDir/broken-revlist-$wgDBname";
465 $filteredXmlFileName =
"$tmpDir/filtered-$wgDBname.xml";
468 if ( !file_put_contents( $revFileName, implode(
"\n", $revIds ) ) ) {
469 echo
"Error writing revision list, can't restore text\n";
475 echo
"Filtering XML dump...\n";
478 passthru(
'mwdumper ' .
480 "--output=file:$filteredXmlFileName",
481 "--filter=revlist:$revFileName",
487 echo
"mwdumper died with exit status $exitStatus\n";
492 $file = fopen( $filteredXmlFileName,
'r' );
494 echo
"Unable to open filtered XML file\n";
506 ->getWikiImporterFactory()
508 $importer->setRevisionCallback( [ $this,
'importRevision' ] );
509 $importer->setNoticeCallback(
static function ( $msg, $params ) {
510 echo
wfMessage( $msg, $params )->text() .
"\n";
512 $importer->doImport();
519 $id = $revision->getID();
524 echo
"Revision $id is broken, we have no content available\n";
530 if ( $text ===
'' ) {
536 echo
"Revision $id is blank in the dump, may have been broken before export\n";
543 echo
"No id tag in revision, can't import\n";
550 $res = $dbr->newSelectQueryBuilder()
551 ->select( [
'content_address' ] )
553 ->join(
'content',
null,
'content_id = slot_content_id' )
554 ->where( [
'slot_revision_id' => $id ] )
555 ->caller( __METHOD__ )->fetchRow();
558 ->getBlobStoreFactory()
560 $oldId = $blobStore->getTextIdFromAddress( $res->content_address );
563 echo
"Missing revision row for rev_id $id\n";
568 $flags = $blobStore->compressData( $text );
572 $dbw->update(
'text',
573 [
'old_flags' => $flags,
'old_text' => $text ],
574 [
'old_id' => $oldId ],
575 __METHOD__, [
'LIMIT' => 1 ]
579 unset( $this->errors[
'restore text'][$id] );
580 $this->errors[
'fixed'][$id] =
true;
586 require_once RUN_MAINTENANCE_IF_MAIN;
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='')
__construct()
Default constructor.
execute()
Do the actual work.
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.
$wgDBname
Config variable stub for the DBname setting, for use by phpdoc and IDEs.
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Item class for a filearchive table row.