Merge "Chinese Conversion Table Update 2017-5"
[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 if ( isset( $args[0] ) ) {
33 $xml = $args[0];
34 } else {
35 $xml = false;
36 }
37 $cs->check( $fix, $xml );
38 }
39
40 // ----------------------------------------------------------------------------------
41
42 /**
43 * Maintenance script to do various checks on external storage.
44 *
45 * @fixme this should extend the base Maintenance class
46 * @ingroup Maintenance ExternalStorage
47 */
48 class CheckStorage {
49 const CONCAT_HEADER = 'O:27:"concatenatedgziphistoryblob"';
50 public $oldIdMap, $errors;
51 public $dbStore = null;
52
53 public $errorDescriptions = [
54 'restore text' => 'Damaged text, need to be restored from a backup',
55 'restore revision' => 'Damaged revision row, need to be restored from a backup',
56 'unfixable' => 'Unexpected errors with no automated fixing method',
57 'fixed' => 'Errors already fixed',
58 'fixable' => 'Errors which would already be fixed if --fix was specified',
59 ];
60
61 function check( $fix = false, $xml = '' ) {
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)', false, __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 // Fetch revision rows
86 $this->oldIdMap = [];
87 $dbr->ping();
88 $res = $dbr->select( 'revision', [ 'rev_id', 'rev_text_id' ],
89 [ "rev_id BETWEEN $chunkStart AND $chunkEnd" ], __METHOD__ );
90 foreach ( $res as $row ) {
91 $this->oldIdMap[$row->rev_id] = $row->rev_text_id;
92 }
93 $dbr->freeResult( $res );
94
95 if ( !count( $this->oldIdMap ) ) {
96 continue;
97 }
98
99 // Fetch old_flags
100 $missingTextRows = array_flip( $this->oldIdMap );
101 $externalRevs = [];
102 $objectRevs = [];
103 $res = $dbr->select( 'text', [ 'old_id', 'old_flags' ],
104 'old_id IN (' . implode( ',', $this->oldIdMap ) . ')', __METHOD__ );
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( 'text', [ 'old_id', 'old_flags', 'old_text' ],
162 [ 'old_id IN (' . implode( ',', $externalRevs ) . ')' ], __METHOD__ );
163 foreach ( $res as $row ) {
164 $urlParts = explode( '://', $row->old_text, 2 );
165 if ( count( $urlParts ) !== 2 || $urlParts[1] == '' ) {
166 $this->addError( 'restore text', "Error: invalid URL \"{$row->old_text}\"", $row->old_id );
167 continue;
168 }
169 list( $proto, ) = $urlParts;
170 if ( $proto != 'DB' ) {
171 $this->addError(
172 'restore text',
173 "Error: invalid external protocol \"$proto\"",
174 $row->old_id );
175 continue;
176 }
177 $path = explode( '/', $row->old_text );
178 $cluster = $path[2];
179 $id = $path[3];
180 if ( isset( $path[4] ) ) {
181 $externalConcatBlobs[$cluster][$id][] = $row->old_id;
182 } else {
183 $externalNormalBlobs[$cluster][$id][] = $row->old_id;
184 }
185 }
186 $dbr->freeResult( $res );
187 }
188
189 // Check external concat blobs for the right header
190 $this->checkExternalConcatBlobs( $externalConcatBlobs );
191
192 // Check external normal blobs for existence
193 if ( count( $externalNormalBlobs ) ) {
194 if ( is_null( $this->dbStore ) ) {
195 $this->dbStore = new ExternalStoreDB;
196 }
197 foreach ( $externalConcatBlobs as $cluster => $xBlobIds ) {
198 $blobIds = array_keys( $xBlobIds );
199 $extDb =& $this->dbStore->getSlave( $cluster );
200 $blobsTable = $this->dbStore->getTable( $extDb );
201 $res = $extDb->select( $blobsTable,
202 [ 'blob_id' ],
203 [ 'blob_id IN( ' . implode( ',', $blobIds ) . ')' ], __METHOD__ );
204 foreach ( $res as $row ) {
205 unset( $xBlobIds[$row->blob_id] );
206 }
207 $extDb->freeResult( $res );
208 // Print errors for missing blobs rows
209 foreach ( $xBlobIds as $blobId => $oldId ) {
210 $this->addError(
211 'restore text',
212 "Error: missing target $blobId for one-part ES URL",
213 $oldId );
214 }
215 }
216 }
217
218 // Check local objects
219 $dbr->ping();
220 $concatBlobs = [];
221 $curIds = [];
222 if ( count( $objectRevs ) ) {
223 $headerLength = 300;
224 $res = $dbr->select(
225 'text',
226 [ 'old_id', 'old_flags', "LEFT(old_text, $headerLength) AS header" ],
227 [ 'old_id IN (' . implode( ',', $objectRevs ) . ')' ],
228 __METHOD__
229 );
230 foreach ( $res as $row ) {
231 $oldId = $row->old_id;
232 $matches = [];
233 if ( !preg_match( '/^O:(\d+):"(\w+)"/', $row->header, $matches ) ) {
234 $this->addError( 'restore text', "Error: invalid object header", $oldId );
235 continue;
236 }
237
238 $className = strtolower( $matches[2] );
239 if ( strlen( $className ) != $matches[1] ) {
240 $this->addError(
241 'restore text',
242 "Error: invalid object header, wrong class name length",
243 $oldId
244 );
245 continue;
246 }
247
248 $objectStats = $objectStats + [ $className => 0 ];
249 $objectStats[$className]++;
250
251 switch ( $className ) {
252 case 'concatenatedgziphistoryblob':
253 // Good
254 break;
255 case 'historyblobstub':
256 case 'historyblobcurstub':
257 if ( strlen( $row->header ) == $headerLength ) {
258 $this->addError( 'unfixable', "Error: overlong stub header", $oldId );
259 continue;
260 }
261 $stubObj = unserialize( $row->header );
262 if ( !is_object( $stubObj ) ) {
263 $this->addError( 'restore text', "Error: unable to unserialize stub object", $oldId );
264 continue;
265 }
266 if ( $className == 'historyblobstub' ) {
267 $concatBlobs[$stubObj->mOldId][] = $oldId;
268 } else {
269 $curIds[$stubObj->mCurId][] = $oldId;
270 }
271 break;
272 default:
273 $this->addError( 'unfixable', "Error: unrecognised object class \"$className\"", $oldId );
274 }
275 }
276 $dbr->freeResult( $res );
277 }
278
279 // Check local concat blob validity
280 $externalConcatBlobs = [];
281 if ( count( $concatBlobs ) ) {
282 $headerLength = 300;
283 $res = $dbr->select(
284 'text',
285 [ 'old_id', 'old_flags', "LEFT(old_text, $headerLength) AS header" ],
286 [ 'old_id IN (' . implode( ',', array_keys( $concatBlobs ) ) . ')' ],
287 __METHOD__
288 );
289 foreach ( $res as $row ) {
290 $flags = explode( ',', $row->old_flags );
291 if ( in_array( 'external', $flags ) ) {
292 // Concat blob is in external storage?
293 if ( in_array( 'object', $flags ) ) {
294 $urlParts = explode( '/', $row->header );
295 if ( $urlParts[0] != 'DB:' ) {
296 $this->addError(
297 'unfixable',
298 "Error: unrecognised external storage type \"{$urlParts[0]}",
299 $row->old_id
300 );
301 } else {
302 $cluster = $urlParts[2];
303 $id = $urlParts[3];
304 if ( !isset( $externalConcatBlobs[$cluster][$id] ) ) {
305 $externalConcatBlobs[$cluster][$id] = [];
306 }
307 $externalConcatBlobs[$cluster][$id] = array_merge(
308 $externalConcatBlobs[$cluster][$id], $concatBlobs[$row->old_id]
309 );
310 }
311 } else {
312 $this->addError(
313 'unfixable',
314 "Error: invalid flags \"{$row->old_flags}\" on concat bulk row {$row->old_id}",
315 $concatBlobs[$row->old_id] );
316 }
317 } elseif ( strcasecmp(
318 substr( $row->header, 0, strlen( self::CONCAT_HEADER ) ),
319 self::CONCAT_HEADER
320 ) ) {
321 $this->addError(
322 'restore text',
323 "Error: Incorrect object header for concat bulk row {$row->old_id}",
324 $concatBlobs[$row->old_id]
325 );
326 } # else good
327
328 unset( $concatBlobs[$row->old_id] );
329 }
330 $dbr->freeResult( $res );
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 IN( ' . implode( ',', $blobIds ) . ')' ], __METHOD__ );
406 foreach ( $res as $row ) {
407 if ( strcasecmp( $row->header, self::CONCAT_HEADER ) ) {
408 $this->addError(
409 'restore text',
410 "Error: invalid header on target $cluster/{$row->blob_id} of two-part ES URL",
411 $oldIds[$row->blob_id]
412 );
413 }
414 unset( $oldIds[$row->blob_id] );
415 }
416 $extDb->freeResult( $res );
417
418 // Print errors for missing blobs rows
419 foreach ( $oldIds as $blobId => $oldIds2 ) {
420 $this->addError(
421 'restore text',
422 "Error: missing target $cluster/$blobId for two-part ES URL",
423 $oldIds2
424 );
425 }
426 }
427 }
428
429 function restoreText( $revIds, $xml ) {
430 global $wgDBname;
431 $tmpDir = wfTempDir();
432
433 if ( !count( $revIds ) ) {
434 return;
435 }
436
437 print "Restoring text from XML backup...\n";
438
439 $revFileName = "$tmpDir/broken-revlist-$wgDBname";
440 $filteredXmlFileName = "$tmpDir/filtered-$wgDBname.xml";
441
442 // Write revision list
443 if ( !file_put_contents( $revFileName, implode( "\n", $revIds ) ) ) {
444 echo "Error writing revision list, can't restore text\n";
445
446 return;
447 }
448
449 // Run mwdumper
450 echo "Filtering XML dump...\n";
451 $exitStatus = 0;
452 passthru( 'mwdumper ' .
453 wfEscapeShellArg(
454 "--output=file:$filteredXmlFileName",
455 "--filter=revlist:$revFileName",
456 $xml
457 ), $exitStatus
458 );
459
460 if ( $exitStatus ) {
461 echo "mwdumper died with exit status $exitStatus\n";
462
463 return;
464 }
465
466 $file = fopen( $filteredXmlFileName, 'r' );
467 if ( !$file ) {
468 echo "Unable to open filtered XML file\n";
469
470 return;
471 }
472
473 $dbr = wfGetDB( DB_REPLICA );
474 $dbw = wfGetDB( DB_MASTER );
475 $dbr->ping();
476 $dbw->ping();
477
478 $source = new ImportStreamSource( $file );
479 $importer = new WikiImporter(
480 $source,
481 MediaWikiServices::getInstance()->getMainConfig()
482 );
483 $importer->setRevisionCallback( [ $this, 'importRevision' ] );
484 $importer->doImport();
485 }
486
487 function importRevision( &$revision, &$importer ) {
488 $id = $revision->getID();
489 $content = $revision->getContent( Revision::RAW );
490 $id = $id ? $id : '';
491
492 if ( $content === null ) {
493 echo "Revision $id is broken, we have no content available\n";
494
495 return;
496 }
497
498 $text = $content->serialize();
499 if ( $text === '' ) {
500 // This is what happens if the revision was broken at the time the
501 // dump was made. Unfortunately, it also happens if the revision was
502 // legitimately blank, so there's no way to tell the difference. To
503 // be safe, we'll skip it and leave it broken
504
505 echo "Revision $id is blank in the dump, may have been broken before export\n";
506
507 return;
508 }
509
510 if ( !$id ) {
511 // No ID, can't import
512 echo "No id tag in revision, can't import\n";
513
514 return;
515 }
516
517 // Find text row again
518 $dbr = wfGetDB( DB_REPLICA );
519 $oldId = $dbr->selectField( 'revision', 'rev_text_id', [ 'rev_id' => $id ], __METHOD__ );
520 if ( !$oldId ) {
521 echo "Missing revision row for rev_id $id\n";
522
523 return;
524 }
525
526 // Compress the text
527 $flags = Revision::compressRevisionText( $text );
528
529 // Update the text row
530 $dbw = wfGetDB( DB_MASTER );
531 $dbw->update( 'text',
532 [ 'old_flags' => $flags, 'old_text' => $text ],
533 [ 'old_id' => $oldId ],
534 __METHOD__, [ 'LIMIT' => 1 ]
535 );
536
537 // Remove it from the unfixed list and add it to the fixed list
538 unset( $this->errors['restore text'][$id] );
539 $this->errors['fixed'][$id] = true;
540 }
541 }