Single messages can be passed as strings to Api::dieUsageMsg()
[lhc/web/wiklou.git] / maintenance / storage / checkStorage.php
1 <?php
2 /**
3 * Fsck for MediaWiki
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup Maintenance ExternalStorage
22 */
23
24 define( 'CONCAT_HEADER', 'O:27:"concatenatedgziphistoryblob"' );
25
26 if ( !defined( 'MEDIAWIKI' ) ) {
27 require_once( dirname( __FILE__ ) . '/../commandLine.inc' );
28
29 $cs = new CheckStorage;
30 $fix = isset( $options['fix'] );
31 if ( isset( $args[0] ) ) {
32 $xml = $args[0];
33 } else {
34 $xml = false;
35 }
36 $cs->check( $fix, $xml );
37 }
38
39
40 // ----------------------------------------------------------------------------------
41
42 /**
43 * @ingroup Maintenance ExternalStorage
44 */
45 class CheckStorage {
46 var $oldIdMap, $errors;
47 var $dbStore = null;
48
49 var $errorDescriptions = array(
50 'restore text' => 'Damaged text, need to be restored from a backup',
51 'restore revision' => 'Damaged revision row, need to be restored from a backup',
52 'unfixable' => 'Unexpected errors with no automated fixing method',
53 'fixed' => 'Errors already fixed',
54 'fixable' => 'Errors which would already be fixed if --fix was specified',
55 );
56
57 function check( $fix = false, $xml = '' ) {
58 $fname = 'checkStorage';
59 $dbr = wfGetDB( DB_SLAVE );
60 if ( $fix ) {
61 $dbw = wfGetDB( DB_MASTER );
62 print "Checking, will fix errors if possible...\n";
63 } else {
64 print "Checking...\n";
65 }
66 $maxRevId = $dbr->selectField( 'revision', 'MAX(rev_id)', false, $fname );
67 $chunkSize = 1000;
68 $flagStats = array();
69 $objectStats = array();
70 $knownFlags = array( 'external', 'gzip', 'object', 'utf-8' );
71 $this->errors = array(
72 'restore text' => array(),
73 'restore revision' => array(),
74 'unfixable' => array(),
75 'fixed' => array(),
76 'fixable' => array(),
77 );
78
79 for ( $chunkStart = 1 ; $chunkStart < $maxRevId; $chunkStart += $chunkSize ) {
80 $chunkEnd = $chunkStart + $chunkSize - 1;
81 // print "$chunkStart of $maxRevId\n";
82
83 // Fetch revision rows
84 $this->oldIdMap = array();
85 $dbr->ping();
86 $res = $dbr->select( 'revision', array( 'rev_id', 'rev_text_id' ),
87 array( "rev_id BETWEEN $chunkStart AND $chunkEnd" ), $fname );
88 foreach ( $res as $row ) {
89 $this->oldIdMap[$row->rev_id] = $row->rev_text_id;
90 }
91 $dbr->freeResult( $res );
92
93 if ( !count( $this->oldIdMap ) ) {
94 continue;
95 }
96
97 // Fetch old_flags
98 $missingTextRows = array_flip( $this->oldIdMap );
99 $externalRevs = array();
100 $objectRevs = array();
101 $res = $dbr->select( 'text', array( 'old_id', 'old_flags' ),
102 'old_id IN (' . implode( ',', $this->oldIdMap ) . ')', $fname );
103 foreach ( $res as $row ) {
104 $flags = $row->old_flags;
105 $id = $row->old_id;
106
107 // Create flagStats row if it doesn't exist
108 $flagStats = $flagStats + array( $flags => 0 );
109 // Increment counter
110 $flagStats[$flags]++;
111
112 // Not missing
113 unset( $missingTextRows[$row->old_id] );
114
115 // Check for external or object
116 if ( $flags == '' ) {
117 $flagArray = array();
118 } else {
119 $flagArray = explode( ',', $flags );
120 }
121 if ( in_array( 'external', $flagArray ) ) {
122 $externalRevs[] = $id;
123 } elseif ( in_array( 'object', $flagArray ) ) {
124 $objectRevs[] = $id;
125 }
126
127 // Check for unrecognised flags
128 if ( $flags == '0' ) {
129 // This is a known bug from 2004
130 // It's safe to just erase the old_flags field
131 if ( $fix ) {
132 $this->error( 'fixed', "Warning: old_flags set to 0", $id );
133 $dbw->ping();
134 $dbw->update( 'text', array( 'old_flags' => '' ),
135 array( 'old_id' => $id ), $fname );
136 echo "Fixed\n";
137 } else {
138 $this->error( 'fixable', "Warning: old_flags set to 0", $id );
139 }
140 } elseif ( count( array_diff( $flagArray, $knownFlags ) ) ) {
141 $this->error( 'unfixable', "Error: invalid flags field \"$flags\"", $id );
142 }
143 }
144 $dbr->freeResult( $res );
145
146 // Output errors for any missing text rows
147 foreach ( $missingTextRows as $oldId => $revId ) {
148 $this->error( 'restore revision', "Error: missing text row", $oldId );
149 }
150
151 // Verify external revisions
152 $externalConcatBlobs = array();
153 $externalNormalBlobs = array();
154 if ( count( $externalRevs ) ) {
155 $res = $dbr->select( 'text', array( 'old_id', 'old_flags', 'old_text' ),
156 array( 'old_id IN (' . implode( ',', $externalRevs ) . ')' ), $fname );
157 foreach ( $res as $row ) {
158 $urlParts = explode( '://', $row->old_text, 2 );
159 if ( count( $urlParts ) !== 2 || $urlParts[1] == '' ) {
160 $this->error( 'restore text', "Error: invalid URL \"{$row->old_text}\"", $row->old_id );
161 continue;
162 }
163 list( $proto, ) = $urlParts;
164 if ( $proto != 'DB' ) {
165 $this->error( 'restore text', "Error: invalid external protocol \"$proto\"", $row->old_id );
166 continue;
167 }
168 $path = explode( '/', $row->old_text );
169 $cluster = $path[2];
170 $id = $path[3];
171 if ( isset( $path[4] ) ) {
172 $externalConcatBlobs[$cluster][$id][] = $row->old_id;
173 } else {
174 $externalNormalBlobs[$cluster][$id][] = $row->old_id;
175 }
176 }
177 $dbr->freeResult( $res );
178 }
179
180 // Check external concat blobs for the right header
181 $this->checkExternalConcatBlobs( $externalConcatBlobs );
182
183 // Check external normal blobs for existence
184 if ( count( $externalNormalBlobs ) ) {
185 if ( is_null( $this->dbStore ) ) {
186 $this->dbStore = new ExternalStoreDB;
187 }
188 foreach ( $externalConcatBlobs as $cluster => $xBlobIds ) {
189 $blobIds = array_keys( $xBlobIds );
190 $extDb =& $this->dbStore->getSlave( $cluster );
191 $blobsTable = $this->dbStore->getTable( $extDb );
192 $res = $extDb->select( $blobsTable,
193 array( 'blob_id' ),
194 array( 'blob_id IN( ' . implode( ',', $blobIds ) . ')' ), $fname );
195 foreach ( $res as $row ) {
196 unset( $xBlobIds[$row->blob_id] );
197 }
198 $extDb->freeResult( $res );
199 // Print errors for missing blobs rows
200 foreach ( $xBlobIds as $blobId => $oldId ) {
201 $this->error( 'restore text', "Error: missing target $blobId for one-part ES URL", $oldId );
202 }
203 }
204 }
205
206 // Check local objects
207 $dbr->ping();
208 $concatBlobs = array();
209 $curIds = array();
210 if ( count( $objectRevs ) ) {
211 $headerLength = 300;
212 $res = $dbr->select( 'text', array( 'old_id', 'old_flags', "LEFT(old_text, $headerLength) AS header" ),
213 array( 'old_id IN (' . implode( ',', $objectRevs ) . ')' ), $fname );
214 foreach ( $res as $row ) {
215 $oldId = $row->old_id;
216 $matches = array();
217 if ( !preg_match( '/^O:(\d+):"(\w+)"/', $row->header, $matches ) ) {
218 $this->error( 'restore text', "Error: invalid object header", $oldId );
219 continue;
220 }
221
222 $className = strtolower( $matches[2] );
223 if ( strlen( $className ) != $matches[1] ) {
224 $this->error( 'restore text', "Error: invalid object header, wrong class name length", $oldId );
225 continue;
226 }
227
228 $objectStats = $objectStats + array( $className => 0 );
229 $objectStats[$className]++;
230
231 switch ( $className ) {
232 case 'concatenatedgziphistoryblob':
233 // Good
234 break;
235 case 'historyblobstub':
236 case 'historyblobcurstub':
237 if ( strlen( $row->header ) == $headerLength ) {
238 $this->error( 'unfixable', "Error: overlong stub header", $oldId );
239 continue;
240 }
241 $stubObj = unserialize( $row->header );
242 if ( !is_object( $stubObj ) ) {
243 $this->error( 'restore text', "Error: unable to unserialize stub object", $oldId );
244 continue;
245 }
246 if ( $className == 'historyblobstub' ) {
247 $concatBlobs[$stubObj->mOldId][] = $oldId;
248 } else {
249 $curIds[$stubObj->mCurId][] = $oldId;
250 }
251 break;
252 default:
253 $this->error( 'unfixable', "Error: unrecognised object class \"$className\"", $oldId );
254 }
255 }
256 $dbr->freeResult( $res );
257 }
258
259 // Check local concat blob validity
260 $externalConcatBlobs = array();
261 if ( count( $concatBlobs ) ) {
262 $headerLength = 300;
263 $res = $dbr->select( 'text', array( 'old_id', 'old_flags', "LEFT(old_text, $headerLength) AS header" ),
264 array( 'old_id IN (' . implode( ',', array_keys( $concatBlobs ) ) . ')' ), $fname );
265 foreach ( $res as $row ) {
266 $flags = explode( ',', $row->old_flags );
267 if ( in_array( 'external', $flags ) ) {
268 // Concat blob is in external storage?
269 if ( in_array( 'object', $flags ) ) {
270 $urlParts = explode( '/', $row->header );
271 if ( $urlParts[0] != 'DB:' ) {
272 $this->error( 'unfixable', "Error: unrecognised external storage type \"{$urlParts[0]}", $row->old_id );
273 } else {
274 $cluster = $urlParts[2];
275 $id = $urlParts[3];
276 if ( !isset( $externalConcatBlobs[$cluster][$id] ) ) {
277 $externalConcatBlobs[$cluster][$id] = array();
278 }
279 $externalConcatBlobs[$cluster][$id] = array_merge(
280 $externalConcatBlobs[$cluster][$id], $concatBlobs[$row->old_id]
281 );
282 }
283 } else {
284 $this->error( 'unfixable', "Error: invalid flags \"{$row->old_flags}\" on concat bulk row {$row->old_id}",
285 $concatBlobs[$row->old_id] );
286 }
287 } elseif ( strcasecmp( substr( $row->header, 0, strlen( CONCAT_HEADER ) ), CONCAT_HEADER ) ) {
288 $this->error( 'restore text', "Error: Incorrect object header for concat bulk row {$row->old_id}",
289 $concatBlobs[$row->old_id] );
290 } # else good
291
292 unset( $concatBlobs[$row->old_id] );
293 }
294 $dbr->freeResult( $res );
295 }
296
297 // Check targets of unresolved stubs
298 $this->checkExternalConcatBlobs( $externalConcatBlobs );
299
300 // next chunk
301 }
302
303 print "\n\nErrors:\n";
304 foreach ( $this->errors as $name => $errors ) {
305 if ( count( $errors ) ) {
306 $description = $this->errorDescriptions[$name];
307 echo "$description: " . implode( ',', array_keys( $errors ) ) . "\n";
308 }
309 }
310
311 if ( count( $this->errors['restore text'] ) && $fix ) {
312 if ( (string)$xml !== '' ) {
313 $this->restoreText( array_keys( $this->errors['restore text'] ), $xml );
314 } else {
315 echo "Can't fix text, no XML backup specified\n";
316 }
317 }
318
319 print "\nFlag statistics:\n";
320 $total = array_sum( $flagStats );
321 foreach ( $flagStats as $flag => $count ) {
322 printf( "%-30s %10d %5.2f%%\n", $flag, $count, $count / $total * 100 );
323 }
324 print "\nLocal object statistics:\n";
325 $total = array_sum( $objectStats );
326 foreach ( $objectStats as $className => $count ) {
327 printf( "%-30s %10d %5.2f%%\n", $className, $count, $count / $total * 100 );
328 }
329 }
330
331
332 function error( $type, $msg, $ids ) {
333 if ( is_array( $ids ) && count( $ids ) == 1 ) {
334 $ids = reset( $ids );
335 }
336 if ( is_array( $ids ) ) {
337 $revIds = array();
338 foreach ( $ids as $id ) {
339 $revIds = array_merge( $revIds, array_keys( $this->oldIdMap, $id ) );
340 }
341 print "$msg in text rows " . implode( ', ', $ids ) .
342 ", revisions " . implode( ', ', $revIds ) . "\n";
343 } else {
344 $id = $ids;
345 $revIds = array_keys( $this->oldIdMap, $id );
346 if ( count( $revIds ) == 1 ) {
347 print "$msg in old_id $id, rev_id {$revIds[0]}\n";
348 } else {
349 print "$msg in old_id $id, revisions " . implode( ', ', $revIds ) . "\n";
350 }
351 }
352 $this->errors[$type] = $this->errors[$type] + array_flip( $revIds );
353 }
354
355 function checkExternalConcatBlobs( $externalConcatBlobs ) {
356 $fname = 'CheckStorage::checkExternalConcatBlobs';
357 if ( !count( $externalConcatBlobs ) ) {
358 return;
359 }
360
361 if ( is_null( $this->dbStore ) ) {
362 $this->dbStore = new ExternalStoreDB;
363 }
364
365 foreach ( $externalConcatBlobs as $cluster => $oldIds ) {
366 $blobIds = array_keys( $oldIds );
367 $extDb =& $this->dbStore->getSlave( $cluster );
368 $blobsTable = $this->dbStore->getTable( $extDb );
369 $headerLength = strlen( CONCAT_HEADER );
370 $res = $extDb->select( $blobsTable,
371 array( 'blob_id', "LEFT(blob_text, $headerLength) AS header" ),
372 array( 'blob_id IN( ' . implode( ',', $blobIds ) . ')' ), $fname );
373 foreach ( $res as $row ) {
374 if ( strcasecmp( $row->header, CONCAT_HEADER ) ) {
375 $this->error( 'restore text', "Error: invalid header on target $cluster/{$row->blob_id} of two-part ES URL",
376 $oldIds[$row->blob_id] );
377 }
378 unset( $oldIds[$row->blob_id] );
379
380 }
381 $extDb->freeResult( $res );
382
383 // Print errors for missing blobs rows
384 foreach ( $oldIds as $blobId => $oldIds ) {
385 $this->error( 'restore text', "Error: missing target $cluster/$blobId for two-part ES URL", $oldIds );
386 }
387 }
388 }
389
390 function restoreText( $revIds, $xml ) {
391 global $wgTmpDirectory, $wgDBname;
392
393 if ( !count( $revIds ) ) {
394 return;
395 }
396
397 print "Restoring text from XML backup...\n";
398
399 $revFileName = "$wgTmpDirectory/broken-revlist-$wgDBname";
400 $filteredXmlFileName = "$wgTmpDirectory/filtered-$wgDBname.xml";
401
402 // Write revision list
403 if ( !file_put_contents( $revFileName, implode( "\n", $revIds ) ) ) {
404 echo "Error writing revision list, can't restore text\n";
405 return;
406 }
407
408 // Run mwdumper
409 echo "Filtering XML dump...\n";
410 $exitStatus = 0;
411 passthru( 'mwdumper ' .
412 wfEscapeShellArg(
413 "--output=file:$filteredXmlFileName",
414 "--filter=revlist:$revFileName",
415 $xml
416 ), $exitStatus
417 );
418
419 if ( $exitStatus ) {
420 echo "mwdumper died with exit status $exitStatus\n";
421 return;
422 }
423
424 $file = fopen( $filteredXmlFileName, 'r' );
425 if ( !$file ) {
426 echo "Unable to open filtered XML file\n";
427 return;
428 }
429
430 $dbr = wfGetDB( DB_SLAVE );
431 $dbw = wfGetDB( DB_MASTER );
432 $dbr->ping();
433 $dbw->ping();
434
435 $source = new ImportStreamSource( $file );
436 $importer = new WikiImporter( $source );
437 $importer->setRevisionCallback( array( &$this, 'importRevision' ) );
438 $importer->doImport();
439 }
440
441 function importRevision( &$revision, &$importer ) {
442 $fname = 'CheckStorage::importRevision';
443
444 $id = $revision->getID();
445 $text = $revision->getText();
446 if ( $text === '' ) {
447 // This is what happens if the revision was broken at the time the
448 // dump was made. Unfortunately, it also happens if the revision was
449 // legitimately blank, so there's no way to tell the difference. To
450 // be safe, we'll skip it and leave it broken
451 $id = $id ? $id : '';
452 echo "Revision $id is blank in the dump, may have been broken before export\n";
453 return;
454 }
455
456 if ( !$id ) {
457 // No ID, can't import
458 echo "No id tag in revision, can't import\n";
459 return;
460 }
461
462 // Find text row again
463 $dbr = wfGetDB( DB_SLAVE );
464 $oldId = $dbr->selectField( 'revision', 'rev_text_id', array( 'rev_id' => $id ), $fname );
465 if ( !$oldId ) {
466 echo "Missing revision row for rev_id $id\n";
467 return;
468 }
469
470 // Compress the text
471 $flags = Revision::compressRevisionText( $text );
472
473 // Update the text row
474 $dbw = wfGetDB( DB_MASTER );
475 $dbw->update( 'text',
476 array( 'old_flags' => $flags, 'old_text' => $text ),
477 array( 'old_id' => $oldId ),
478 $fname, array( 'LIMIT' => 1 )
479 );
480
481 // Remove it from the unfixed list and add it to the fixed list
482 unset( $this->errors['restore text'][$id] );
483 $this->errors['fixed'][$id] = true;
484 }
485 }
486