Implement extension registration from an extension.json file
[mediawiki.git] / maintenance / storage / checkStorage.php
blobc0f6c7b6fa80621f61c18283d9cf82996fb86e50
1 <?php
2 /**
3 * Fsck for MediaWiki
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.
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.
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
20 * @file
21 * @ingroup Maintenance ExternalStorage
24 if ( !defined( 'MEDIAWIKI' ) ) {
25 require_once __DIR__ . '/../commandLine.inc';
27 $cs = new CheckStorage;
28 $fix = isset( $options['fix'] );
29 if ( isset( $args[0] ) ) {
30 $xml = $args[0];
31 } else {
32 $xml = false;
34 $cs->check( $fix, $xml );
37 // ----------------------------------------------------------------------------------
39 /**
40 * Maintenance script to do various checks on external storage.
42 * @fixme this should extend the base Maintenance class
43 * @ingroup Maintenance ExternalStorage
45 class CheckStorage {
46 const CONCAT_HEADER = 'O:27:"concatenatedgziphistoryblob"';
47 public $oldIdMap, $errors;
48 public $dbStore = null;
50 public $errorDescriptions = array(
51 'restore text' => 'Damaged text, need to be restored from a backup',
52 'restore revision' => 'Damaged revision row, need to be restored from a backup',
53 'unfixable' => 'Unexpected errors with no automated fixing method',
54 'fixed' => 'Errors already fixed',
55 'fixable' => 'Errors which would already be fixed if --fix was specified',
58 function check( $fix = false, $xml = '' ) {
59 $dbr = wfGetDB( DB_SLAVE );
60 if ( $fix ) {
61 print "Checking, will fix errors if possible...\n";
62 } else {
63 print "Checking...\n";
65 $maxRevId = $dbr->selectField( 'revision', 'MAX(rev_id)', false, __METHOD__ );
66 $chunkSize = 1000;
67 $flagStats = array();
68 $objectStats = array();
69 $knownFlags = array( 'external', 'gzip', 'object', 'utf-8' );
70 $this->errors = array(
71 'restore text' => array(),
72 'restore revision' => array(),
73 'unfixable' => array(),
74 'fixed' => array(),
75 'fixable' => array(),
78 for ( $chunkStart = 1; $chunkStart < $maxRevId; $chunkStart += $chunkSize ) {
79 $chunkEnd = $chunkStart + $chunkSize - 1;
80 // print "$chunkStart of $maxRevId\n";
82 // Fetch revision rows
83 $this->oldIdMap = array();
84 $dbr->ping();
85 $res = $dbr->select( 'revision', array( 'rev_id', 'rev_text_id' ),
86 array( "rev_id BETWEEN $chunkStart AND $chunkEnd" ), __METHOD__ );
87 foreach ( $res as $row ) {
88 $this->oldIdMap[$row->rev_id] = $row->rev_text_id;
90 $dbr->freeResult( $res );
92 if ( !count( $this->oldIdMap ) ) {
93 continue;
96 // Fetch old_flags
97 $missingTextRows = array_flip( $this->oldIdMap );
98 $externalRevs = array();
99 $objectRevs = array();
100 $res = $dbr->select( 'text', array( 'old_id', 'old_flags' ),
101 'old_id IN (' . implode( ',', $this->oldIdMap ) . ')', __METHOD__ );
102 foreach ( $res as $row ) {
104 * @var $flags int
106 $flags = $row->old_flags;
107 $id = $row->old_id;
109 // Create flagStats row if it doesn't exist
110 $flagStats = $flagStats + array( $flags => 0 );
111 // Increment counter
112 $flagStats[$flags]++;
114 // Not missing
115 unset( $missingTextRows[$row->old_id] );
117 // Check for external or object
118 if ( $flags == '' ) {
119 $flagArray = array();
120 } else {
121 $flagArray = explode( ',', $flags );
123 if ( in_array( 'external', $flagArray ) ) {
124 $externalRevs[] = $id;
125 } elseif ( in_array( 'object', $flagArray ) ) {
126 $objectRevs[] = $id;
129 // Check for unrecognised flags
130 if ( $flags == '0' ) {
131 // This is a known bug from 2004
132 // It's safe to just erase the old_flags field
133 if ( $fix ) {
134 $this->error( 'fixed', "Warning: old_flags set to 0", $id );
135 $dbw = wfGetDB( DB_MASTER );
136 $dbw->ping();
137 $dbw->update( 'text', array( 'old_flags' => '' ),
138 array( 'old_id' => $id ), __METHOD__ );
139 echo "Fixed\n";
140 } else {
141 $this->error( 'fixable', "Warning: old_flags set to 0", $id );
143 } elseif ( count( array_diff( $flagArray, $knownFlags ) ) ) {
144 $this->error( 'unfixable', "Error: invalid flags field \"$flags\"", $id );
147 $dbr->freeResult( $res );
149 // Output errors for any missing text rows
150 foreach ( $missingTextRows as $oldId => $revId ) {
151 $this->error( 'restore revision', "Error: missing text row", $oldId );
154 // Verify external revisions
155 $externalConcatBlobs = array();
156 $externalNormalBlobs = array();
157 if ( count( $externalRevs ) ) {
158 $res = $dbr->select( 'text', array( 'old_id', 'old_flags', 'old_text' ),
159 array( 'old_id IN (' . implode( ',', $externalRevs ) . ')' ), __METHOD__ );
160 foreach ( $res as $row ) {
161 $urlParts = explode( '://', $row->old_text, 2 );
162 if ( count( $urlParts ) !== 2 || $urlParts[1] == '' ) {
163 $this->error( 'restore text', "Error: invalid URL \"{$row->old_text}\"", $row->old_id );
164 continue;
166 list( $proto, ) = $urlParts;
167 if ( $proto != 'DB' ) {
168 $this->error( 'restore text', "Error: invalid external protocol \"$proto\"", $row->old_id );
169 continue;
171 $path = explode( '/', $row->old_text );
172 $cluster = $path[2];
173 $id = $path[3];
174 if ( isset( $path[4] ) ) {
175 $externalConcatBlobs[$cluster][$id][] = $row->old_id;
176 } else {
177 $externalNormalBlobs[$cluster][$id][] = $row->old_id;
180 $dbr->freeResult( $res );
183 // Check external concat blobs for the right header
184 $this->checkExternalConcatBlobs( $externalConcatBlobs );
186 // Check external normal blobs for existence
187 if ( count( $externalNormalBlobs ) ) {
188 if ( is_null( $this->dbStore ) ) {
189 $this->dbStore = new ExternalStoreDB;
191 foreach ( $externalConcatBlobs as $cluster => $xBlobIds ) {
192 $blobIds = array_keys( $xBlobIds );
193 $extDb =& $this->dbStore->getSlave( $cluster );
194 $blobsTable = $this->dbStore->getTable( $extDb );
195 $res = $extDb->select( $blobsTable,
196 array( 'blob_id' ),
197 array( 'blob_id IN( ' . implode( ',', $blobIds ) . ')' ), __METHOD__ );
198 foreach ( $res as $row ) {
199 unset( $xBlobIds[$row->blob_id] );
201 $extDb->freeResult( $res );
202 // Print errors for missing blobs rows
203 foreach ( $xBlobIds as $blobId => $oldId ) {
204 $this->error( 'restore text', "Error: missing target $blobId for one-part ES URL", $oldId );
209 // Check local objects
210 $dbr->ping();
211 $concatBlobs = array();
212 $curIds = array();
213 if ( count( $objectRevs ) ) {
214 $headerLength = 300;
215 $res = $dbr->select(
216 'text',
217 array( 'old_id', 'old_flags', "LEFT(old_text, $headerLength) AS header" ),
218 array( 'old_id IN (' . implode( ',', $objectRevs ) . ')' ),
219 __METHOD__
221 foreach ( $res as $row ) {
222 $oldId = $row->old_id;
223 $matches = array();
224 if ( !preg_match( '/^O:(\d+):"(\w+)"/', $row->header, $matches ) ) {
225 $this->error( 'restore text', "Error: invalid object header", $oldId );
226 continue;
229 $className = strtolower( $matches[2] );
230 if ( strlen( $className ) != $matches[1] ) {
231 $this->error(
232 'restore text',
233 "Error: invalid object header, wrong class name length",
234 $oldId
236 continue;
239 $objectStats = $objectStats + array( $className => 0 );
240 $objectStats[$className]++;
242 switch ( $className ) {
243 case 'concatenatedgziphistoryblob':
244 // Good
245 break;
246 case 'historyblobstub':
247 case 'historyblobcurstub':
248 if ( strlen( $row->header ) == $headerLength ) {
249 $this->error( 'unfixable', "Error: overlong stub header", $oldId );
250 continue;
252 $stubObj = unserialize( $row->header );
253 if ( !is_object( $stubObj ) ) {
254 $this->error( 'restore text', "Error: unable to unserialize stub object", $oldId );
255 continue;
257 if ( $className == 'historyblobstub' ) {
258 $concatBlobs[$stubObj->mOldId][] = $oldId;
259 } else {
260 $curIds[$stubObj->mCurId][] = $oldId;
262 break;
263 default:
264 $this->error( 'unfixable', "Error: unrecognised object class \"$className\"", $oldId );
267 $dbr->freeResult( $res );
270 // Check local concat blob validity
271 $externalConcatBlobs = array();
272 if ( count( $concatBlobs ) ) {
273 $headerLength = 300;
274 $res = $dbr->select(
275 'text',
276 array( 'old_id', 'old_flags', "LEFT(old_text, $headerLength) AS header" ),
277 array( 'old_id IN (' . implode( ',', array_keys( $concatBlobs ) ) . ')' ),
278 __METHOD__
280 foreach ( $res as $row ) {
281 $flags = explode( ',', $row->old_flags );
282 if ( in_array( 'external', $flags ) ) {
283 // Concat blob is in external storage?
284 if ( in_array( 'object', $flags ) ) {
285 $urlParts = explode( '/', $row->header );
286 if ( $urlParts[0] != 'DB:' ) {
287 $this->error(
288 'unfixable',
289 "Error: unrecognised external storage type \"{$urlParts[0]}",
290 $row->old_id
292 } else {
293 $cluster = $urlParts[2];
294 $id = $urlParts[3];
295 if ( !isset( $externalConcatBlobs[$cluster][$id] ) ) {
296 $externalConcatBlobs[$cluster][$id] = array();
298 $externalConcatBlobs[$cluster][$id] = array_merge(
299 $externalConcatBlobs[$cluster][$id], $concatBlobs[$row->old_id]
302 } else {
303 $this->error(
304 'unfixable',
305 "Error: invalid flags \"{$row->old_flags}\" on concat bulk row {$row->old_id}",
306 $concatBlobs[$row->old_id] );
308 } elseif ( strcasecmp(
309 substr( $row->header, 0, strlen( self::CONCAT_HEADER ) ),
310 self::CONCAT_HEADER
311 ) ) {
312 $this->error(
313 'restore text',
314 "Error: Incorrect object header for concat bulk row {$row->old_id}",
315 $concatBlobs[$row->old_id]
317 } # else good
319 unset( $concatBlobs[$row->old_id] );
321 $dbr->freeResult( $res );
324 // Check targets of unresolved stubs
325 $this->checkExternalConcatBlobs( $externalConcatBlobs );
326 // next chunk
329 print "\n\nErrors:\n";
330 foreach ( $this->errors as $name => $errors ) {
331 if ( count( $errors ) ) {
332 $description = $this->errorDescriptions[$name];
333 echo "$description: " . implode( ',', array_keys( $errors ) ) . "\n";
337 if ( count( $this->errors['restore text'] ) && $fix ) {
338 if ( (string)$xml !== '' ) {
339 $this->restoreText( array_keys( $this->errors['restore text'] ), $xml );
340 } else {
341 echo "Can't fix text, no XML backup specified\n";
345 print "\nFlag statistics:\n";
346 $total = array_sum( $flagStats );
347 foreach ( $flagStats as $flag => $count ) {
348 printf( "%-30s %10d %5.2f%%\n", $flag, $count, $count / $total * 100 );
350 print "\nLocal object statistics:\n";
351 $total = array_sum( $objectStats );
352 foreach ( $objectStats as $className => $count ) {
353 printf( "%-30s %10d %5.2f%%\n", $className, $count, $count / $total * 100 );
357 function error( $type, $msg, $ids ) {
358 if ( is_array( $ids ) && count( $ids ) == 1 ) {
359 $ids = reset( $ids );
361 if ( is_array( $ids ) ) {
362 $revIds = array();
363 foreach ( $ids as $id ) {
364 $revIds = array_merge( $revIds, array_keys( $this->oldIdMap, $id ) );
366 print "$msg in text rows " . implode( ', ', $ids ) .
367 ", revisions " . implode( ', ', $revIds ) . "\n";
368 } else {
369 $id = $ids;
370 $revIds = array_keys( $this->oldIdMap, $id );
371 if ( count( $revIds ) == 1 ) {
372 print "$msg in old_id $id, rev_id {$revIds[0]}\n";
373 } else {
374 print "$msg in old_id $id, revisions " . implode( ', ', $revIds ) . "\n";
377 $this->errors[$type] = $this->errors[$type] + array_flip( $revIds );
380 function checkExternalConcatBlobs( $externalConcatBlobs ) {
381 if ( !count( $externalConcatBlobs ) ) {
382 return;
385 if ( is_null( $this->dbStore ) ) {
386 $this->dbStore = new ExternalStoreDB;
389 foreach ( $externalConcatBlobs as $cluster => $oldIds ) {
390 $blobIds = array_keys( $oldIds );
391 $extDb =& $this->dbStore->getSlave( $cluster );
392 $blobsTable = $this->dbStore->getTable( $extDb );
393 $headerLength = strlen( self::CONCAT_HEADER );
394 $res = $extDb->select( $blobsTable,
395 array( 'blob_id', "LEFT(blob_text, $headerLength) AS header" ),
396 array( 'blob_id IN( ' . implode( ',', $blobIds ) . ')' ), __METHOD__ );
397 foreach ( $res as $row ) {
398 if ( strcasecmp( $row->header, self::CONCAT_HEADER ) ) {
399 $this->error(
400 'restore text',
401 "Error: invalid header on target $cluster/{$row->blob_id} of two-part ES URL",
402 $oldIds[$row->blob_id]
405 unset( $oldIds[$row->blob_id] );
407 $extDb->freeResult( $res );
409 // Print errors for missing blobs rows
410 foreach ( $oldIds as $blobId => $oldIds2 ) {
411 $this->error(
412 'restore text',
413 "Error: missing target $cluster/$blobId for two-part ES URL",
414 $oldIds2
420 function restoreText( $revIds, $xml ) {
421 global $wgDBname;
422 $tmpDir = wfTempDir();
424 if ( !count( $revIds ) ) {
425 return;
428 print "Restoring text from XML backup...\n";
430 $revFileName = "$tmpDir/broken-revlist-$wgDBname";
431 $filteredXmlFileName = "$tmpDir/filtered-$wgDBname.xml";
433 // Write revision list
434 if ( !file_put_contents( $revFileName, implode( "\n", $revIds ) ) ) {
435 echo "Error writing revision list, can't restore text\n";
437 return;
440 // Run mwdumper
441 echo "Filtering XML dump...\n";
442 $exitStatus = 0;
443 passthru( 'mwdumper ' .
444 wfEscapeShellArg(
445 "--output=file:$filteredXmlFileName",
446 "--filter=revlist:$revFileName",
447 $xml
448 ), $exitStatus
451 if ( $exitStatus ) {
452 echo "mwdumper died with exit status $exitStatus\n";
454 return;
457 $file = fopen( $filteredXmlFileName, 'r' );
458 if ( !$file ) {
459 echo "Unable to open filtered XML file\n";
461 return;
464 $dbr = wfGetDB( DB_SLAVE );
465 $dbw = wfGetDB( DB_MASTER );
466 $dbr->ping();
467 $dbw->ping();
469 $source = new ImportStreamSource( $file );
470 $importer = new WikiImporter(
471 $source,
472 ConfigFactory::getDefaultInstance()->makeConfig( 'main' )
474 $importer->setRevisionCallback( array( &$this, 'importRevision' ) );
475 $importer->doImport();
478 function importRevision( &$revision, &$importer ) {
479 $id = $revision->getID();
480 $content = $revision->getContent( Revision::RAW );
481 $id = $id ? $id : '';
483 if ( $content === null ) {
484 echo "Revision $id is broken, we have no content available\n";
486 return;
489 $text = $content->serialize();
490 if ( $text === '' ) {
491 // This is what happens if the revision was broken at the time the
492 // dump was made. Unfortunately, it also happens if the revision was
493 // legitimately blank, so there's no way to tell the difference. To
494 // be safe, we'll skip it and leave it broken
496 echo "Revision $id is blank in the dump, may have been broken before export\n";
498 return;
501 if ( !$id ) {
502 // No ID, can't import
503 echo "No id tag in revision, can't import\n";
505 return;
508 // Find text row again
509 $dbr = wfGetDB( DB_SLAVE );
510 $oldId = $dbr->selectField( 'revision', 'rev_text_id', array( 'rev_id' => $id ), __METHOD__ );
511 if ( !$oldId ) {
512 echo "Missing revision row for rev_id $id\n";
514 return;
517 // Compress the text
518 $flags = Revision::compressRevisionText( $text );
520 // Update the text row
521 $dbw = wfGetDB( DB_MASTER );
522 $dbw->update( 'text',
523 array( 'old_flags' => $flags, 'old_text' => $text ),
524 array( 'old_id' => $oldId ),
525 __METHOD__, array( 'LIMIT' => 1 )
528 // Remove it from the unfixed list and add it to the fixed list
529 unset( $this->errors['restore text'][$id] );
530 $this->errors['fixed'][$id] = true;