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