17require_once __DIR__ .
'/BackupDumper.php';
18require_once __DIR__ .
'/../../includes/Export/WikiExporter.php';
38use Wikimedia\Timestamp\ConvertibleTimestamp;
39use Wikimedia\Timestamp\TimestampFormat as TS;
53 private $thisRole =
null;
86 protected $php = [ PHP_BINARY ];
130 parent::__construct();
133This script postprocesses XML dumps from dumpBackup.php to add
134page text which was stubbed out (
using --stub).
136XML input is accepted on stdin.
140 $this->stderr = fopen(
"php://stderr",
"wt" );
142 $this->
addOption(
'stub',
'To load a compressed stub dump instead of stdin. ' .
143 'Specify as --stub=<type>:<file>.',
false,
true );
144 $this->
addOption(
'prefetch',
'Use a prior dump file as a text source, to savepressure on the ' .
145 'database. (Requires the XMLReader extension). Specify as --prefetch=<type>:<file>',
147 $this->
addOption(
'maxtime',
'Write out checkpoint file after this many minutes (writing' .
148 'out complete page, closing xml file properly, and opening new one' .
149 'with header). This option requires the checkpointfile option.',
false,
true );
150 $this->
addOption(
'checkpointfile',
'Use this string for checkpoint filenames,substituting ' .
151 'first pageid written for the first %s (required) and the last pageid written for the ' .
152 'second %s if it exists.',
false,
true,
false,
true );
153 $this->
addOption(
'quiet',
'Don\'t dump status reports to stderr.' );
154 $this->
addOption(
'full',
'Dump all revisions of every page' );
155 $this->
addOption(
'current',
'Base ETA on number of pages in database instead of all revisions' );
156 $this->
addOption(
'spawn',
'Spawn a subprocess for loading text records, optionally specify ' .
157 'php[,mwscript] paths' );
158 $this->
addOption(
'buffersize',
'Buffer size in bytes to use for reading the stub. ' .
159 '(Default: 512 KiB, Minimum: 4 KiB)',
false,
true );
168 parent::finalSetup( $settingsBuilder );
176 private function getBlobStore() {
183 private function getRevisionStore() {
189 $this->
dump( $this->history );
193 parent::processOptions();
195 if ( $this->
hasOption(
'buffersize' ) ) {
196 $this->bufferSize = max( intval( $this->
getOption(
'buffersize' ) ), 4 * 1024 );
209 $this->maxTimeAllowed = intval( $this->
getOption(
'maxtime' ) ) * 60;
212 if ( $this->
hasOption(
'checkpointfile' ) ) {
213 $this->checkpointFiles = $this->
getOption(
'checkpointfile' );
217 $this->history = WikiExporter::CURRENT;
221 $this->history = WikiExporter::FULL;
228 $this->php = explode(
',', $val, 2 );
243 if ( ini_get(
'display_errors' ) ) {
244 ini_set(
'display_errors',
'stderr' );
252 $this->finalOptionCheck();
255 $this->xmlwriterobj =
new XmlDumpWriter( XmlDumpWriter::WRITE_CONTENT, $this->schemaVersion );
257 $input = fopen( $this->input,
"rt" );
260 if ( $this->spawnProc ) {
268 $split = explode(
':', $opt, 2 );
270 $param = $split[1] ??
'';
272 foreach ( explode(
';', $param ) as $uri ) {
273 $newFileURIs[] = match ( $val ) {
274 'gzip' =>
"compress.zlib://$uri",
275 'bzip2' =>
"compress.bzip2://$uri",
276 '7zip' =>
"mediawiki.compress.7z://$uri",
280 return implode(
';', $newFileURIs );
287 if ( !$this->prefetch ) {
288 parent::showReport();
293 if ( $this->reporting ) {
294 $now = ConvertibleTimestamp::now( TS::DB );
295 $nowts = microtime(
true );
296 $deltaAll = $nowts - $this->startTime;
297 $deltaPart = $nowts - $this->lastTime;
298 $this->pageCountPart = $this->pageCount - $this->pageCountLast;
299 $this->revCountPart = $this->revCount - $this->revCountLast;
302 $portion = $this->revCount / $this->maxCount;
303 $eta = $this->startTime + $deltaAll / $portion;
305 if ( $this->fetchCount ) {
306 $fetchRate = 100.0 * $this->prefetchCount / $this->fetchCount;
310 $pageRate = $this->pageCount / $deltaAll;
311 $revRate = $this->revCount / $deltaAll;
319 if ( $this->fetchCountLast ) {
320 $fetchRatePart = 100.0 * $this->prefetchCountLast / $this->fetchCountLast;
322 $fetchRatePart =
'-';
324 $pageRatePart = $this->pageCountPart / $deltaPart;
325 $revRatePart = $this->revCountPart / $deltaPart;
327 $fetchRatePart =
'-';
332 $dbDomain = WikiMap::getCurrentWikiDbDomain()->getId();
333 $this->progress( sprintf(
334 "%s: %s (ID %d) %d pages (%0.1f|%0.1f/sec all|curr), "
335 .
"%d revs (%0.1f|%0.1f/sec all|curr), %0.1f%%|%0.1f%% "
336 .
"prefetched (all|curr), ETA %s [max %d]",
337 $now, $dbDomain, $this->ID, $this->pageCount, $pageRate,
338 $pageRatePart, $this->revCount, $revRate, $revRatePart,
339 $fetchRate, $fetchRatePart, $etats, $this->maxCount
341 $this->lastTime = $nowts;
342 $this->revCountLast = $this->revCount;
343 $this->prefetchCountLast = $this->prefetchCount;
344 $this->fetchCountLast = $this->fetchCount;
348 private function setTimeExceeded() {
349 $this->timeExceeded =
true;
352 private function checkIfTimeExceeded(): bool {
353 if ( $this->maxTimeAllowed
354 && ( $this->lastTime - $this->timeOfCheckpoint > $this->maxTimeAllowed )
362 private function finalOptionCheck() {
363 if ( ( $this->checkpointFiles && !$this->maxTimeAllowed )
364 || ( $this->maxTimeAllowed && !$this->checkpointFiles )
366 throw new RuntimeException(
"Options checkpointfile and maxtime must be specified together.\n" );
368 foreach ( $this->checkpointFiles as $checkpointFile ) {
369 $count = substr_count( $checkpointFile,
"%s" );
370 if ( $count !== 2 ) {
371 throw new RuntimeException(
"Option checkpointfile must contain two '%s' "
372 .
"for substitution of first and last pageids, count is $count instead, "
373 .
"file is $checkpointFile.\n" );
377 if ( $this->checkpointFiles ) {
378 $filenameList = (array)$this->egress->getFilenames();
379 if ( count( $filenameList ) !== count( $this->checkpointFiles ) ) {
380 throw new RuntimeException(
"One checkpointfile must be specified "
381 .
"for each output option, if maxtime is used.\n" );
393 $this->openElement =
false;
394 $this->atStart =
true;
396 $this->lastName =
"";
397 $this->thisPage =
"";
399 $this->thisRole =
null;
400 $this->thisRevModel =
null;
401 $this->thisRevFormat =
null;
403 $parser = xml_parser_create(
"UTF-8" );
404 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, 0 );
406 xml_set_element_handler(
408 $this->startElement( ... ),
409 $this->endElement( ... )
411 xml_set_character_data_handler( $parser, $this->characterData( ... ) );
415 if ( $this->checkIfTimeExceeded() ) {
416 $this->setTimeExceeded();
418 $chunk = fread( $input, $this->bufferSize );
419 if ( !xml_parse( $parser, $chunk, feof( $input ) ) ) {
420 wfDebug(
"TextDumpPass::readDump encountered XML parsing error" );
422 $byte = xml_get_current_byte_index( $parser );
424 'XML import parse failure',
425 xml_get_current_line_number( $parser ),
426 xml_get_current_column_number( $parser ),
427 $byte . ( $chunk ===
false ?
'' : (
'; "' . substr( $chunk, $byte - $offset, 16 ) .
'"' ) ),
428 xml_error_string( xml_get_error_code( $parser ) ) )->escaped();
432 $offset += strlen( $chunk );
433 }
while ( $chunk !==
false && !feof( $input ) );
434 if ( $this->maxTimeAllowed ) {
435 $filenameList = (array)$this->egress->getFilenames();
437 if ( file_exists( $filenameList[0] ) ) {
439 # we might have just written the header and footer and had no
440 # pages or revisions written... perhaps they were all deleted
441 # there's no pageID 0 so we use that. the caller is responsible
442 # for deciding what to do with a file containing only the
443 # siteinfo information and the mw tags.
444 if ( !$this->firstPageWritten ) {
445 $firstPageID = str_pad(
'0', 9,
"0", STR_PAD_LEFT );
446 $lastPageID = str_pad(
'0', 9,
"0", STR_PAD_LEFT );
448 $firstPageID = str_pad( $this->firstPageWritten, 9,
"0", STR_PAD_LEFT );
449 $lastPageID = str_pad( $this->lastPageWritten, 9,
"0", STR_PAD_LEFT );
452 $filenameCount = count( $filenameList );
453 for ( $i = 0; $i < $filenameCount; $i++ ) {
454 $checkpointNameFilledIn = sprintf( $this->checkpointFiles[$i], $firstPageID, $lastPageID );
455 $fileinfo = pathinfo( $filenameList[$i] );
456 $newFilenames[] = $fileinfo[
'dirname'] .
'/' . $checkpointNameFilledIn;
458 $this->egress->closeAndRename( $newFilenames );
474 private function exportTransform( $text, $model, $format =
null ) {
476 $contentHandler = $this->getServiceContainer()
477 ->getContentHandlerFactory()
478 ->getContentHandler( $model );
479 }
catch ( UnknownContentModelException $ex ) {
480 wfWarn(
"Unable to apply export transformation for content model '$model': " .
484 "Unable to apply export transformation for content model '$model': " .
490 return $contentHandler->exportTransform( $text, $format );
513 protected function getText( $id, $model =
null, $format =
null, $expSize =
null ) {
514 if ( !$this->isValidTextId( $id ) ) {
515 $msg =
"Skipping bad text id " . $id .
" of revision " . $this->thisRev;
516 $this->progress( $msg );
520 $model = $model ?:
null;
521 $prefetchNotTried =
true;
524 $contentAddress = $id;
527 static $consecutiveFailedTextRetrievals = 0;
534 $oldConsecutiveFailedTextRetrievals = $consecutiveFailedTextRetrievals;
535 $consecutiveFailedTextRetrievals = 0;
537 while ( $failures < $this->maxFailures ) {
548 if ( $text ===
false && $this->prefetch && $prefetchNotTried ) {
549 $prefetchNotTried =
false;
550 $tryIsPrefetch =
true;
551 $text = $this->prefetch->prefetch(
552 (
int)$this->thisPage,
554 trim( $this->thisRole )
557 if ( is_string( $text ) && $model !==
null ) {
563 $text = $this->exportTransform( $text, $model, $format );
567 if ( $text ===
false ) {
569 $tryIsPrefetch =
false;
570 if ( $this->spawn ) {
571 $text = $this->getTextSpawned( $contentAddress );
573 $text = $this->getTextDb( $contentAddress );
576 if ( $text !==
false && $model !==
null ) {
579 $text = $this->exportTransform( $text, $model, $format );
585 if ( $text !==
false ) {
590 if ( $text ===
false ) {
591 throw new RuntimeException(
"Generic error while obtaining text for id " . $contentAddress );
599 if ( $expSize ===
null || strlen( $text ) == $expSize ) {
601 if ( $tryIsPrefetch ) {
602 $this->prefetchCount++;
609 throw new RuntimeException(
"Received text is unplausible for id " . $contentAddress );
610 }
catch ( Exception $e ) {
611 $msg =
"getting/checking text " . $contentAddress .
" failed (" . $e->getMessage()
612 .
") for revision " . $this->thisRev;
613 if ( $failures + 1 < $this->maxFailures ) {
614 $msg .=
" (Will retry " . ( $this->maxFailures - $failures - 1 ) .
" more times)";
616 $this->progress( $msg );
622 if ( $contentAddress === $id && $this->thisRev && trim( $this->thisRole ) ) {
627 $revRecord = $this->getRevisionStore()->getRevisionById( (
int)$this->thisRev );
628 if ( $revRecord !==
null ) {
629 $refreshed = $revRecord->getSlot( trim( $this->thisRole ) )->getAddress();
630 if ( $contentAddress !== $refreshed ) {
632 "Updated content address for rev {$this->thisRev} from "
633 .
"{$contentAddress} to {$refreshed}"
635 $contentAddress = $refreshed;
640 }
catch ( Exception $e ) {
642 "refreshing content address for revision {$this->thisRev} failed ({$e->getMessage()})"
649 if ( !$tryIsPrefetch ) {
653 sleep( $this->failureTimeout );
655 if ( $this->spawn ) {
659 }
catch ( Exception $e ) {
660 $this->progress(
"Rebooting getText infrastructure failed (" . $e->getMessage() .
")" .
661 " Trying to continue anyways" );
671 $consecutiveFailedTextRetrievals = $oldConsecutiveFailedTextRetrievals + 1;
672 if ( $consecutiveFailedTextRetrievals > $this->maxConsecutiveFailedTextRetrievals ) {
673 throw new MWException(
"Graceful storage failure" );
685 private function getTextDb( $id ) {
686 $store = $this->getBlobStore();
687 $address = ( is_int( $id ) || !str_contains( $id,
':' ) )
688 ? SqlBlobStore::makeAddressFromTextId( (
int)$id )
692 $text = $store->getBlob( $address );
694 $stripped = str_replace(
"\r",
"", $text );
695 $normalized = $this->getServiceContainer()->getContentLanguage()
696 ->normalize( $stripped );
699 }
catch ( BlobAccessException ) {
709 private function getTextSpawned( $address ) {
710 if ( !$this->spawnProc ) {
716 return @$this->getTextSpawnedOnce( $address );
720 $wiki =
WikiMap::getCurrentWikiId();
721 if ( count( $this->php ) == 2 ) {
722 $mwscriptpath = $this->php[1];
727 $mwscriptpath = MW_INSTALL_PATH .
'/../multiversion/MWScript.php';
729 if ( file_exists( $mwscriptpath ) ) {
731 array_map( Shell::escape( ... ),
736 '--wiki', $wiki ] ) );
739 array_map( Shell::escape( ... ),
742 MW_INSTALL_PATH .
'/maintenance/fetchText.php',
743 '--wiki', $wiki ] ) );
746 0 => [
"pipe",
"r" ],
747 1 => [
"pipe",
"w" ],
748 2 => [
"file",
"/dev/null",
"a" ] ];
751 $this->progress(
"Spawning database subprocess: $cmd" );
752 $this->spawnProc = proc_open( $cmd, $spec, $pipes );
753 if ( !$this->spawnProc ) {
754 $this->progress(
"Subprocess spawn failed." );
766 private function closeSpawn() {
767 if ( $this->spawnRead ) {
769 @fclose( $this->spawnRead );
771 $this->spawnRead =
null;
772 if ( $this->spawnWrite ) {
774 @fclose( $this->spawnWrite );
776 $this->spawnWrite =
null;
777 if ( $this->spawnErr ) {
779 @fclose( $this->spawnErr );
781 $this->spawnErr =
false;
782 if ( $this->spawnProc ) {
784 @proc_close( $this->spawnProc );
786 $this->spawnProc =
false;
793 private function getTextSpawnedOnce( $address ) {
794 if ( is_int( $address ) || intval( $address ) ) {
795 $address = SqlBlobStore::makeAddressFromTextId( (
int)$address );
798 $ok = fwrite( $this->spawnWrite,
"$address\n" );
804 $ok = fflush( $this->spawnWrite );
812 $newAddress = fgets( $this->spawnRead );
813 if ( $newAddress ===
false ) {
816 $newAddress = trim( $newAddress );
817 if ( !str_contains( $newAddress,
':' ) ) {
818 $newAddress = SqlBlobStore::makeAddressFromTextId( intval( $newAddress ) );
821 if ( $newAddress !== $address ) {
825 $len = fgets( $this->spawnRead );
827 if ( $len ===
false ) {
831 $nbytes = intval( $len );
840 while ( $nbytes > strlen( $text ) ) {
841 $buffer = fread( $this->spawnRead, $nbytes - strlen( $text ) );
842 if ( $buffer ===
false ) {
848 $gotbytes = strlen( $text );
849 if ( $gotbytes != $nbytes ) {
850 $this->progress(
"Expected $nbytes bytes from database subprocess, got $gotbytes " );
856 $stripped = str_replace(
"\r",
"", $text );
857 $normalized = $this->getServiceContainer()->getContentLanguage()->
858 normalize( $stripped );
868 protected function startElement( $parser,
string $name, array $attribs ) {
869 $this->checkpointJustWritten =
false;
871 $this->clearOpenElement(
null );
872 $this->lastName = $name;
874 if ( $name ==
'revision' ) {
875 $this->state = $name;
876 $this->egress->writeOpenPage(
null, $this->buffer );
878 } elseif ( $name ==
'page' ) {
879 $this->state = $name;
880 if ( $this->atStart ) {
881 $this->egress->writeOpenStream( $this->buffer );
883 $this->atStart =
false;
885 } elseif ( $name ===
'mediawiki' ) {
886 if ( isset( $attribs[
'version'] ) ) {
887 if ( $attribs[
'version'] !== $this->schemaVersion ) {
888 throw new RuntimeException(
'Mismatching schema version. '
889 .
'Use the --schema-version option to set the output schema version to '
890 .
'the version declared by the stub file, namely ' . $attribs[
'version'] );
895 if ( $name ==
"text" && ( isset( $attribs[
'id'] ) || isset( $attribs[
'location'] ) ) ) {
896 $id = $attribs[
'location'] ?? $attribs[
'id'];
897 $model = trim( $this->thisRevModel );
898 $format = trim( $this->thisRevFormat );
900 $model = $model ===
'' ? null : $model;
901 $format = $format ===
'' ? null : $format;
903 ? (int)$attribs[
'bytes'] :
null;
905 $text = $this->getText( $id, $model, $format, $expSize );
907 unset( $attribs[
'id'] );
908 unset( $attribs[
'location'] );
909 if ( $text !==
'' ) {
910 $attribs[
'xml:space'] =
'preserve';
913 $this->openElement = [ $name, $attribs ];
914 if ( $text !==
'' ) {
915 $this->characterData( $parser, $text );
918 $this->openElement = [ $name, $attribs ];
927 $this->checkpointJustWritten =
false;
929 if ( $this->openElement ) {
930 $this->clearOpenElement(
"" );
932 $this->buffer .=
"</$name>";
935 if ( $name ==
'revision' ) {
936 $this->egress->writeRevision(
null, $this->buffer );
939 $this->thisRole =
null;
940 $this->thisRevModel =
null;
941 $this->thisRevFormat =
null;
942 } elseif ( $name ==
'page' ) {
943 if ( !$this->firstPageWritten ) {
944 $this->firstPageWritten = trim( $this->thisPage );
946 $this->lastPageWritten = trim( $this->thisPage );
947 if ( $this->timeExceeded ) {
948 $this->egress->writeClosePage( $this->buffer );
951 $this->egress->sink->write(
"\n" );
953 $this->buffer = $this->xmlwriterobj->closeStream();
954 $this->egress->writeCloseStream( $this->buffer );
957 $this->thisPage =
"";
960 $filenameList = (array)$this->egress->getFilenames();
962 $firstPageID = str_pad( $this->firstPageWritten, 9,
"0", STR_PAD_LEFT );
963 $lastPageID = str_pad( $this->lastPageWritten, 9,
"0", STR_PAD_LEFT );
964 $filenamesCount = count( $filenameList );
965 for ( $i = 0; $i < $filenamesCount; $i++ ) {
966 $checkpointNameFilledIn = sprintf( $this->checkpointFiles[$i], $firstPageID, $lastPageID );
967 $fileinfo = pathinfo( $filenameList[$i] );
968 $newFilenames[] = $fileinfo[
'dirname'] .
'/' . $checkpointNameFilledIn;
970 $this->egress->closeRenameAndReopen( $newFilenames );
971 $this->buffer = $this->xmlwriterobj->openStream();
972 $this->timeExceeded =
false;
973 $this->timeOfCheckpoint = $this->lastTime;
974 $this->firstPageWritten =
false;
975 $this->checkpointJustWritten =
true;
977 $this->egress->writeClosePage( $this->buffer );
979 $this->thisPage =
"";
981 } elseif ( $name ==
'mediawiki' ) {
982 $this->egress->writeCloseStream( $this->buffer );
992 $this->clearOpenElement(
null );
993 if ( $this->lastName ==
"id" ) {
994 if ( $this->state ==
"revision" ) {
995 $this->thisRev .= $data;
996 $this->thisRole = SlotRecord::MAIN;
997 } elseif ( $this->state ==
"page" ) {
998 $this->thisPage .= $data;
1000 } elseif ( $this->lastName ==
"model" ) {
1001 $this->thisRevModel .= $data;
1002 } elseif ( $this->lastName ==
"format" ) {
1003 $this->thisRevFormat .= $data;
1004 } elseif ( $this->lastName ==
"content" ) {
1005 $this->thisRole =
"";
1006 $this->thisRevModel =
"";
1007 $this->thisRevFormat =
"";
1008 } elseif ( $this->lastName ==
"role" ) {
1009 $this->thisRole .= $data;
1014 if ( $this->checkpointJustWritten ) {
1015 if ( $data[0] ==
"\n" ) {
1016 $data = substr( $data, 1 );
1018 $this->checkpointJustWritten =
false;
1020 $this->buffer .= htmlspecialchars( $data, ENT_COMPAT );
1024 if ( $this->openElement ) {
1025 $this->buffer .= Xml::element( $this->openElement[0], $this->openElement[1], $style );
1026 $this->openElement =
false;
1030 private function isValidTextId(
string $id ): bool {
1031 if ( preg_match(
'/:/', $id ) ) {
1032 return $id !==
'tt:0';
1033 } elseif ( preg_match(
'/^\d+$/', $id ) ) {
1034 return intval( $id ) > 0;
1043class_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('MW_SETUP_CALLBACK'))
Exception thrown when an unregistered content model is requested.
report(bool $final=false)
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
endElement( $parser, string $name)
dump( $history, $text=WikiExporter::TEXT)
finalSetup(SettingsBuilder $settingsBuilder)
Handle some last-minute setup here.
processOptions()
Processes arguments and sets $this->$sink accordingly.
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.We'll make ETA calculations based on progress,...
clearOpenElement(?string $style)
bool $checkpointJustWritten
execute()
Do the actual work.
startElement( $parser, string $name, array $attribs)
string false $lastPageWritten
XmlDumpWriter false $xmlwriterobj
characterData( $parser, string $data)
string[] $checkpointFiles
resource null $spawnWrite
int $maxTimeAllowed
when we spend more than maxTimeAllowed seconds on this run, we continue processing until we write out...
processFileOpt(string $opt)
int $failureTimeout
Seconds to sleep after db failure.
Update the CREDITS list by merging in the list of git commit authors.