Fixing a variable name, and a PHP warning.
[mediawiki.git] / maintenance / storage / checkStorage.php
blobd50ef366d26b9d289838921b6b58a764459a5228
1 <?php
3 /**
4 * Fsck for MediaWiki
5 */
7 define( 'CONCAT_HEADER', 'O:27:"concatenatedgziphistoryblob"' );
9 if ( !defined( 'MEDIAWIKI' ) ) {
10 require_once( dirname(__FILE__) . '/../commandLine.inc' );
12 $cs = new CheckStorage;
13 $fix = isset( $options['fix'] );
14 if ( isset( $args[0] ) ) {
15 $xml = $args[0];
16 } else {
17 $xml = false;
19 $cs->check( $fix, $xml );
23 //----------------------------------------------------------------------------------
25 class CheckStorage
27 var $oldIdMap, $errors;
28 var $dbStore = null;
30 var $errorDescriptions = array(
31 'restore text' => 'Damaged text, need to be restored from a backup',
32 'restore revision' => 'Damaged revision row, need to be restored from a backup',
33 'unfixable' => 'Unexpected errors with no automated fixing method',
34 'fixed' => 'Errors already fixed',
35 'fixable' => 'Errors which would already be fixed if --fix was specified',
36 );
38 function check( $fix = false, $xml = '' ) {
39 $fname = 'checkStorage';
40 $dbr = wfGetDB( DB_SLAVE );
41 if ( $fix ) {
42 $dbw = wfGetDB( DB_MASTER );
43 print "Checking, will fix errors if possible...\n";
44 } else {
45 print "Checking...\n";
47 $maxRevId = $dbr->selectField( 'revision', 'MAX(rev_id)', false, $fname );
48 $chunkSize = 1000;
49 $flagStats = array();
50 $objectStats = array();
51 $knownFlags = array( 'external', 'gzip', 'object', 'utf-8' );
52 $this->errors = array(
53 'restore text' => array(),
54 'restore revision' => array(),
55 'unfixable' => array(),
56 'fixed' => array(),
57 'fixable' => array(),
60 for ( $chunkStart = 1 ; $chunkStart < $maxRevId; $chunkStart += $chunkSize ) {
61 $chunkEnd = $chunkStart + $chunkSize - 1;
62 //print "$chunkStart of $maxRevId\n";
64 // Fetch revision rows
65 $this->oldIdMap = array();
66 $dbr->ping();
67 $res = $dbr->select( 'revision', array( 'rev_id', 'rev_text_id' ),
68 array( "rev_id BETWEEN $chunkStart AND $chunkEnd" ), $fname );
69 while ( $row = $dbr->fetchObject( $res ) ) {
70 $this->oldIdMap[$row->rev_id] = $row->rev_text_id;
72 $dbr->freeResult( $res );
74 if ( !count( $this->oldIdMap ) ) {
75 continue;
78 // Fetch old_flags
79 $missingTextRows = array_flip( $this->oldIdMap );
80 $externalRevs = array();
81 $objectRevs = array();
82 $res = $dbr->select( 'text', array( 'old_id', 'old_flags' ),
83 'old_id IN (' . implode( ',', $this->oldIdMap ) . ')', $fname );
84 while ( $row = $dbr->fetchObject( $res ) ) {
85 $flags = $row->old_flags;
86 $id = $row->old_id;
88 // Create flagStats row if it doesn't exist
89 $flagStats = $flagStats + array( $flags => 0 );
90 // Increment counter
91 $flagStats[$flags]++;
93 // Not missing
94 unset( $missingTextRows[$row->old_id] );
96 // Check for external or object
97 if ( $flags == '' ) {
98 $flagArray = array();
99 } else {
100 $flagArray = explode( ',', $flags );
102 if ( in_array( 'external', $flagArray ) ) {
103 $externalRevs[] = $id;
104 } elseif ( in_array( 'object', $flagArray ) ) {
105 $objectRevs[] = $id;
108 // Check for unrecognised flags
109 if ( $flags == '0' ) {
110 // This is a known bug from 2004
111 // It's safe to just erase the old_flags field
112 if ( $fix ) {
113 $this->error( 'fixed', "Warning: old_flags set to 0", $id );
114 $dbw->ping();
115 $dbw->update( 'text', array( 'old_flags' => '' ),
116 array( 'old_id' => $id ), $fname );
117 echo "Fixed\n";
118 } else {
119 $this->error( 'fixable', "Warning: old_flags set to 0", $id );
121 } elseif ( count( array_diff( $flagArray, $knownFlags ) ) ) {
122 $this->error( 'unfixable', "Error: invalid flags field \"$flags\"", $id );
125 $dbr->freeResult( $res );
127 // Output errors for any missing text rows
128 foreach ( $missingTextRows as $oldId => $revId ) {
129 $this->error( 'restore revision', "Error: missing text row", $oldId );
132 // Verify external revisions
133 $externalConcatBlobs = array();
134 $externalNormalBlobs = array();
135 if ( count( $externalRevs ) ) {
136 $res = $dbr->select( 'text', array( 'old_id', 'old_flags', 'old_text' ),
137 array( 'old_id IN (' . implode( ',', $externalRevs ) . ')' ), $fname );
138 while ( $row = $dbr->fetchObject( $res ) ) {
139 $urlParts = explode( '://', $row->old_text, 2 );
140 if ( count( $urlParts ) !== 2 || $urlParts[1] == '' ) {
141 $this->error( 'restore text', "Error: invalid URL \"{$row->old_text}\"", $row->old_id );
142 continue;
144 list( $proto, $path ) = $urlParts;
145 if ( $proto != 'DB' ) {
146 $this->error( 'restore text', "Error: invalid external protocol \"$proto\"", $row->old_id );
147 continue;
149 $path = explode( '/', $row->old_text );
150 $cluster = $path[2];
151 $id = $path[3];
152 if ( isset( $path[4] ) ) {
153 $externalConcatBlobs[$cluster][$id][] = $row->old_id;
154 } else {
155 $externalNormalBlobs[$cluster][$id][] = $row->old_id;
158 $dbr->freeResult( $res );
161 // Check external concat blobs for the right header
162 $this->checkExternalConcatBlobs( $externalConcatBlobs );
164 // Check external normal blobs for existence
165 if ( count( $externalNormalBlobs ) ) {
166 if ( is_null( $this->dbStore ) ) {
167 $this->dbStore = new ExternalStoreDB;
169 foreach ( $externalConcatBlobs as $cluster => $xBlobIds ) {
170 $blobIds = array_keys( $xBlobIds );
171 $extDb =& $this->dbStore->getSlave( $cluster );
172 $blobsTable = $this->dbStore->getTable( $extDb );
173 $res = $extDb->select( $blobsTable,
174 array( 'blob_id' ),
175 array( 'blob_id IN( ' . implode( ',', $blobIds ) . ')' ), $fname );
176 while ( $row = $extDb->fetchObject( $res ) ) {
177 unset( $xBlobIds[$row->blob_id] );
179 $extDb->freeResult( $res );
180 // Print errors for missing blobs rows
181 foreach ( $xBlobIds as $blobId => $oldId ) {
182 $this->error( 'restore text', "Error: missing target $blobId for one-part ES URL", $oldId );
187 // Check local objects
188 $dbr->ping();
189 $concatBlobs = array();
190 $curIds = array();
191 if ( count( $objectRevs ) ) {
192 $headerLength = 300;
193 $res = $dbr->select( 'text', array( 'old_id', 'old_flags', "LEFT(old_text, $headerLength) AS header" ),
194 array( 'old_id IN (' . implode( ',', $objectRevs ) . ')' ), $fname );
195 while ( $row = $dbr->fetchObject( $res ) ) {
196 $oldId = $row->old_id;
197 $matches = array();
198 if ( !preg_match( '/^O:(\d+):"(\w+)"/', $row->header, $matches ) ) {
199 $this->error( 'restore text', "Error: invalid object header", $oldId );
200 continue;
203 $className = strtolower( $matches[2] );
204 if ( strlen( $className ) != $matches[1] ) {
205 $this->error( 'restore text', "Error: invalid object header, wrong class name length", $oldId );
206 continue;
209 $objectStats = $objectStats + array( $className => 0 );
210 $objectStats[$className]++;
212 switch ( $className ) {
213 case 'concatenatedgziphistoryblob':
214 // Good
215 break;
216 case 'historyblobstub':
217 case 'historyblobcurstub':
218 if ( strlen( $row->header ) == $headerLength ) {
219 $this->error( 'unfixable', "Error: overlong stub header", $oldId );
220 continue;
222 $stubObj = unserialize( $row->header );
223 if ( !is_object( $stubObj ) ) {
224 $this->error( 'restore text', "Error: unable to unserialize stub object", $oldId );
225 continue;
227 if ( $className == 'historyblobstub' ) {
228 $concatBlobs[$stubObj->mOldId][] = $oldId;
229 } else {
230 $curIds[$stubObj->mCurId][] = $oldId;
232 break;
233 default:
234 $this->error( 'unfixable', "Error: unrecognised object class \"$className\"", $oldId );
237 $dbr->freeResult( $res );
240 // Check local concat blob validity
241 $externalConcatBlobs = array();
242 if ( count( $concatBlobs ) ) {
243 $headerLength = 300;
244 $res = $dbr->select( 'text', array( 'old_id', 'old_flags', "LEFT(old_text, $headerLength) AS header" ),
245 array( 'old_id IN (' . implode( ',', array_keys( $concatBlobs ) ) . ')' ), $fname );
246 while ( $row = $dbr->fetchObject( $res ) ) {
247 $flags = explode( ',', $row->old_flags );
248 if ( in_array( 'external', $flags ) ) {
249 // Concat blob is in external storage?
250 if ( in_array( 'object', $flags ) ) {
251 $urlParts = explode( '/', $row->header );
252 if ( $urlParts[0] != 'DB:' ) {
253 $this->error( 'unfixable', "Error: unrecognised external storage type \"{$urlParts[0]}", $row->old_id );
254 } else {
255 $cluster = $urlParts[2];
256 $id = $urlParts[3];
257 if ( !isset( $externalConcatBlobs[$cluster][$id] ) ) {
258 $externalConcatBlobs[$cluster][$id] = array();
260 $externalConcatBlobs[$cluster][$id] = array_merge(
261 $externalConcatBlobs[$cluster][$id], $concatBlobs[$row->old_id]
264 } else {
265 $this->error( 'unfixable', "Error: invalid flags \"{$row->old_flags}\" on concat bulk row {$row->old_id}",
266 $concatBlobs[$row->old_id] );
268 } elseif ( strcasecmp( substr( $row->header, 0, strlen( CONCAT_HEADER ) ), CONCAT_HEADER ) ) {
269 $this->error( 'restore text', "Error: Incorrect object header for concat bulk row {$row->old_id}",
270 $concatBlobs[$row->old_id] );
271 } # else good
273 unset( $concatBlobs[$row->old_id] );
275 $dbr->freeResult( $res );
278 // Check targets of unresolved stubs
279 $this->checkExternalConcatBlobs( $externalConcatBlobs );
281 // next chunk
284 print "\n\nErrors:\n";
285 foreach( $this->errors as $name => $errors ) {
286 if ( count( $errors ) ) {
287 $description = $this->errorDescriptions[$name];
288 echo "$description: " . implode( ',', array_keys( $errors ) ) . "\n";
292 if ( count( $this->errors['restore text'] ) && $fix ) {
293 if ( (string)$xml !== '' ) {
294 $this->restoreText( array_keys( $this->errors['restore text'] ), $xml );
295 } else {
296 echo "Can't fix text, no XML backup specified\n";
300 print "\nFlag statistics:\n";
301 $total = array_sum( $flagStats );
302 foreach ( $flagStats as $flag => $count ) {
303 printf( "%-30s %10d %5.2f%%\n", $flag, $count, $count / $total * 100 );
305 print "\nLocal object statistics:\n";
306 $total = array_sum( $objectStats );
307 foreach ( $objectStats as $className => $count ) {
308 printf( "%-30s %10d %5.2f%%\n", $className, $count, $count / $total * 100 );
313 function error( $type, $msg, $ids ) {
314 if ( is_array( $ids ) && count( $ids ) == 1 ) {
315 $ids = reset( $ids );
317 if ( is_array( $ids ) ) {
318 $revIds = array();
319 foreach ( $ids as $id ) {
320 $revIds = array_merge( $revIds, array_keys( $this->oldIdMap, $id ) );
322 print "$msg in text rows " . implode( ', ', $ids ) .
323 ", revisions " . implode( ', ', $revIds ) . "\n";
324 } else {
325 $id = $ids;
326 $revIds = array_keys( $this->oldIdMap, $id );
327 if ( count( $revIds ) == 1 ) {
328 print "$msg in old_id $id, rev_id {$revIds[0]}\n";
329 } else {
330 print "$msg in old_id $id, revisions " . implode( ', ', $revIds ) . "\n";
333 $this->errors[$type] = $this->errors[$type] + array_flip( $revIds );
336 function checkExternalConcatBlobs( $externalConcatBlobs ) {
337 $fname = 'CheckStorage::checkExternalConcatBlobs';
338 if ( !count( $externalConcatBlobs ) ) {
339 return;
342 if ( is_null( $this->dbStore ) ) {
343 $this->dbStore = new ExternalStoreDB;
346 foreach ( $externalConcatBlobs as $cluster => $oldIds ) {
347 $blobIds = array_keys( $oldIds );
348 $extDb =& $this->dbStore->getSlave( $cluster );
349 $blobsTable = $this->dbStore->getTable( $extDb );
350 $headerLength = strlen( CONCAT_HEADER );
351 $res = $extDb->select( $blobsTable,
352 array( 'blob_id', "LEFT(blob_text, $headerLength) AS header" ),
353 array( 'blob_id IN( ' . implode( ',', $blobIds ) . ')' ), $fname );
354 while ( $row = $extDb->fetchObject( $res ) ) {
355 if ( strcasecmp( $row->header, CONCAT_HEADER ) ) {
356 $this->error( 'restore text', "Error: invalid header on target $cluster/{$row->blob_id} of two-part ES URL",
357 $oldIds[$row->blob_id] );
359 unset( $oldIds[$row->blob_id] );
362 $extDb->freeResult( $res );
364 // Print errors for missing blobs rows
365 foreach ( $oldIds as $blobId => $oldIds ) {
366 $this->error( 'restore text', "Error: missing target $cluster/$blobId for two-part ES URL", $oldIds );
371 function restoreText( $revIds, $xml ) {
372 global $wgTmpDirectory, $wgDBname;
374 if ( !count( $revIds ) ) {
375 return;
378 print "Restoring text from XML backup...\n";
380 $revFileName = "$wgTmpDirectory/broken-revlist-$wgDBname";
381 $filteredXmlFileName = "$wgTmpDirectory/filtered-$wgDBname.xml";
383 // Write revision list
384 if ( !file_put_contents( $revFileName, implode( "\n", $revIds ) ) ) {
385 echo "Error writing revision list, can't restore text\n";
386 return;
389 // Run mwdumper
390 echo "Filtering XML dump...\n";
391 $exitStatus = 0;
392 passthru( 'mwdumper ' .
393 wfEscapeShellArg(
394 "--output=file:$filteredXmlFileName",
395 "--filter=revlist:$revFileName",
396 $xml
397 ), $exitStatus
400 if ( $exitStatus ) {
401 echo "mwdumper died with exit status $exitStatus\n";
402 return;
405 $file = fopen( $filteredXmlFileName, 'r' );
406 if ( !$file ) {
407 echo "Unable to open filtered XML file\n";
408 return;
411 $dbr = wfGetDB( DB_SLAVE );
412 $dbw = wfGetDB( DB_MASTER );
413 $dbr->ping();
414 $dbw->ping();
416 $source = new ImportStreamSource( $file );
417 $importer = new WikiImporter( $source );
418 $importer->setRevisionCallback( array( &$this, 'importRevision' ) );
419 $importer->doImport();
422 function importRevision( &$revision, &$importer ) {
423 $fname = 'CheckStorage::importRevision';
425 $id = $revision->getID();
426 $text = $revision->getText();
427 if ( $text === '' ) {
428 // This is what happens if the revision was broken at the time the
429 // dump was made. Unfortunately, it also happens if the revision was
430 // legitimately blank, so there's no way to tell the difference. To
431 // be safe, we'll skip it and leave it broken
432 $id = $id ? $id : '';
433 echo "Revision $id is blank in the dump, may have been broken before export\n";
434 return;
437 if ( !$id ) {
438 // No ID, can't import
439 echo "No id tag in revision, can't import\n";
440 return;
443 // Find text row again
444 $dbr = wfGetDB( DB_SLAVE );
445 $oldId = $dbr->selectField( 'revision', 'rev_text_id', array( 'rev_id' => $id ), $fname );
446 if ( !$oldId ) {
447 echo "Missing revision row for rev_id $id\n";
448 return;
451 // Compress the text
452 $flags = Revision::compressRevisionText( $text );
454 // Update the text row
455 $dbw = wfGetDB( DB_MASTER );
456 $dbw->update( 'text',
457 array( 'old_flags' => $flags, 'old_text' => $text ),
458 array( 'old_id' => $oldId ),
459 $fname, array( 'LIMIT' => 1 )
462 // Remove it from the unfixed list and add it to the fixed list
463 unset( $this->errors['restore text'][$id] );
464 $this->errors['fixed'][$id] = true;