MediaWiki  REL1_23
checkStorage.php
Go to the documentation of this file.
00001 <?php
00024 if ( !defined( 'MEDIAWIKI' ) ) {
00025     require_once __DIR__ . '/../commandLine.inc';
00026 
00027     $cs = new CheckStorage;
00028     $fix = isset( $options['fix'] );
00029     if ( isset( $args[0] ) ) {
00030         $xml = $args[0];
00031     } else {
00032         $xml = false;
00033     }
00034     $cs->check( $fix, $xml );
00035 }
00036 
00037 // ----------------------------------------------------------------------------------
00038 
00044 class CheckStorage {
00045     const CONCAT_HEADER = 'O:27:"concatenatedgziphistoryblob"';
00046     public $oldIdMap, $errors;
00047     public $dbStore = null;
00048 
00049     public $errorDescriptions = array(
00050         'restore text' => 'Damaged text, need to be restored from a backup',
00051         'restore revision' => 'Damaged revision row, need to be restored from a backup',
00052         'unfixable' => 'Unexpected errors with no automated fixing method',
00053         'fixed' => 'Errors already fixed',
00054         'fixable' => 'Errors which would already be fixed if --fix was specified',
00055     );
00056 
00057     function check( $fix = false, $xml = '' ) {
00058         $dbr = wfGetDB( DB_SLAVE );
00059         if ( $fix ) {
00060             print "Checking, will fix errors if possible...\n";
00061         } else {
00062             print "Checking...\n";
00063         }
00064         $maxRevId = $dbr->selectField( 'revision', 'MAX(rev_id)', false, __METHOD__ );
00065         $chunkSize = 1000;
00066         $flagStats = array();
00067         $objectStats = array();
00068         $knownFlags = array( 'external', 'gzip', 'object', 'utf-8' );
00069         $this->errors = array(
00070             'restore text' => array(),
00071             'restore revision' => array(),
00072             'unfixable' => array(),
00073             'fixed' => array(),
00074             'fixable' => array(),
00075         );
00076 
00077         for ( $chunkStart = 1; $chunkStart < $maxRevId; $chunkStart += $chunkSize ) {
00078             $chunkEnd = $chunkStart + $chunkSize - 1;
00079             // print "$chunkStart of $maxRevId\n";
00080 
00081             // Fetch revision rows
00082             $this->oldIdMap = array();
00083             $dbr->ping();
00084             $res = $dbr->select( 'revision', array( 'rev_id', 'rev_text_id' ),
00085                 array( "rev_id BETWEEN $chunkStart AND $chunkEnd" ), __METHOD__ );
00086             foreach ( $res as $row ) {
00087                 $this->oldIdMap[$row->rev_id] = $row->rev_text_id;
00088             }
00089             $dbr->freeResult( $res );
00090 
00091             if ( !count( $this->oldIdMap ) ) {
00092                 continue;
00093             }
00094 
00095             // Fetch old_flags
00096             $missingTextRows = array_flip( $this->oldIdMap );
00097             $externalRevs = array();
00098             $objectRevs = array();
00099             $res = $dbr->select( 'text', array( 'old_id', 'old_flags' ),
00100                 'old_id IN (' . implode( ',', $this->oldIdMap ) . ')', __METHOD__ );
00101             foreach ( $res as $row ) {
00105                 $flags = $row->old_flags;
00106                 $id = $row->old_id;
00107 
00108                 // Create flagStats row if it doesn't exist
00109                 $flagStats = $flagStats + array( $flags => 0 );
00110                 // Increment counter
00111                 $flagStats[$flags]++;
00112 
00113                 // Not missing
00114                 unset( $missingTextRows[$row->old_id] );
00115 
00116                 // Check for external or object
00117                 if ( $flags == '' ) {
00118                     $flagArray = array();
00119                 } else {
00120                     $flagArray = explode( ',', $flags );
00121                 }
00122                 if ( in_array( 'external', $flagArray ) ) {
00123                     $externalRevs[] = $id;
00124                 } elseif ( in_array( 'object', $flagArray ) ) {
00125                     $objectRevs[] = $id;
00126                 }
00127 
00128                 // Check for unrecognised flags
00129                 if ( $flags == '0' ) {
00130                     // This is a known bug from 2004
00131                     // It's safe to just erase the old_flags field
00132                     if ( $fix ) {
00133                         $this->error( 'fixed', "Warning: old_flags set to 0", $id );
00134                         $dbw = wfGetDB( DB_MASTER );
00135                         $dbw->ping();
00136                         $dbw->update( 'text', array( 'old_flags' => '' ),
00137                             array( 'old_id' => $id ), __METHOD__ );
00138                         echo "Fixed\n";
00139                     } else {
00140                         $this->error( 'fixable', "Warning: old_flags set to 0", $id );
00141                     }
00142                 } elseif ( count( array_diff( $flagArray, $knownFlags ) ) ) {
00143                     $this->error( 'unfixable', "Error: invalid flags field \"$flags\"", $id );
00144                 }
00145             }
00146             $dbr->freeResult( $res );
00147 
00148             // Output errors for any missing text rows
00149             foreach ( $missingTextRows as $oldId => $revId ) {
00150                 $this->error( 'restore revision', "Error: missing text row", $oldId );
00151             }
00152 
00153             // Verify external revisions
00154             $externalConcatBlobs = array();
00155             $externalNormalBlobs = array();
00156             if ( count( $externalRevs ) ) {
00157                 $res = $dbr->select( 'text', array( 'old_id', 'old_flags', 'old_text' ),
00158                     array( 'old_id IN (' . implode( ',', $externalRevs ) . ')' ), __METHOD__ );
00159                 foreach ( $res as $row ) {
00160                     $urlParts = explode( '://', $row->old_text, 2 );
00161                     if ( count( $urlParts ) !== 2 || $urlParts[1] == '' ) {
00162                         $this->error( 'restore text', "Error: invalid URL \"{$row->old_text}\"", $row->old_id );
00163                         continue;
00164                     }
00165                     list( $proto, ) = $urlParts;
00166                     if ( $proto != 'DB' ) {
00167                         $this->error( 'restore text', "Error: invalid external protocol \"$proto\"", $row->old_id );
00168                         continue;
00169                     }
00170                     $path = explode( '/', $row->old_text );
00171                     $cluster = $path[2];
00172                     $id = $path[3];
00173                     if ( isset( $path[4] ) ) {
00174                         $externalConcatBlobs[$cluster][$id][] = $row->old_id;
00175                     } else {
00176                         $externalNormalBlobs[$cluster][$id][] = $row->old_id;
00177                     }
00178                 }
00179                 $dbr->freeResult( $res );
00180             }
00181 
00182             // Check external concat blobs for the right header
00183             $this->checkExternalConcatBlobs( $externalConcatBlobs );
00184 
00185             // Check external normal blobs for existence
00186             if ( count( $externalNormalBlobs ) ) {
00187                 if ( is_null( $this->dbStore ) ) {
00188                     $this->dbStore = new ExternalStoreDB;
00189                 }
00190                 foreach ( $externalConcatBlobs as $cluster => $xBlobIds ) {
00191                     $blobIds = array_keys( $xBlobIds );
00192                     $extDb =& $this->dbStore->getSlave( $cluster );
00193                     $blobsTable = $this->dbStore->getTable( $extDb );
00194                     $res = $extDb->select( $blobsTable,
00195                         array( 'blob_id' ),
00196                         array( 'blob_id IN( ' . implode( ',', $blobIds ) . ')' ), __METHOD__ );
00197                     foreach ( $res as $row ) {
00198                         unset( $xBlobIds[$row->blob_id] );
00199                     }
00200                     $extDb->freeResult( $res );
00201                     // Print errors for missing blobs rows
00202                     foreach ( $xBlobIds as $blobId => $oldId ) {
00203                         $this->error( 'restore text', "Error: missing target $blobId for one-part ES URL", $oldId );
00204                     }
00205                 }
00206             }
00207 
00208             // Check local objects
00209             $dbr->ping();
00210             $concatBlobs = array();
00211             $curIds = array();
00212             if ( count( $objectRevs ) ) {
00213                 $headerLength = 300;
00214                 $res = $dbr->select( 'text', array( 'old_id', 'old_flags', "LEFT(old_text, $headerLength) AS header" ),
00215                     array( 'old_id IN (' . implode( ',', $objectRevs ) . ')' ), __METHOD__ );
00216                 foreach ( $res as $row ) {
00217                     $oldId = $row->old_id;
00218                     $matches = array();
00219                     if ( !preg_match( '/^O:(\d+):"(\w+)"/', $row->header, $matches ) ) {
00220                         $this->error( 'restore text', "Error: invalid object header", $oldId );
00221                         continue;
00222                     }
00223 
00224                     $className = strtolower( $matches[2] );
00225                     if ( strlen( $className ) != $matches[1] ) {
00226                         $this->error( 'restore text', "Error: invalid object header, wrong class name length", $oldId );
00227                         continue;
00228                     }
00229 
00230                     $objectStats = $objectStats + array( $className => 0 );
00231                     $objectStats[$className]++;
00232 
00233                     switch ( $className ) {
00234                         case 'concatenatedgziphistoryblob':
00235                             // Good
00236                             break;
00237                         case 'historyblobstub':
00238                         case 'historyblobcurstub':
00239                             if ( strlen( $row->header ) == $headerLength ) {
00240                                 $this->error( 'unfixable', "Error: overlong stub header", $oldId );
00241                                 continue;
00242                             }
00243                             $stubObj = unserialize( $row->header );
00244                             if ( !is_object( $stubObj ) ) {
00245                                 $this->error( 'restore text', "Error: unable to unserialize stub object", $oldId );
00246                                 continue;
00247                             }
00248                             if ( $className == 'historyblobstub' ) {
00249                                 $concatBlobs[$stubObj->mOldId][] = $oldId;
00250                             } else {
00251                                 $curIds[$stubObj->mCurId][] = $oldId;
00252                             }
00253                             break;
00254                         default:
00255                             $this->error( 'unfixable', "Error: unrecognised object class \"$className\"", $oldId );
00256                     }
00257                 }
00258                 $dbr->freeResult( $res );
00259             }
00260 
00261             // Check local concat blob validity
00262             $externalConcatBlobs = array();
00263             if ( count( $concatBlobs ) ) {
00264                 $headerLength = 300;
00265                 $res = $dbr->select( 'text', array( 'old_id', 'old_flags', "LEFT(old_text, $headerLength) AS header" ),
00266                     array( 'old_id IN (' . implode( ',', array_keys( $concatBlobs ) ) . ')' ), __METHOD__ );
00267                 foreach ( $res as $row ) {
00268                     $flags = explode( ',', $row->old_flags );
00269                     if ( in_array( 'external', $flags ) ) {
00270                         // Concat blob is in external storage?
00271                         if ( in_array( 'object', $flags ) ) {
00272                             $urlParts = explode( '/', $row->header );
00273                             if ( $urlParts[0] != 'DB:' ) {
00274                                 $this->error( 'unfixable', "Error: unrecognised external storage type \"{$urlParts[0]}", $row->old_id );
00275                             } else {
00276                                 $cluster = $urlParts[2];
00277                                 $id = $urlParts[3];
00278                                 if ( !isset( $externalConcatBlobs[$cluster][$id] ) ) {
00279                                     $externalConcatBlobs[$cluster][$id] = array();
00280                                 }
00281                                 $externalConcatBlobs[$cluster][$id] = array_merge(
00282                                     $externalConcatBlobs[$cluster][$id], $concatBlobs[$row->old_id]
00283                                 );
00284                             }
00285                         } else {
00286                             $this->error( 'unfixable', "Error: invalid flags \"{$row->old_flags}\" on concat bulk row {$row->old_id}",
00287                                 $concatBlobs[$row->old_id] );
00288                         }
00289                     } elseif ( strcasecmp( substr( $row->header, 0, strlen( self::CONCAT_HEADER ) ), self::CONCAT_HEADER ) ) {
00290                         $this->error( 'restore text', "Error: Incorrect object header for concat bulk row {$row->old_id}",
00291                             $concatBlobs[$row->old_id] );
00292                     } # else good
00293 
00294                     unset( $concatBlobs[$row->old_id] );
00295                 }
00296                 $dbr->freeResult( $res );
00297             }
00298 
00299             // Check targets of unresolved stubs
00300             $this->checkExternalConcatBlobs( $externalConcatBlobs );
00301 
00302             // next chunk
00303         }
00304 
00305         print "\n\nErrors:\n";
00306         foreach ( $this->errors as $name => $errors ) {
00307             if ( count( $errors ) ) {
00308                 $description = $this->errorDescriptions[$name];
00309                 echo "$description: " . implode( ',', array_keys( $errors ) ) . "\n";
00310             }
00311         }
00312 
00313         if ( count( $this->errors['restore text'] ) && $fix ) {
00314             if ( (string)$xml !== '' ) {
00315                 $this->restoreText( array_keys( $this->errors['restore text'] ), $xml );
00316             } else {
00317                 echo "Can't fix text, no XML backup specified\n";
00318             }
00319         }
00320 
00321         print "\nFlag statistics:\n";
00322         $total = array_sum( $flagStats );
00323         foreach ( $flagStats as $flag => $count ) {
00324             printf( "%-30s %10d %5.2f%%\n", $flag, $count, $count / $total * 100 );
00325         }
00326         print "\nLocal object statistics:\n";
00327         $total = array_sum( $objectStats );
00328         foreach ( $objectStats as $className => $count ) {
00329             printf( "%-30s %10d %5.2f%%\n", $className, $count, $count / $total * 100 );
00330         }
00331     }
00332 
00333     function error( $type, $msg, $ids ) {
00334         if ( is_array( $ids ) && count( $ids ) == 1 ) {
00335             $ids = reset( $ids );
00336         }
00337         if ( is_array( $ids ) ) {
00338             $revIds = array();
00339             foreach ( $ids as $id ) {
00340                 $revIds = array_merge( $revIds, array_keys( $this->oldIdMap, $id ) );
00341             }
00342             print "$msg in text rows " . implode( ', ', $ids ) .
00343                 ", revisions " . implode( ', ', $revIds ) . "\n";
00344         } else {
00345             $id = $ids;
00346             $revIds = array_keys( $this->oldIdMap, $id );
00347             if ( count( $revIds ) == 1 ) {
00348                 print "$msg in old_id $id, rev_id {$revIds[0]}\n";
00349             } else {
00350                 print "$msg in old_id $id, revisions " . implode( ', ', $revIds ) . "\n";
00351             }
00352         }
00353         $this->errors[$type] = $this->errors[$type] + array_flip( $revIds );
00354     }
00355 
00356     function checkExternalConcatBlobs( $externalConcatBlobs ) {
00357         if ( !count( $externalConcatBlobs ) ) {
00358             return;
00359         }
00360 
00361         if ( is_null( $this->dbStore ) ) {
00362             $this->dbStore = new ExternalStoreDB;
00363         }
00364 
00365         foreach ( $externalConcatBlobs as $cluster => $oldIds ) {
00366             $blobIds = array_keys( $oldIds );
00367             $extDb =& $this->dbStore->getSlave( $cluster );
00368             $blobsTable = $this->dbStore->getTable( $extDb );
00369             $headerLength = strlen( self::CONCAT_HEADER );
00370             $res = $extDb->select( $blobsTable,
00371                 array( 'blob_id', "LEFT(blob_text, $headerLength) AS header" ),
00372                 array( 'blob_id IN( ' . implode( ',', $blobIds ) . ')' ), __METHOD__ );
00373             foreach ( $res as $row ) {
00374                 if ( strcasecmp( $row->header, self::CONCAT_HEADER ) ) {
00375                     $this->error( 'restore text', "Error: invalid header on target $cluster/{$row->blob_id} of two-part ES URL",
00376                         $oldIds[$row->blob_id] );
00377                 }
00378                 unset( $oldIds[$row->blob_id] );
00379 
00380             }
00381             $extDb->freeResult( $res );
00382 
00383             // Print errors for missing blobs rows
00384             foreach ( $oldIds as $blobId => $oldIds2 ) {
00385                 $this->error( 'restore text', "Error: missing target $cluster/$blobId for two-part ES URL", $oldIds2 );
00386             }
00387         }
00388     }
00389 
00390     function restoreText( $revIds, $xml ) {
00391         global $wgDBname;
00392         $tmpDir = wfTempDir();
00393 
00394         if ( !count( $revIds ) ) {
00395             return;
00396         }
00397 
00398         print "Restoring text from XML backup...\n";
00399 
00400         $revFileName = "$tmpDir/broken-revlist-$wgDBname";
00401         $filteredXmlFileName = "$tmpDir/filtered-$wgDBname.xml";
00402 
00403         // Write revision list
00404         if ( !file_put_contents( $revFileName, implode( "\n", $revIds ) ) ) {
00405             echo "Error writing revision list, can't restore text\n";
00406             return;
00407         }
00408 
00409         // Run mwdumper
00410         echo "Filtering XML dump...\n";
00411         $exitStatus = 0;
00412         passthru( 'mwdumper ' .
00413             wfEscapeShellArg(
00414                 "--output=file:$filteredXmlFileName",
00415                 "--filter=revlist:$revFileName",
00416                 $xml
00417             ), $exitStatus
00418         );
00419 
00420         if ( $exitStatus ) {
00421             echo "mwdumper died with exit status $exitStatus\n";
00422             return;
00423         }
00424 
00425         $file = fopen( $filteredXmlFileName, 'r' );
00426         if ( !$file ) {
00427             echo "Unable to open filtered XML file\n";
00428             return;
00429         }
00430 
00431         $dbr = wfGetDB( DB_SLAVE );
00432         $dbw = wfGetDB( DB_MASTER );
00433         $dbr->ping();
00434         $dbw->ping();
00435 
00436         $source = new ImportStreamSource( $file );
00437         $importer = new WikiImporter( $source );
00438         $importer->setRevisionCallback( array( &$this, 'importRevision' ) );
00439         $importer->doImport();
00440     }
00441 
00442     function importRevision( &$revision, &$importer ) {
00443         $id = $revision->getID();
00444         $content = $revision->getContent( Revision::RAW );
00445         $id = $id ? $id : '';
00446 
00447         if ( $content === null ) {
00448             echo "Revision $id is broken, we have no content available\n";
00449             return;
00450         }
00451 
00452         $text = $content->serialize();
00453         if ( $text === '' ) {
00454             // This is what happens if the revision was broken at the time the
00455             // dump was made. Unfortunately, it also happens if the revision was
00456             // legitimately blank, so there's no way to tell the difference. To
00457             // be safe, we'll skip it and leave it broken
00458 
00459             echo "Revision $id is blank in the dump, may have been broken before export\n";
00460             return;
00461         }
00462 
00463         if ( !$id ) {
00464             // No ID, can't import
00465             echo "No id tag in revision, can't import\n";
00466             return;
00467         }
00468 
00469         // Find text row again
00470         $dbr = wfGetDB( DB_SLAVE );
00471         $oldId = $dbr->selectField( 'revision', 'rev_text_id', array( 'rev_id' => $id ), __METHOD__ );
00472         if ( !$oldId ) {
00473             echo "Missing revision row for rev_id $id\n";
00474             return;
00475         }
00476 
00477         // Compress the text
00478         $flags = Revision::compressRevisionText( $text );
00479 
00480         // Update the text row
00481         $dbw = wfGetDB( DB_MASTER );
00482         $dbw->update( 'text',
00483             array( 'old_flags' => $flags, 'old_text' => $text ),
00484             array( 'old_id' => $oldId ),
00485             __METHOD__, array( 'LIMIT' => 1 )
00486         );
00487 
00488         // Remove it from the unfixed list and add it to the fixed list
00489         unset( $this->errors['restore text'][$id] );
00490         $this->errors['fixed'][$id] = true;
00491     }
00492 }