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