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