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