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