31require_once __DIR__ .
'/BackupDumper.php';
32require_once __DIR__ .
'/../../includes/export/WikiExporter.php';
51use Wikimedia\AtEase\AtEase;
65 private $thisRole =
null;
98 protected $php = [ PHP_BINARY ];
142 parent::__construct();
145This script postprocesses XML dumps from dumpBackup.php to add
146page text which was stubbed out (
using --stub).
148XML input is accepted on stdin.
152 $this->stderr = fopen(
"php://stderr",
"wt" );
154 $this->
addOption(
'stub',
'To load a compressed stub dump instead of stdin. ' .
155 'Specify as --stub=<type>:<file>.',
false,
true );
156 $this->
addOption(
'prefetch',
'Use a prior dump file as a text source, to savepressure on the ' .
157 'database. (Requires the XMLReader extension). Specify as --prefetch=<type>:<file>',
159 $this->
addOption(
'maxtime',
'Write out checkpoint file after this many minutes (writing' .
160 'out complete page, closing xml file properly, and opening new one' .
161 'with header). This option requires the checkpointfile option.',
false,
true );
162 $this->
addOption(
'checkpointfile',
'Use this string for checkpoint filenames,substituting ' .
163 'first pageid written for the first %s (required) and the last pageid written for the ' .
164 'second %s if it exists.',
false,
true,
false,
true );
165 $this->
addOption(
'quiet',
'Don\'t dump status reports to stderr.' );
166 $this->
addOption(
'full',
'Dump all revisions of every page' );
167 $this->
addOption(
'current',
'Base ETA on number of pages in database instead of all revisions' );
168 $this->
addOption(
'spawn',
'Spawn a subprocess for loading text records, optionally specify ' .
169 'php[,mwscript] paths' );
170 $this->
addOption(
'buffersize',
'Buffer size in bytes to use for reading the stub. ' .
171 '(Default: 512 KiB, Minimum: 4 KiB)',
false,
true );
180 parent::finalSetup( $settingsBuilder );
188 private function getBlobStore() {
195 private function getRevisionStore() {
205 parent::processOptions();
207 if ( $this->
hasOption(
'buffersize' ) ) {
208 $this->bufferSize = max( intval( $this->
getOption(
'buffersize' ) ), 4 * 1024 );
221 $this->maxTimeAllowed = intval( $this->
getOption(
'maxtime' ) ) * 60;
224 if ( $this->
hasOption(
'checkpointfile' ) ) {
225 $this->checkpointFiles = $this->
getOption(
'checkpointfile' );
229 $this->history = WikiExporter::CURRENT;
233 $this->history = WikiExporter::FULL;
240 $this->php = explode(
',', $val, 2 );
246 parent::initProgress();
253 if ( ini_get(
'display_errors' ) ) {
254 ini_set(
'display_errors',
'stderr' );
262 $this->finalOptionCheck();
265 $this->xmlwriterobj =
new XmlDumpWriter( XmlDumpWriter::WRITE_CONTENT, $this->schemaVersion );
267 $input = fopen( $this->input,
"rt" );
270 if ( $this->spawnProc ) {
278 $split = explode(
':', $opt, 2 );
281 if ( count( $split ) === 2 ) {
284 $fileURIs = explode(
';', $param );
286 foreach ( $fileURIs as $URI ) {
292 $newURI =
"compress.zlib://$URI";
295 $newURI =
"compress.bzip2://$URI";
298 $newURI =
"mediawiki.compress.7z://$URI";
303 $newFileURIs[] = $newURI;
305 $val = implode(
';', $newFileURIs );
314 if ( !$this->prefetch ) {
315 parent::showReport();
320 if ( $this->reporting ) {
322 $nowts = microtime(
true );
330 $eta = $this->startTime + $deltaAll / $portion;
332 if ( $this->fetchCount ) {
337 $pageRate = $this->pageCount / $deltaAll;
338 $revRate = $this->
revCount / $deltaAll;
346 if ( $this->fetchCountLast ) {
349 $fetchRatePart =
'-';
351 $pageRatePart = $this->pageCountPart / $deltaPart;
352 $revRatePart = $this->revCountPart / $deltaPart;
354 $fetchRatePart =
'-';
359 $dbDomain = WikiMap::getCurrentWikiDbDomain()->getId();
361 "%s: %s (ID %d) %d pages (%0.1f|%0.1f/sec all|curr), "
362 .
"%d revs (%0.1f|%0.1f/sec all|curr), %0.1f%%|%0.1f%% "
363 .
"prefetched (all|curr), ETA %s [max %d]",
364 $now, $dbDomain, $this->ID, $this->pageCount, $pageRate,
365 $pageRatePart, $this->
revCount, $revRate, $revRatePart,
366 $fetchRate, $fetchRatePart, $etats, $this->maxCount
368 $this->lastTime = $nowts;
375 private function setTimeExceeded() {
376 $this->timeExceeded =
true;
379 private function checkIfTimeExceeded() {
380 if ( $this->maxTimeAllowed
381 && ( $this->lastTime - $this->timeOfCheckpoint > $this->maxTimeAllowed )
389 private function finalOptionCheck() {
390 if ( ( $this->checkpointFiles && !$this->maxTimeAllowed )
391 || ( $this->maxTimeAllowed && !$this->checkpointFiles )
393 throw new RuntimeException(
"Options checkpointfile and maxtime must be specified together.\n" );
395 foreach ( $this->checkpointFiles as $checkpointFile ) {
396 $count = substr_count( $checkpointFile,
"%s" );
397 if ( $count !== 2 ) {
398 throw new RuntimeException(
"Option checkpointfile must contain two '%s' "
399 .
"for substitution of first and last pageids, count is $count instead, "
400 .
"file is $checkpointFile.\n" );
404 if ( $this->checkpointFiles ) {
405 $filenameList = (array)$this->egress->getFilenames();
406 if ( count( $filenameList ) !== count( $this->checkpointFiles ) ) {
407 throw new RuntimeException(
"One checkpointfile must be specified "
408 .
"for each output option, if maxtime is used.\n" );
420 $this->openElement =
false;
421 $this->atStart =
true;
423 $this->lastName =
"";
424 $this->thisPage =
"";
426 $this->thisRole =
null;
427 $this->thisRevModel =
null;
428 $this->thisRevFormat =
null;
430 $parser = xml_parser_create(
"UTF-8" );
431 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, 0 );
433 xml_set_element_handler(
435 [ $this,
'startElement' ],
436 [ $this,
'endElement' ]
438 xml_set_character_data_handler( $parser, [ $this,
'characterData' ] );
442 if ( $this->checkIfTimeExceeded() ) {
443 $this->setTimeExceeded();
445 $chunk = fread(
$input, $this->bufferSize );
446 if ( !xml_parse( $parser, $chunk, feof(
$input ) ) ) {
447 wfDebug(
"TextDumpPass::readDump encountered XML parsing error" );
449 $byte = xml_get_current_byte_index( $parser );
451 'XML import parse failure',
452 xml_get_current_line_number( $parser ),
453 xml_get_current_column_number( $parser ),
454 $byte . ( $chunk ===
false ?
'' : (
'; "' . substr( $chunk, $byte - $offset, 16 ) .
'"' ) ),
455 xml_error_string( xml_get_error_code( $parser ) ) )->escaped();
457 xml_parser_free( $parser );
461 $offset += strlen( $chunk );
462 }
while ( $chunk !==
false && !feof(
$input ) );
463 if ( $this->maxTimeAllowed ) {
464 $filenameList = (array)$this->egress->getFilenames();
466 if ( file_exists( $filenameList[0] ) ) {
468 # we might have just written the header and footer and had no
469 # pages or revisions written... perhaps they were all deleted
470 # there's no pageID 0 so we use that. the caller is responsible
471 # for deciding what to do with a file containing only the
472 # siteinfo information and the mw tags.
473 if ( !$this->firstPageWritten ) {
474 $firstPageID = str_pad(
'0', 9,
"0", STR_PAD_LEFT );
475 $lastPageID = str_pad(
'0', 9,
"0", STR_PAD_LEFT );
477 $firstPageID = str_pad( $this->firstPageWritten, 9,
"0", STR_PAD_LEFT );
478 $lastPageID = str_pad( $this->lastPageWritten, 9,
"0", STR_PAD_LEFT );
481 $filenameCount = count( $filenameList );
482 for ( $i = 0; $i < $filenameCount; $i++ ) {
483 $checkpointNameFilledIn = sprintf( $this->checkpointFiles[$i], $firstPageID, $lastPageID );
484 $fileinfo = pathinfo( $filenameList[$i] );
485 $newFilenames[] = $fileinfo[
'dirname'] .
'/' . $checkpointNameFilledIn;
487 $this->egress->closeAndRename( $newFilenames );
490 xml_parser_free( $parser );
504 private function exportTransform( $text, $model, $format =
null ) {
507 ->getContentHandlerFactory()
508 ->getContentHandler( $model );
510 wfWarn(
"Unable to apply export transformation for content model '$model': " .
514 "Unable to apply export transformation for content model '$model': " .
520 return $contentHandler->exportTransform( $text, $format );
543 protected function getText( $id, $model =
null, $format =
null, $expSize =
null ) {
544 if ( !$this->isValidTextId( $id ) ) {
545 $msg =
"Skipping bad text id " . $id .
" of revision " . $this->thisRev;
550 $model = $model ?:
null;
551 $prefetchNotTried =
true;
554 $contentAddress = $id;
557 static $consecutiveFailedTextRetrievals = 0;
564 $oldConsecutiveFailedTextRetrievals = $consecutiveFailedTextRetrievals;
565 $consecutiveFailedTextRetrievals = 0;
567 while ( $failures < $this->maxFailures ) {
578 if ( $text ===
false && isset( $this->prefetch ) && $prefetchNotTried ) {
579 $prefetchNotTried =
false;
580 $tryIsPrefetch =
true;
581 $text = $this->prefetch->prefetch(
582 (
int)$this->thisPage,
584 trim( $this->thisRole )
587 if ( is_string( $text ) && $model !==
null ) {
593 $text = $this->exportTransform( $text, $model, $format );
597 if ( $text ===
false ) {
599 $tryIsPrefetch =
false;
600 if ( $this->spawn ) {
601 $text = $this->getTextSpawned( $contentAddress );
603 $text = $this->getTextDb( $contentAddress );
606 if ( $text !==
false && $model !==
null ) {
609 $text = $this->exportTransform( $text, $model, $format );
615 if ( $text !==
false ) {
620 if ( $text ===
false ) {
621 throw new RuntimeException(
"Generic error while obtaining text for id " . $contentAddress );
629 if ( $expSize ===
null || strlen( $text ) == $expSize ) {
631 if ( $tryIsPrefetch ) {
632 $this->prefetchCount++;
639 throw new RuntimeException(
"Received text is unplausible for id " . $contentAddress );
640 }
catch ( Exception $e ) {
641 $msg =
"getting/checking text " . $contentAddress .
" failed (" . $e->getMessage()
642 .
") for revision " . $this->thisRev;
643 if ( $failures + 1 < $this->maxFailures ) {
644 $msg .=
" (Will retry " . ( $this->maxFailures - $failures - 1 ) .
" more times)";
652 if ( $contentAddress === $id && $this->thisRev && trim( $this->thisRole ) ) {
657 $revRecord = $this->getRevisionStore()->getRevisionById( (
int)$this->thisRev );
658 if ( $revRecord !==
null ) {
659 $refreshed = $revRecord->getSlot( trim( $this->thisRole ) )->getAddress();
660 if ( $contentAddress !== $refreshed ) {
662 "Updated content address for rev {$this->thisRev} from "
663 .
"{$contentAddress} to {$refreshed}"
665 $contentAddress = $refreshed;
670 }
catch ( Exception $e ) {
672 "refreshing content address for revision {$this->thisRev} failed ({$e->getMessage()})"
678 if ( !$tryIsPrefetch ) {
682 sleep( $this->failureTimeout );
684 if ( $this->spawn ) {
688 }
catch ( Exception $e ) {
689 $this->
progress(
"Rebooting getText infrastructure failed (" . $e->getMessage() .
")" .
690 " Trying to continue anyways" );
700 $consecutiveFailedTextRetrievals = $oldConsecutiveFailedTextRetrievals + 1;
701 if ( $consecutiveFailedTextRetrievals > $this->maxConsecutiveFailedTextRetrievals ) {
702 throw new MWException(
"Graceful storage failure" );
714 private function getTextDb( $id ) {
715 $store = $this->getBlobStore();
716 $address = ( is_int( $id ) || strpos( $id,
':' ) === false )
717 ? SqlBlobStore::makeAddressFromTextId( (
int)$id )
721 $text = $store->getBlob( $address );
723 $stripped = str_replace(
"\r",
"", $text );
725 ->normalize( $stripped );
728 }
catch ( BlobAccessException $ex ) {
738 private function getTextSpawned( $address ) {
739 AtEase::suppressWarnings();
740 if ( !$this->spawnProc ) {
744 $text = $this->getTextSpawnedOnce( $address );
745 AtEase::restoreWarnings();
753 $wiki = WikiMap::getCurrentWikiId();
754 if ( count( $this->php ) == 2 ) {
755 $mwscriptpath = $this->php[1];
757 $mwscriptpath =
"$IP/../multiversion/MWScript.php";
759 if ( file_exists( $mwscriptpath ) ) {
761 array_map( [ Shell::class,
'escape' ],
766 '--wiki', $wiki ] ) );
769 array_map( [ Shell::class,
'escape' ],
772 "$IP/maintenance/fetchText.php",
773 '--wiki', $wiki ] ) );
776 0 => [
"pipe",
"r" ],
777 1 => [
"pipe",
"w" ],
778 2 => [
"file",
"/dev/null",
"a" ] ];
781 $this->
progress(
"Spawning database subprocess: $cmd" );
782 $this->spawnProc = proc_open( $cmd, $spec, $pipes );
783 if ( !$this->spawnProc ) {
784 $this->
progress(
"Subprocess spawn failed." );
796 private function closeSpawn() {
797 AtEase::suppressWarnings();
798 if ( $this->spawnRead ) {
799 fclose( $this->spawnRead );
801 $this->spawnRead =
null;
802 if ( $this->spawnWrite ) {
803 fclose( $this->spawnWrite );
805 $this->spawnWrite =
null;
806 if ( $this->spawnErr ) {
807 fclose( $this->spawnErr );
809 $this->spawnErr =
false;
810 if ( $this->spawnProc ) {
811 pclose( $this->spawnProc );
813 $this->spawnProc =
false;
814 AtEase::restoreWarnings();
821 private function getTextSpawnedOnce( $address ) {
822 if ( is_int( $address ) || intval( $address ) ) {
823 $address = SqlBlobStore::makeAddressFromTextId( (
int)$address );
826 $ok = fwrite( $this->spawnWrite,
"$address\n" );
832 $ok = fflush( $this->spawnWrite );
840 $newAddress = fgets( $this->spawnRead );
841 if ( $newAddress ===
false ) {
844 $newAddress = trim( $newAddress );
845 if ( strpos( $newAddress,
':' ) ===
false ) {
846 $newAddress = SqlBlobStore::makeAddressFromTextId( intval( $newAddress ) );
849 if ( $newAddress !== $address ) {
853 $len = fgets( $this->spawnRead );
855 if ( $len ===
false ) {
859 $nbytes = intval( $len );
868 while ( $nbytes > strlen( $text ) ) {
869 $buffer = fread( $this->spawnRead, $nbytes - strlen( $text ) );
876 $gotbytes = strlen( $text );
877 if ( $gotbytes != $nbytes ) {
878 $this->
progress(
"Expected $nbytes bytes from database subprocess, got $gotbytes " );
884 $stripped = str_replace(
"\r",
"", $text );
886 normalize( $stripped );
892 $this->checkpointJustWritten =
false;
895 $this->lastName = $name;
897 if ( $name ==
'revision' ) {
898 $this->state = $name;
899 $this->egress->writeOpenPage(
null, $this->buffer );
901 } elseif ( $name ==
'page' ) {
902 $this->state = $name;
903 if ( $this->atStart ) {
904 $this->egress->writeOpenStream( $this->buffer );
906 $this->atStart =
false;
908 } elseif ( $name ===
'mediawiki' ) {
909 if ( isset( $attribs[
'version'] ) ) {
910 if ( $attribs[
'version'] !== $this->schemaVersion ) {
911 throw new RuntimeException(
'Mismatching schema version. '
912 .
'Use the --schema-version option to set the output schema version to '
913 .
'the version declared by the stub file, namely ' . $attribs[
'version'] );
918 if ( $name ==
"text" && ( isset( $attribs[
'id'] ) || isset( $attribs[
'location'] ) ) ) {
919 $id = $attribs[
'location'] ?? $attribs[
'id'];
920 $model = trim( $this->thisRevModel );
921 $format = trim( $this->thisRevFormat );
923 $model = $model ===
'' ? null : $model;
924 $format = $format ===
'' ? null : $format;
926 ? (int)$attribs[
'bytes'] :
null;
928 $text = $this->
getText( $id, $model, $format, $expSize );
930 unset( $attribs[
'id'] );
931 unset( $attribs[
'location'] );
932 if ( strlen( $text ) > 0 ) {
933 $attribs[
'xml:space'] =
'preserve';
936 $this->openElement = [ $name, $attribs ];
937 if ( strlen( $text ) > 0 ) {
941 $this->openElement = [ $name, $attribs ];
946 $this->checkpointJustWritten =
false;
948 if ( $this->openElement ) {
951 $this->buffer .=
"</$name>";
954 if ( $name ==
'revision' ) {
955 $this->egress->writeRevision(
null, $this->buffer );
958 $this->thisRole =
null;
959 $this->thisRevModel =
null;
960 $this->thisRevFormat =
null;
961 } elseif ( $name ==
'page' ) {
962 if ( !$this->firstPageWritten ) {
963 $this->firstPageWritten = trim( $this->thisPage );
965 $this->lastPageWritten = trim( $this->thisPage );
966 if ( $this->timeExceeded ) {
967 $this->egress->writeClosePage( $this->buffer );
970 $this->egress->sink->write(
"\n" );
972 $this->buffer = $this->xmlwriterobj->closeStream();
973 $this->egress->writeCloseStream( $this->buffer );
976 $this->thisPage =
"";
979 $filenameList = (array)$this->egress->getFilenames();
981 $firstPageID = str_pad( $this->firstPageWritten, 9,
"0", STR_PAD_LEFT );
982 $lastPageID = str_pad( $this->lastPageWritten, 9,
"0", STR_PAD_LEFT );
983 $filenamesCount = count( $filenameList );
984 for ( $i = 0; $i < $filenamesCount; $i++ ) {
985 $checkpointNameFilledIn = sprintf( $this->checkpointFiles[$i], $firstPageID, $lastPageID );
986 $fileinfo = pathinfo( $filenameList[$i] );
987 $newFilenames[] = $fileinfo[
'dirname'] .
'/' . $checkpointNameFilledIn;
989 $this->egress->closeRenameAndReopen( $newFilenames );
990 $this->buffer = $this->xmlwriterobj->openStream();
991 $this->timeExceeded =
false;
993 $this->firstPageWritten =
false;
994 $this->checkpointJustWritten =
true;
996 $this->egress->writeClosePage( $this->buffer );
998 $this->thisPage =
"";
1000 } elseif ( $name ==
'mediawiki' ) {
1001 $this->egress->writeCloseStream( $this->buffer );
1008 if ( $this->lastName ==
"id" ) {
1009 if ( $this->state ==
"revision" ) {
1010 $this->thisRev .= $data;
1011 $this->thisRole = SlotRecord::MAIN;
1012 } elseif ( $this->state ==
"page" ) {
1013 $this->thisPage .= $data;
1015 } elseif ( $this->lastName ==
"model" ) {
1016 $this->thisRevModel .= $data;
1017 } elseif ( $this->lastName ==
"format" ) {
1018 $this->thisRevFormat .= $data;
1019 } elseif ( $this->lastName ==
"content" ) {
1020 $this->thisRole =
"";
1021 $this->thisRevModel =
"";
1022 $this->thisRevFormat =
"";
1023 } elseif ( $this->lastName ==
"role" ) {
1024 $this->thisRole .= $data;
1029 if ( $this->checkpointJustWritten ) {
1030 if ( $data[0] ==
"\n" ) {
1031 $data = substr( $data, 1 );
1033 $this->checkpointJustWritten =
false;
1035 $this->buffer .= htmlspecialchars( $data, ENT_COMPAT );
1039 if ( $this->openElement ) {
1040 $this->buffer .=
Xml::element( $this->openElement[0], $this->openElement[1], $style );
1041 $this->openElement =
false;
1045 private function isValidTextId( $id ) {
1046 if ( preg_match(
'/:/', $id ) ) {
1047 return $id !==
'tt:0';
1048 } elseif ( preg_match(
'/^\d+$/', $id ) ) {
1049 return intval( $id ) > 0;
1058class_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.
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)
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
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)