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