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