31require_once __DIR__ .
'/BackupDumper.php';
32require_once __DIR__ .
'/../../includes/export/WikiExporter.php';
50use Wikimedia\AtEase\AtEase;
65 private $thisRole =
null;
98 protected $php = [ PHP_BINARY ];
147 parent::__construct();
150This script postprocesses XML dumps from dumpBackup.php to add
151page text which was stubbed out (
using --stub).
153XML input is accepted on stdin.
157 $this->stderr = fopen(
"php://stderr",
"wt" );
159 $this->
addOption(
'stub',
'To load a compressed stub dump instead of stdin. ' .
160 'Specify as --stub=<type>:<file>.',
false,
true );
161 $this->
addOption(
'prefetch',
'Use a prior dump file as a text source, to savepressure on the ' .
162 'database. (Requires the XMLReader extension). Specify as --prefetch=<type>:<file>',
164 $this->
addOption(
'maxtime',
'Write out checkpoint file after this many minutes (writing' .
165 'out complete page, closing xml file properly, and opening new one' .
166 'with header). This option requires the checkpointfile option.',
false,
true );
167 $this->
addOption(
'checkpointfile',
'Use this string for checkpoint filenames,substituting ' .
168 'first pageid written for the first %s (required) and the last pageid written for the ' .
169 'second %s if it exists.',
false,
true,
false,
true );
170 $this->
addOption(
'quiet',
'Don\'t dump status reports to stderr.' );
171 $this->
addOption(
'full',
'Dump all revisions of every page' );
172 $this->
addOption(
'current',
'Base ETA on number of pages in database instead of all revisions' );
173 $this->
addOption(
'spawn',
'Spawn a subprocess for loading text records, optionally specify ' .
174 'php[,mwscript] paths' );
175 $this->
addOption(
'buffersize',
'Buffer size in bytes to use for reading the stub. ' .
176 '(Default: 512 KiB, Minimum: 4 KiB)',
false,
true );
185 parent::finalSetup( $settingsBuilder );
193 private function getBlobStore() {
203 parent::processOptions();
205 if ( $this->
hasOption(
'buffersize' ) ) {
206 $this->bufferSize = max( intval( $this->
getOption(
'buffersize' ) ), 4 * 1024 );
219 $this->maxTimeAllowed = intval( $this->
getOption(
'maxtime' ) ) * 60;
222 if ( $this->
hasOption(
'checkpointfile' ) ) {
223 $this->checkpointFiles = $this->
getOption(
'checkpointfile' );
227 $this->history = WikiExporter::CURRENT;
231 $this->history = WikiExporter::FULL;
238 $this->php = explode(
',', $val, 2 );
256 if ( isset( $this->lb ) ) {
257 $this->lb->closeAll( __METHOD__ );
261 if ( $this->forcedDb !==
null ) {
267 if ( isset( $this->db ) && $this->db->isOpen() ) {
268 throw new RuntimeException(
'DB is set and has not been closed by the Load Balancer' );
279 $this->lb = $lbFactory->newMainLB();
280 }
catch ( Exception $e ) {
281 throw new RuntimeException( __METHOD__
282 .
" rotating DB failed to obtain new load balancer (" . $e->getMessage() .
")" );
286 $this->db = $this->lb->getMaintenanceConnectionRef(
DB_REPLICA,
'dump' );
287 }
catch ( Exception $e ) {
288 throw new RuntimeException( __METHOD__
289 .
" rotating DB failed to obtain new database (" . $e->getMessage() .
")" );
294 parent::initProgress();
301 if ( ini_get(
'display_errors' ) ) {
302 ini_set(
'display_errors',
'stderr' );
314 }
catch ( Exception $e ) {
317 $this->
progress(
"Getting initial DB connection failed (" .
318 $e->getMessage() .
")" );
324 $this->finalOptionCheck();
327 $this->xmlwriterobj =
new XmlDumpWriter( XmlDumpWriter::WRITE_CONTENT, $this->schemaVersion );
329 $input = fopen( $this->input,
"rt" );
332 if ( $this->spawnProc ) {
340 $split = explode(
':', $opt, 2 );
343 if ( count( $split ) === 2 ) {
346 $fileURIs = explode(
';', $param );
348 foreach ( $fileURIs as $URI ) {
354 $newURI =
"compress.zlib://$URI";
357 $newURI =
"compress.bzip2://$URI";
360 $newURI =
"mediawiki.compress.7z://$URI";
365 $newFileURIs[] = $newURI;
367 $val = implode(
';', $newFileURIs );
376 if ( !$this->prefetch ) {
377 parent::showReport();
382 if ( $this->reporting ) {
384 $nowts = microtime(
true );
392 $eta = $this->startTime + $deltaAll / $portion;
394 if ( $this->fetchCount ) {
399 $pageRate = $this->pageCount / $deltaAll;
400 $revRate = $this->
revCount / $deltaAll;
408 if ( $this->fetchCountLast ) {
411 $fetchRatePart =
'-';
413 $pageRatePart = $this->pageCountPart / $deltaPart;
414 $revRatePart = $this->revCountPart / $deltaPart;
416 $fetchRatePart =
'-';
421 $dbDomain = WikiMap::getCurrentWikiDbDomain()->getId();
423 "%s: %s (ID %d) %d pages (%0.1f|%0.1f/sec all|curr), "
424 .
"%d revs (%0.1f|%0.1f/sec all|curr), %0.1f%%|%0.1f%% "
425 .
"prefetched (all|curr), ETA %s [max %d]",
426 $now, $dbDomain, $this->ID, $this->pageCount, $pageRate,
427 $pageRatePart, $this->
revCount, $revRate, $revRatePart,
428 $fetchRate, $fetchRatePart, $etats, $this->maxCount
430 $this->lastTime = $nowts;
437 private function setTimeExceeded() {
438 $this->timeExceeded =
true;
441 private function checkIfTimeExceeded() {
442 if ( $this->maxTimeAllowed
443 && ( $this->lastTime - $this->timeOfCheckpoint > $this->maxTimeAllowed )
451 private function finalOptionCheck() {
452 if ( ( $this->checkpointFiles && !$this->maxTimeAllowed )
453 || ( $this->maxTimeAllowed && !$this->checkpointFiles )
455 throw new RuntimeException(
"Options checkpointfile and maxtime must be specified together.\n" );
457 foreach ( $this->checkpointFiles as $checkpointFile ) {
458 $count = substr_count( $checkpointFile,
"%s" );
459 if ( $count !== 2 ) {
460 throw new RuntimeException(
"Option checkpointfile must contain two '%s' "
461 .
"for substitution of first and last pageids, count is $count instead, "
462 .
"file is $checkpointFile.\n" );
466 if ( $this->checkpointFiles ) {
467 $filenameList = (array)$this->egress->getFilenames();
468 if ( count( $filenameList ) !== count( $this->checkpointFiles ) ) {
469 throw new RuntimeException(
"One checkpointfile must be specified "
470 .
"for each output option, if maxtime is used.\n" );
482 $this->openElement =
false;
483 $this->atStart =
true;
485 $this->lastName =
"";
486 $this->thisPage =
"";
488 $this->thisRole =
null;
489 $this->thisRevModel =
null;
490 $this->thisRevFormat =
null;
492 $parser = xml_parser_create(
"UTF-8" );
493 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, 0 );
495 xml_set_element_handler(
497 [ $this,
'startElement' ],
498 [ $this,
'endElement' ]
500 xml_set_character_data_handler( $parser, [ $this,
'characterData' ] );
504 if ( $this->checkIfTimeExceeded() ) {
505 $this->setTimeExceeded();
507 $chunk = fread(
$input, $this->bufferSize );
508 if ( !xml_parse( $parser, $chunk, feof(
$input ) ) ) {
509 wfDebug(
"TextDumpPass::readDump encountered XML parsing error" );
511 $byte = xml_get_current_byte_index( $parser );
513 'XML import parse failure',
514 xml_get_current_line_number( $parser ),
515 xml_get_current_column_number( $parser ),
516 $byte . ( $chunk ===
false ?
'' : (
'; "' . substr( $chunk, $byte - $offset, 16 ) .
'"' ) ),
517 xml_error_string( xml_get_error_code( $parser ) ) )->escaped();
519 xml_parser_free( $parser );
523 $offset += strlen( $chunk );
524 }
while ( $chunk !==
false && !feof(
$input ) );
525 if ( $this->maxTimeAllowed ) {
526 $filenameList = (array)$this->egress->getFilenames();
528 if ( file_exists( $filenameList[0] ) ) {
530 # we might have just written the header and footer and had no
531 # pages or revisions written... perhaps they were all deleted
532 # there's no pageID 0 so we use that. the caller is responsible
533 # for deciding what to do with a file containing only the
534 # siteinfo information and the mw tags.
535 if ( !$this->firstPageWritten ) {
536 $firstPageID = str_pad(
'0', 9,
"0", STR_PAD_LEFT );
537 $lastPageID = str_pad(
'0', 9,
"0", STR_PAD_LEFT );
539 $firstPageID = str_pad( $this->firstPageWritten, 9,
"0", STR_PAD_LEFT );
540 $lastPageID = str_pad( $this->lastPageWritten, 9,
"0", STR_PAD_LEFT );
543 $filenameCount = count( $filenameList );
544 for ( $i = 0; $i < $filenameCount; $i++ ) {
545 $checkpointNameFilledIn = sprintf( $this->checkpointFiles[$i], $firstPageID, $lastPageID );
546 $fileinfo = pathinfo( $filenameList[$i] );
547 $newFilenames[] = $fileinfo[
'dirname'] .
'/' . $checkpointNameFilledIn;
549 $this->egress->closeAndRename( $newFilenames );
552 xml_parser_free( $parser );
566 private function exportTransform( $text, $model, $format =
null ) {
569 ->getContentHandlerFactory()
570 ->getContentHandler( $model );
572 wfWarn(
"Unable to apply export transformation for content model '$model': " .
576 "Unable to apply export transformation for content model '$model': " .
582 return $contentHandler->exportTransform( $text, $format );
605 protected function getText( $id, $model =
null, $format =
null, $expSize =
null ) {
606 if ( !$this->isValidTextId( $id ) ) {
607 $msg =
"Skipping bad text id " . $id .
" of revision " . $this->thisRev;
612 $model = $model ?:
null;
613 $prefetchNotTried =
true;
618 static $consecutiveFailedTextRetrievals = 0;
625 $oldConsecutiveFailedTextRetrievals = $consecutiveFailedTextRetrievals;
626 $consecutiveFailedTextRetrievals = 0;
628 while ( $failures < $this->maxFailures ) {
639 if ( $text ===
false && isset( $this->prefetch ) && $prefetchNotTried ) {
640 $prefetchNotTried =
false;
641 $tryIsPrefetch =
true;
642 $text = $this->prefetch->prefetch(
643 (
int)$this->thisPage,
645 trim( $this->thisRole )
648 if ( is_string( $text ) && $model !==
null ) {
654 $text = $this->exportTransform( $text, $model, $format );
658 if ( $text ===
false ) {
660 $tryIsPrefetch =
false;
661 if ( $this->spawn ) {
662 $text = $this->getTextSpawned( $id );
664 $text = $this->getTextDb( $id );
667 if ( $text !==
false && $model !==
null ) {
670 $text = $this->exportTransform( $text, $model, $format );
676 if ( $text !==
false ) {
681 if ( $text ===
false ) {
682 throw new RuntimeException(
"Generic error while obtaining text for id " . $id );
690 if ( $expSize ===
null || strlen( $text ) == $expSize ) {
692 if ( $tryIsPrefetch ) {
693 $this->prefetchCount++;
700 throw new RuntimeException(
"Received text is unplausible for id " . $id );
701 }
catch ( Exception $e ) {
702 $msg =
"getting/checking text " . $id .
" failed (" . $e->getMessage()
703 .
") for revision " . $this->thisRev;
704 if ( $failures + 1 < $this->maxFailures ) {
705 $msg .=
" (Will retry " . ( $this->maxFailures - $failures - 1 ) .
" more times)";
715 if ( !$tryIsPrefetch ) {
719 sleep( $this->failureTimeout );
722 if ( $this->spawn ) {
726 }
catch ( Exception $e ) {
727 $this->
progress(
"Rebooting getText infrastructure failed (" . $e->getMessage() .
")" .
728 " Trying to continue anyways" );
738 $consecutiveFailedTextRetrievals = $oldConsecutiveFailedTextRetrievals + 1;
739 if ( $consecutiveFailedTextRetrievals > $this->maxConsecutiveFailedTextRetrievals ) {
740 throw new MWException(
"Graceful storage failure" );
752 private function getTextDb( $id ) {
753 $store = $this->getBlobStore();
754 $address = ( is_int( $id ) || strpos( $id,
':' ) === false )
755 ? SqlBlobStore::makeAddressFromTextId( (
int)$id )
759 $text = $store->getBlob( $address );
761 $stripped = str_replace(
"\r",
"", $text );
763 ->normalize( $stripped );
766 }
catch ( BlobAccessException $ex ) {
776 private function getTextSpawned( $address ) {
777 AtEase::suppressWarnings();
778 if ( !$this->spawnProc ) {
782 $text = $this->getTextSpawnedOnce( $address );
783 AtEase::restoreWarnings();
791 $wiki = WikiMap::getCurrentWikiId();
792 if ( count( $this->php ) == 2 ) {
793 $mwscriptpath = $this->php[1];
795 $mwscriptpath =
"$IP/../multiversion/MWScript.php";
797 if ( file_exists( $mwscriptpath ) ) {
799 array_map( [ Shell::class,
'escape' ],
804 '--wiki', $wiki ] ) );
807 array_map( [ Shell::class,
'escape' ],
810 "$IP/maintenance/fetchText.php",
811 '--wiki', $wiki ] ) );
814 0 => [
"pipe",
"r" ],
815 1 => [
"pipe",
"w" ],
816 2 => [
"file",
"/dev/null",
"a" ] ];
819 $this->
progress(
"Spawning database subprocess: $cmd" );
820 $this->spawnProc = proc_open( $cmd, $spec, $pipes );
821 if ( !$this->spawnProc ) {
822 $this->
progress(
"Subprocess spawn failed." );
834 private function closeSpawn() {
835 AtEase::suppressWarnings();
836 if ( $this->spawnRead ) {
837 fclose( $this->spawnRead );
839 $this->spawnRead =
null;
840 if ( $this->spawnWrite ) {
841 fclose( $this->spawnWrite );
843 $this->spawnWrite =
null;
844 if ( $this->spawnErr ) {
845 fclose( $this->spawnErr );
847 $this->spawnErr =
false;
848 if ( $this->spawnProc ) {
849 proc_close( $this->spawnProc );
851 $this->spawnProc =
false;
852 AtEase::restoreWarnings();
859 private function getTextSpawnedOnce( $address ) {
860 if ( is_int( $address ) || intval( $address ) ) {
861 $address = SqlBlobStore::makeAddressFromTextId( (
int)$address );
864 $ok = fwrite( $this->spawnWrite,
"$address\n" );
870 $ok = fflush( $this->spawnWrite );
878 $newAddress = fgets( $this->spawnRead );
879 if ( $newAddress ===
false ) {
882 $newAddress = trim( $newAddress );
883 if ( strpos( $newAddress,
':' ) ===
false ) {
884 $newAddress = SqlBlobStore::makeAddressFromTextId( intval( $newAddress ) );
887 if ( $newAddress !== $address ) {
891 $len = fgets( $this->spawnRead );
893 if ( $len ===
false ) {
897 $nbytes = intval( $len );
906 while ( $nbytes > strlen( $text ) ) {
907 $buffer = fread( $this->spawnRead, $nbytes - strlen( $text ) );
914 $gotbytes = strlen( $text );
915 if ( $gotbytes != $nbytes ) {
916 $this->
progress(
"Expected $nbytes bytes from database subprocess, got $gotbytes " );
922 $stripped = str_replace(
"\r",
"", $text );
924 normalize( $stripped );
930 $this->checkpointJustWritten =
false;
933 $this->lastName = $name;
935 if ( $name ==
'revision' ) {
936 $this->state = $name;
937 $this->egress->writeOpenPage(
null, $this->buffer );
939 } elseif ( $name ==
'page' ) {
940 $this->state = $name;
941 if ( $this->atStart ) {
942 $this->egress->writeOpenStream( $this->buffer );
944 $this->atStart =
false;
946 } elseif ( $name ===
'mediawiki' ) {
947 if ( isset( $attribs[
'version'] ) ) {
948 if ( $attribs[
'version'] !== $this->schemaVersion ) {
949 throw new RuntimeException(
'Mismatching schema version. '
950 .
'Use the --schema-version option to set the output schema version to '
951 .
'the version declared by the stub file, namely ' . $attribs[
'version'] );
956 if ( $name ==
"text" && ( isset( $attribs[
'id'] ) || isset( $attribs[
'location'] ) ) ) {
957 $id = $attribs[
'location'] ?? $attribs[
'id'];
958 $model = trim( $this->thisRevModel );
959 $format = trim( $this->thisRevFormat );
961 $model = $model ===
'' ? null : $model;
962 $format = $format ===
'' ? null : $format;
964 ? (int)$attribs[
'bytes'] :
null;
966 $text = $this->
getText( $id, $model, $format, $expSize );
968 unset( $attribs[
'id'] );
969 unset( $attribs[
'location'] );
970 if ( strlen( $text ) > 0 ) {
971 $attribs[
'xml:space'] =
'preserve';
974 $this->openElement = [ $name, $attribs ];
975 if ( strlen( $text ) > 0 ) {
979 $this->openElement = [ $name, $attribs ];
984 $this->checkpointJustWritten =
false;
986 if ( $this->openElement ) {
989 $this->buffer .=
"</$name>";
992 if ( $name ==
'revision' ) {
993 $this->egress->writeRevision(
null, $this->buffer );
996 $this->thisRole =
null;
997 $this->thisRevModel =
null;
998 $this->thisRevFormat =
null;
999 } elseif ( $name ==
'page' ) {
1000 if ( !$this->firstPageWritten ) {
1001 $this->firstPageWritten = trim( $this->thisPage );
1003 $this->lastPageWritten = trim( $this->thisPage );
1004 if ( $this->timeExceeded ) {
1005 $this->egress->writeClosePage( $this->buffer );
1008 $this->egress->sink->write(
"\n" );
1010 $this->buffer = $this->xmlwriterobj->closeStream();
1011 $this->egress->writeCloseStream( $this->buffer );
1014 $this->thisPage =
"";
1017 $filenameList = (array)$this->egress->getFilenames();
1019 $firstPageID = str_pad( $this->firstPageWritten, 9,
"0", STR_PAD_LEFT );
1020 $lastPageID = str_pad( $this->lastPageWritten, 9,
"0", STR_PAD_LEFT );
1021 $filenamesCount = count( $filenameList );
1022 for ( $i = 0; $i < $filenamesCount; $i++ ) {
1023 $checkpointNameFilledIn = sprintf( $this->checkpointFiles[$i], $firstPageID, $lastPageID );
1024 $fileinfo = pathinfo( $filenameList[$i] );
1025 $newFilenames[] = $fileinfo[
'dirname'] .
'/' . $checkpointNameFilledIn;
1027 $this->egress->closeRenameAndReopen( $newFilenames );
1028 $this->buffer = $this->xmlwriterobj->openStream();
1029 $this->timeExceeded =
false;
1031 $this->firstPageWritten =
false;
1032 $this->checkpointJustWritten =
true;
1034 $this->egress->writeClosePage( $this->buffer );
1036 $this->thisPage =
"";
1038 } elseif ( $name ==
'mediawiki' ) {
1039 $this->egress->writeCloseStream( $this->buffer );
1046 if ( $this->lastName ==
"id" ) {
1047 if ( $this->state ==
"revision" ) {
1048 $this->thisRev .= $data;
1049 $this->thisRole = SlotRecord::MAIN;
1050 } elseif ( $this->state ==
"page" ) {
1051 $this->thisPage .= $data;
1053 } elseif ( $this->lastName ==
"model" ) {
1054 $this->thisRevModel .= $data;
1055 } elseif ( $this->lastName ==
"format" ) {
1056 $this->thisRevFormat .= $data;
1057 } elseif ( $this->lastName ==
"content" ) {
1058 $this->thisRole =
"";
1059 $this->thisRevModel =
"";
1060 $this->thisRevFormat =
"";
1061 } elseif ( $this->lastName ==
"role" ) {
1062 $this->thisRole .= $data;
1067 if ( $this->checkpointJustWritten ) {
1068 if ( $data[0] ==
"\n" ) {
1069 $data = substr( $data, 1 );
1071 $this->checkpointJustWritten =
false;
1073 $this->buffer .= htmlspecialchars( $data, ENT_COMPAT );
1077 if ( $this->openElement ) {
1078 $this->buffer .=
Xml::element( $this->openElement[0], $this->openElement[1], $style );
1079 $this->openElement =
false;
1083 private function isValidTextId( $id ) {
1084 if ( preg_match(
'/:/', $id ) ) {
1085 return $id !==
'tt:0';
1086 } elseif ( preg_match(
'/^\d+$/', $id ) ) {
1087 return intval( $id ) > 0;
1096class_alias( TextPassDumper::class,
'TextPassDumper' );
const CONTENT_MODEL_WIKITEXT
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
wfWarn( $msg, $callerOffset=1, $level=E_USER_NOTICE)
Send a warning either to the debug log or in a PHP error depending on $wgDevelopmentWarnings.
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
if(!defined( 'MEDIAWIKI')) if(ini_get('mbstring.func_overload')) if(!defined( 'MW_ENTRY_POINT')) global $IP
Environment checks.
Readahead helper for making large MediaWiki data dumps; reads in a previous XML dump to sequentially ...
Exception thrown when an unregistered content model is requested.
IMaintainableDatabase null $forcedDb
The dependency-injected database to use.
output( $out, $channel=null)
Throw some output to the user.
loadWithArgv( $argv)
Load params and arguments from a given array of command-line arguments.
addOption( $name, $description, $required=false, $withArg=false, $shortName=false, $multiOccurrence=false)
Add a parameter to the script.
hasOption( $name)
Checks to see if a particular option was set.
getOption( $name, $default=null)
Get an option, or return the default.
getServiceContainer()
Returns the main service container.
addDescription( $text)
Set the description text.
int $maxConsecutiveFailedTextRetrievals
dump( $history, $text=WikiExporter::TEXT)
finalSetup(SettingsBuilder $settingsBuilder)
Handle some last-minute setup here.
clearOpenElement( $style)
characterData( $parser, $data)
processOptions()
Processes arguments and sets $this->$sink accordingly.
startElement( $parser, $name, $attribs)
rotateDb()
Drop the database connection $this->db and try to get a new one.
string false $firstPageWritten
getText( $id, $model=null, $format=null, $expSize=null)
Tries to load revision text.
resource false $spawnProc
showReport()
Overridden to include prefetch ratio if enabled.
initProgress( $history=WikiExporter::FULL)
Initialise starting time and maximum revision count.
bool $checkpointJustWritten
execute()
Do the actual work.
string false $lastPageWritten
XmlDumpWriter false $xmlwriterobj
IMaintainableDatabase $db
string[] $checkpointFiles
resource null $spawnWrite
int $maxTimeAllowed
when we spend more than maxTimeAllowed seconds on this run, we continue processing until we write out...
int $failureTimeout
Seconds to sleep after db failure.
endElement( $parser, $name)
Advanced database interface for IDatabase handles that include maintenance methods.