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