Merge "Remove fix for a 5.3 problem"
[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 * Maintenance script to do various checks on external storage.
41 *
42 * @fixme this should extend the base Maintenance class
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 = [
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 = [];
68 $objectStats = [];
69 $knownFlags = [ 'external', 'gzip', 'object', 'utf-8' ];
70 $this->errors = [
71 'restore text' => [],
72 'restore revision' => [],
73 'unfixable' => [],
74 'fixed' => [],
75 'fixable' => [],
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 = [];
84 $dbr->ping();
85 $res = $dbr->select( 'revision', [ 'rev_id', 'rev_text_id' ],
86 [ "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 = [];
99 $objectRevs = [];
100 $res = $dbr->select( 'text', [ '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 + [ $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 = [];
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', [ 'old_flags' => '' ],
138 [ '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 = [];
156 $externalNormalBlobs = [];
157 if ( count( $externalRevs ) ) {
158 $res = $dbr->select( 'text', [ 'old_id', 'old_flags', 'old_text' ],
159 [ '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 [ 'blob_id' ],
197 [ '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 = [];
212 $curIds = [];
213 if ( count( $objectRevs ) ) {
214 $headerLength = 300;
215 $res = $dbr->select(
216 'text',
217 [ 'old_id', 'old_flags', "LEFT(old_text, $headerLength) AS header" ],
218 [ 'old_id IN (' . implode( ',', $objectRevs ) . ')' ],
219 __METHOD__
220 );
221 foreach ( $res as $row ) {
222 $oldId = $row->old_id;
223 $matches = [];
224 if ( !preg_match( '/^O:(\d+):"(\w+)"/', $row->header, $matches ) ) {
225 $this->error( 'restore text', "Error: invalid object header", $oldId );
226 continue;
227 }
228
229 $className = strtolower( $matches[2] );
230 if ( strlen( $className ) != $matches[1] ) {
231 $this->error(
232 'restore text',
233 "Error: invalid object header, wrong class name length",
234 $oldId
235 );
236 continue;
237 }
238
239 $objectStats = $objectStats + [ $className => 0 ];
240 $objectStats[$className]++;
241
242 switch ( $className ) {
243 case 'concatenatedgziphistoryblob':
244 // Good
245 break;
246 case 'historyblobstub':
247 case 'historyblobcurstub':
248 if ( strlen( $row->header ) == $headerLength ) {
249 $this->error( 'unfixable', "Error: overlong stub header", $oldId );
250 continue;
251 }
252 $stubObj = unserialize( $row->header );
253 if ( !is_object( $stubObj ) ) {
254 $this->error( 'restore text', "Error: unable to unserialize stub object", $oldId );
255 continue;
256 }
257 if ( $className == 'historyblobstub' ) {
258 $concatBlobs[$stubObj->mOldId][] = $oldId;
259 } else {
260 $curIds[$stubObj->mCurId][] = $oldId;
261 }
262 break;
263 default:
264 $this->error( 'unfixable', "Error: unrecognised object class \"$className\"", $oldId );
265 }
266 }
267 $dbr->freeResult( $res );
268 }
269
270 // Check local concat blob validity
271 $externalConcatBlobs = [];
272 if ( count( $concatBlobs ) ) {
273 $headerLength = 300;
274 $res = $dbr->select(
275 'text',
276 [ 'old_id', 'old_flags', "LEFT(old_text, $headerLength) AS header" ],
277 [ 'old_id IN (' . implode( ',', array_keys( $concatBlobs ) ) . ')' ],
278 __METHOD__
279 );
280 foreach ( $res as $row ) {
281 $flags = explode( ',', $row->old_flags );
282 if ( in_array( 'external', $flags ) ) {
283 // Concat blob is in external storage?
284 if ( in_array( 'object', $flags ) ) {
285 $urlParts = explode( '/', $row->header );
286 if ( $urlParts[0] != 'DB:' ) {
287 $this->error(
288 'unfixable',
289 "Error: unrecognised external storage type \"{$urlParts[0]}",
290 $row->old_id
291 );
292 } else {
293 $cluster = $urlParts[2];
294 $id = $urlParts[3];
295 if ( !isset( $externalConcatBlobs[$cluster][$id] ) ) {
296 $externalConcatBlobs[$cluster][$id] = [];
297 }
298 $externalConcatBlobs[$cluster][$id] = array_merge(
299 $externalConcatBlobs[$cluster][$id], $concatBlobs[$row->old_id]
300 );
301 }
302 } else {
303 $this->error(
304 'unfixable',
305 "Error: invalid flags \"{$row->old_flags}\" on concat bulk row {$row->old_id}",
306 $concatBlobs[$row->old_id] );
307 }
308 } elseif ( strcasecmp(
309 substr( $row->header, 0, strlen( self::CONCAT_HEADER ) ),
310 self::CONCAT_HEADER
311 ) ) {
312 $this->error(
313 'restore text',
314 "Error: Incorrect object header for concat bulk row {$row->old_id}",
315 $concatBlobs[$row->old_id]
316 );
317 } # else good
318
319 unset( $concatBlobs[$row->old_id] );
320 }
321 $dbr->freeResult( $res );
322 }
323
324 // Check targets of unresolved stubs
325 $this->checkExternalConcatBlobs( $externalConcatBlobs );
326 // next chunk
327 }
328
329 print "\n\nErrors:\n";
330 foreach ( $this->errors as $name => $errors ) {
331 if ( count( $errors ) ) {
332 $description = $this->errorDescriptions[$name];
333 echo "$description: " . implode( ',', array_keys( $errors ) ) . "\n";
334 }
335 }
336
337 if ( count( $this->errors['restore text'] ) && $fix ) {
338 if ( (string)$xml !== '' ) {
339 $this->restoreText( array_keys( $this->errors['restore text'] ), $xml );
340 } else {
341 echo "Can't fix text, no XML backup specified\n";
342 }
343 }
344
345 print "\nFlag statistics:\n";
346 $total = array_sum( $flagStats );
347 foreach ( $flagStats as $flag => $count ) {
348 printf( "%-30s %10d %5.2f%%\n", $flag, $count, $count / $total * 100 );
349 }
350 print "\nLocal object statistics:\n";
351 $total = array_sum( $objectStats );
352 foreach ( $objectStats as $className => $count ) {
353 printf( "%-30s %10d %5.2f%%\n", $className, $count, $count / $total * 100 );
354 }
355 }
356
357 function error( $type, $msg, $ids ) {
358 if ( is_array( $ids ) && count( $ids ) == 1 ) {
359 $ids = reset( $ids );
360 }
361 if ( is_array( $ids ) ) {
362 $revIds = [];
363 foreach ( $ids as $id ) {
364 $revIds = array_merge( $revIds, array_keys( $this->oldIdMap, $id ) );
365 }
366 print "$msg in text rows " . implode( ', ', $ids ) .
367 ", revisions " . implode( ', ', $revIds ) . "\n";
368 } else {
369 $id = $ids;
370 $revIds = array_keys( $this->oldIdMap, $id );
371 if ( count( $revIds ) == 1 ) {
372 print "$msg in old_id $id, rev_id {$revIds[0]}\n";
373 } else {
374 print "$msg in old_id $id, revisions " . implode( ', ', $revIds ) . "\n";
375 }
376 }
377 $this->errors[$type] = $this->errors[$type] + array_flip( $revIds );
378 }
379
380 function checkExternalConcatBlobs( $externalConcatBlobs ) {
381 if ( !count( $externalConcatBlobs ) ) {
382 return;
383 }
384
385 if ( is_null( $this->dbStore ) ) {
386 $this->dbStore = new ExternalStoreDB;
387 }
388
389 foreach ( $externalConcatBlobs as $cluster => $oldIds ) {
390 $blobIds = array_keys( $oldIds );
391 $extDb =& $this->dbStore->getSlave( $cluster );
392 $blobsTable = $this->dbStore->getTable( $extDb );
393 $headerLength = strlen( self::CONCAT_HEADER );
394 $res = $extDb->select( $blobsTable,
395 [ 'blob_id', "LEFT(blob_text, $headerLength) AS header" ],
396 [ 'blob_id IN( ' . implode( ',', $blobIds ) . ')' ], __METHOD__ );
397 foreach ( $res as $row ) {
398 if ( strcasecmp( $row->header, self::CONCAT_HEADER ) ) {
399 $this->error(
400 'restore text',
401 "Error: invalid header on target $cluster/{$row->blob_id} of two-part ES URL",
402 $oldIds[$row->blob_id]
403 );
404 }
405 unset( $oldIds[$row->blob_id] );
406 }
407 $extDb->freeResult( $res );
408
409 // Print errors for missing blobs rows
410 foreach ( $oldIds as $blobId => $oldIds2 ) {
411 $this->error(
412 'restore text',
413 "Error: missing target $cluster/$blobId for two-part ES URL",
414 $oldIds2
415 );
416 }
417 }
418 }
419
420 function restoreText( $revIds, $xml ) {
421 global $wgDBname;
422 $tmpDir = wfTempDir();
423
424 if ( !count( $revIds ) ) {
425 return;
426 }
427
428 print "Restoring text from XML backup...\n";
429
430 $revFileName = "$tmpDir/broken-revlist-$wgDBname";
431 $filteredXmlFileName = "$tmpDir/filtered-$wgDBname.xml";
432
433 // Write revision list
434 if ( !file_put_contents( $revFileName, implode( "\n", $revIds ) ) ) {
435 echo "Error writing revision list, can't restore text\n";
436
437 return;
438 }
439
440 // Run mwdumper
441 echo "Filtering XML dump...\n";
442 $exitStatus = 0;
443 passthru( 'mwdumper ' .
444 wfEscapeShellArg(
445 "--output=file:$filteredXmlFileName",
446 "--filter=revlist:$revFileName",
447 $xml
448 ), $exitStatus
449 );
450
451 if ( $exitStatus ) {
452 echo "mwdumper died with exit status $exitStatus\n";
453
454 return;
455 }
456
457 $file = fopen( $filteredXmlFileName, 'r' );
458 if ( !$file ) {
459 echo "Unable to open filtered XML file\n";
460
461 return;
462 }
463
464 $dbr = wfGetDB( DB_SLAVE );
465 $dbw = wfGetDB( DB_MASTER );
466 $dbr->ping();
467 $dbw->ping();
468
469 $source = new ImportStreamSource( $file );
470 $importer = new WikiImporter(
471 $source,
472 ConfigFactory::getDefaultInstance()->makeConfig( 'main' )
473 );
474 $importer->setRevisionCallback( [ $this, 'importRevision' ] );
475 $importer->doImport();
476 }
477
478 function importRevision( &$revision, &$importer ) {
479 $id = $revision->getID();
480 $content = $revision->getContent( Revision::RAW );
481 $id = $id ? $id : '';
482
483 if ( $content === null ) {
484 echo "Revision $id is broken, we have no content available\n";
485
486 return;
487 }
488
489 $text = $content->serialize();
490 if ( $text === '' ) {
491 // This is what happens if the revision was broken at the time the
492 // dump was made. Unfortunately, it also happens if the revision was
493 // legitimately blank, so there's no way to tell the difference. To
494 // be safe, we'll skip it and leave it broken
495
496 echo "Revision $id is blank in the dump, may have been broken before export\n";
497
498 return;
499 }
500
501 if ( !$id ) {
502 // No ID, can't import
503 echo "No id tag in revision, can't import\n";
504
505 return;
506 }
507
508 // Find text row again
509 $dbr = wfGetDB( DB_SLAVE );
510 $oldId = $dbr->selectField( 'revision', 'rev_text_id', [ 'rev_id' => $id ], __METHOD__ );
511 if ( !$oldId ) {
512 echo "Missing revision row for rev_id $id\n";
513
514 return;
515 }
516
517 // Compress the text
518 $flags = Revision::compressRevisionText( $text );
519
520 // Update the text row
521 $dbw = wfGetDB( DB_MASTER );
522 $dbw->update( 'text',
523 [ 'old_flags' => $flags, 'old_text' => $text ],
524 [ 'old_id' => $oldId ],
525 __METHOD__, [ 'LIMIT' => 1 ]
526 );
527
528 // Remove it from the unfixed list and add it to the fixed list
529 unset( $this->errors['restore text'][$id] );
530 $this->errors['fixed'][$id] = true;
531 }
532 }