17require_once __DIR__ .
'/BackupDumper.php';
18require_once __DIR__ .
'/../../includes/Export/WikiExporter.php';
38use Wikimedia\AtEase\AtEase;
39use Wikimedia\Timestamp\ConvertibleTimestamp;
40use Wikimedia\Timestamp\TimestampFormat as TS;
54 private $thisRole =
null;
87 protected $php = [ PHP_BINARY ];
131 parent::__construct();
134This script postprocesses XML dumps from dumpBackup.php to add
135page text which was stubbed out (
using --stub).
137XML input is accepted on stdin.
141 $this->stderr = fopen(
"php://stderr",
"wt" );
143 $this->
addOption(
'stub',
'To load a compressed stub dump instead of stdin. ' .
144 'Specify as --stub=<type>:<file>.',
false,
true );
145 $this->
addOption(
'prefetch',
'Use a prior dump file as a text source, to savepressure on the ' .
146 'database. (Requires the XMLReader extension). Specify as --prefetch=<type>:<file>',
148 $this->
addOption(
'maxtime',
'Write out checkpoint file after this many minutes (writing' .
149 'out complete page, closing xml file properly, and opening new one' .
150 'with header). This option requires the checkpointfile option.',
false,
true );
151 $this->
addOption(
'checkpointfile',
'Use this string for checkpoint filenames,substituting ' .
152 'first pageid written for the first %s (required) and the last pageid written for the ' .
153 'second %s if it exists.',
false,
true,
false,
true );
154 $this->
addOption(
'quiet',
'Don\'t dump status reports to stderr.' );
155 $this->
addOption(
'full',
'Dump all revisions of every page' );
156 $this->
addOption(
'current',
'Base ETA on number of pages in database instead of all revisions' );
157 $this->
addOption(
'spawn',
'Spawn a subprocess for loading text records, optionally specify ' .
158 'php[,mwscript] paths' );
159 $this->
addOption(
'buffersize',
'Buffer size in bytes to use for reading the stub. ' .
160 '(Default: 512 KiB, Minimum: 4 KiB)',
false,
true );
169 parent::finalSetup( $settingsBuilder );
177 private function getBlobStore() {
184 private function getRevisionStore() {
190 $this->
dump( $this->history );
194 parent::processOptions();
196 if ( $this->
hasOption(
'buffersize' ) ) {
197 $this->bufferSize = max( intval( $this->
getOption(
'buffersize' ) ), 4 * 1024 );
210 $this->maxTimeAllowed = intval( $this->
getOption(
'maxtime' ) ) * 60;
213 if ( $this->
hasOption(
'checkpointfile' ) ) {
214 $this->checkpointFiles = $this->
getOption(
'checkpointfile' );
218 $this->history = WikiExporter::CURRENT;
222 $this->history = WikiExporter::FULL;
229 $this->php = explode(
',', $val, 2 );
244 if ( ini_get(
'display_errors' ) ) {
245 ini_set(
'display_errors',
'stderr' );
253 $this->finalOptionCheck();
256 $this->xmlwriterobj =
new XmlDumpWriter( XmlDumpWriter::WRITE_CONTENT, $this->schemaVersion );
258 $input = fopen( $this->input,
"rt" );
261 if ( $this->spawnProc ) {
269 $split = explode(
':', $opt, 2 );
271 $param = $split[1] ??
'';
273 foreach ( explode(
';', $param ) as $uri ) {
274 $newFileURIs[] = match ( $val ) {
275 'gzip' =>
"compress.zlib://$uri",
276 'bzip2' =>
"compress.bzip2://$uri",
277 '7zip' =>
"mediawiki.compress.7z://$uri",
281 return implode(
';', $newFileURIs );
288 if ( !$this->prefetch ) {
289 parent::showReport();
294 if ( $this->reporting ) {
295 $now = ConvertibleTimestamp::now( TS::DB );
296 $nowts = microtime(
true );
297 $deltaAll = $nowts - $this->startTime;
298 $deltaPart = $nowts - $this->lastTime;
299 $this->pageCountPart = $this->pageCount - $this->pageCountLast;
300 $this->revCountPart = $this->revCount - $this->revCountLast;
303 $portion = $this->revCount / $this->maxCount;
304 $eta = $this->startTime + $deltaAll / $portion;
306 if ( $this->fetchCount ) {
307 $fetchRate = 100.0 * $this->prefetchCount / $this->fetchCount;
311 $pageRate = $this->pageCount / $deltaAll;
312 $revRate = $this->revCount / $deltaAll;
320 if ( $this->fetchCountLast ) {
321 $fetchRatePart = 100.0 * $this->prefetchCountLast / $this->fetchCountLast;
323 $fetchRatePart =
'-';
325 $pageRatePart = $this->pageCountPart / $deltaPart;
326 $revRatePart = $this->revCountPart / $deltaPart;
328 $fetchRatePart =
'-';
333 $dbDomain = WikiMap::getCurrentWikiDbDomain()->getId();
334 $this->progress( sprintf(
335 "%s: %s (ID %d) %d pages (%0.1f|%0.1f/sec all|curr), "
336 .
"%d revs (%0.1f|%0.1f/sec all|curr), %0.1f%%|%0.1f%% "
337 .
"prefetched (all|curr), ETA %s [max %d]",
338 $now, $dbDomain, $this->ID, $this->pageCount, $pageRate,
339 $pageRatePart, $this->revCount, $revRate, $revRatePart,
340 $fetchRate, $fetchRatePart, $etats, $this->maxCount
342 $this->lastTime = $nowts;
343 $this->revCountLast = $this->revCount;
344 $this->prefetchCountLast = $this->prefetchCount;
345 $this->fetchCountLast = $this->fetchCount;
349 private function setTimeExceeded() {
350 $this->timeExceeded =
true;
353 private function checkIfTimeExceeded(): bool {
354 if ( $this->maxTimeAllowed
355 && ( $this->lastTime - $this->timeOfCheckpoint > $this->maxTimeAllowed )
363 private function finalOptionCheck() {
364 if ( ( $this->checkpointFiles && !$this->maxTimeAllowed )
365 || ( $this->maxTimeAllowed && !$this->checkpointFiles )
367 throw new RuntimeException(
"Options checkpointfile and maxtime must be specified together.\n" );
369 foreach ( $this->checkpointFiles as $checkpointFile ) {
370 $count = substr_count( $checkpointFile,
"%s" );
371 if ( $count !== 2 ) {
372 throw new RuntimeException(
"Option checkpointfile must contain two '%s' "
373 .
"for substitution of first and last pageids, count is $count instead, "
374 .
"file is $checkpointFile.\n" );
378 if ( $this->checkpointFiles ) {
379 $filenameList = (array)$this->egress->getFilenames();
380 if ( count( $filenameList ) !== count( $this->checkpointFiles ) ) {
381 throw new RuntimeException(
"One checkpointfile must be specified "
382 .
"for each output option, if maxtime is used.\n" );
394 $this->openElement =
false;
395 $this->atStart =
true;
397 $this->lastName =
"";
398 $this->thisPage =
"";
400 $this->thisRole =
null;
401 $this->thisRevModel =
null;
402 $this->thisRevFormat =
null;
404 $parser = xml_parser_create(
"UTF-8" );
405 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, 0 );
407 xml_set_element_handler(
409 $this->startElement( ... ),
410 $this->endElement( ... )
412 xml_set_character_data_handler( $parser, $this->characterData( ... ) );
416 if ( $this->checkIfTimeExceeded() ) {
417 $this->setTimeExceeded();
419 $chunk = fread( $input, $this->bufferSize );
420 if ( !xml_parse( $parser, $chunk, feof( $input ) ) ) {
421 wfDebug(
"TextDumpPass::readDump encountered XML parsing error" );
423 $byte = xml_get_current_byte_index( $parser );
425 'XML import parse failure',
426 xml_get_current_line_number( $parser ),
427 xml_get_current_column_number( $parser ),
428 $byte . ( $chunk ===
false ?
'' : (
'; "' . substr( $chunk, $byte - $offset, 16 ) .
'"' ) ),
429 xml_error_string( xml_get_error_code( $parser ) ) )->escaped();
433 $offset += strlen( $chunk );
434 }
while ( $chunk !==
false && !feof( $input ) );
435 if ( $this->maxTimeAllowed ) {
436 $filenameList = (array)$this->egress->getFilenames();
438 if ( file_exists( $filenameList[0] ) ) {
440 # we might have just written the header and footer and had no
441 # pages or revisions written... perhaps they were all deleted
442 # there's no pageID 0 so we use that. the caller is responsible
443 # for deciding what to do with a file containing only the
444 # siteinfo information and the mw tags.
445 if ( !$this->firstPageWritten ) {
446 $firstPageID = str_pad(
'0', 9,
"0", STR_PAD_LEFT );
447 $lastPageID = str_pad(
'0', 9,
"0", STR_PAD_LEFT );
449 $firstPageID = str_pad( $this->firstPageWritten, 9,
"0", STR_PAD_LEFT );
450 $lastPageID = str_pad( $this->lastPageWritten, 9,
"0", STR_PAD_LEFT );
453 $filenameCount = count( $filenameList );
454 for ( $i = 0; $i < $filenameCount; $i++ ) {
455 $checkpointNameFilledIn = sprintf( $this->checkpointFiles[$i], $firstPageID, $lastPageID );
456 $fileinfo = pathinfo( $filenameList[$i] );
457 $newFilenames[] = $fileinfo[
'dirname'] .
'/' . $checkpointNameFilledIn;
459 $this->egress->closeAndRename( $newFilenames );
475 private function exportTransform( $text, $model, $format =
null ) {
477 $contentHandler = $this->getServiceContainer()
478 ->getContentHandlerFactory()
479 ->getContentHandler( $model );
480 }
catch ( MWUnknownContentModelException $ex ) {
481 wfWarn(
"Unable to apply export transformation for content model '$model': " .
485 "Unable to apply export transformation for content model '$model': " .
491 return $contentHandler->exportTransform( $text, $format );
514 protected function getText( $id, $model =
null, $format =
null, $expSize =
null ) {
515 if ( !$this->isValidTextId( $id ) ) {
516 $msg =
"Skipping bad text id " . $id .
" of revision " . $this->thisRev;
517 $this->progress( $msg );
521 $model = $model ?:
null;
522 $prefetchNotTried =
true;
525 $contentAddress = $id;
528 static $consecutiveFailedTextRetrievals = 0;
535 $oldConsecutiveFailedTextRetrievals = $consecutiveFailedTextRetrievals;
536 $consecutiveFailedTextRetrievals = 0;
538 while ( $failures < $this->maxFailures ) {
549 if ( $text ===
false && $this->prefetch && $prefetchNotTried ) {
550 $prefetchNotTried =
false;
551 $tryIsPrefetch =
true;
552 $text = $this->prefetch->prefetch(
553 (
int)$this->thisPage,
555 trim( $this->thisRole )
558 if ( is_string( $text ) && $model !==
null ) {
564 $text = $this->exportTransform( $text, $model, $format );
568 if ( $text ===
false ) {
570 $tryIsPrefetch =
false;
571 if ( $this->spawn ) {
572 $text = $this->getTextSpawned( $contentAddress );
574 $text = $this->getTextDb( $contentAddress );
577 if ( $text !==
false && $model !==
null ) {
580 $text = $this->exportTransform( $text, $model, $format );
586 if ( $text !==
false ) {
591 if ( $text ===
false ) {
592 throw new RuntimeException(
"Generic error while obtaining text for id " . $contentAddress );
600 if ( $expSize ===
null || strlen( $text ) == $expSize ) {
602 if ( $tryIsPrefetch ) {
603 $this->prefetchCount++;
610 throw new RuntimeException(
"Received text is unplausible for id " . $contentAddress );
611 }
catch ( Exception $e ) {
612 $msg =
"getting/checking text " . $contentAddress .
" failed (" . $e->getMessage()
613 .
") for revision " . $this->thisRev;
614 if ( $failures + 1 < $this->maxFailures ) {
615 $msg .=
" (Will retry " . ( $this->maxFailures - $failures - 1 ) .
" more times)";
617 $this->progress( $msg );
623 if ( $contentAddress === $id && $this->thisRev && trim( $this->thisRole ) ) {
628 $revRecord = $this->getRevisionStore()->getRevisionById( (
int)$this->thisRev );
629 if ( $revRecord !==
null ) {
630 $refreshed = $revRecord->getSlot( trim( $this->thisRole ) )->getAddress();
631 if ( $contentAddress !== $refreshed ) {
633 "Updated content address for rev {$this->thisRev} from "
634 .
"{$contentAddress} to {$refreshed}"
636 $contentAddress = $refreshed;
641 }
catch ( Exception $e ) {
643 "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 AtEase::suppressWarnings();
711 if ( !$this->spawnProc ) {
715 $text = $this->getTextSpawnedOnce( $address );
716 AtEase::restoreWarnings();
724 $wiki = WikiMap::getCurrentWikiId();
725 if ( count( $this->php ) == 2 ) {
726 $mwscriptpath = $this->php[1];
728 $mwscriptpath =
"$IP/../multiversion/MWScript.php";
730 if ( file_exists( $mwscriptpath ) ) {
732 array_map( Shell::escape( ... ),
737 '--wiki', $wiki ] ) );
740 array_map( Shell::escape( ... ),
743 "$IP/maintenance/fetchText.php",
744 '--wiki', $wiki ] ) );
747 0 => [
"pipe",
"r" ],
748 1 => [
"pipe",
"w" ],
749 2 => [
"file",
"/dev/null",
"a" ] ];
752 $this->progress(
"Spawning database subprocess: $cmd" );
753 $this->spawnProc = proc_open( $cmd, $spec, $pipes );
754 if ( !$this->spawnProc ) {
755 $this->progress(
"Subprocess spawn failed." );
767 private function closeSpawn() {
768 AtEase::suppressWarnings();
769 if ( $this->spawnRead ) {
770 fclose( $this->spawnRead );
772 $this->spawnRead =
null;
773 if ( $this->spawnWrite ) {
774 fclose( $this->spawnWrite );
776 $this->spawnWrite =
null;
777 if ( $this->spawnErr ) {
778 fclose( $this->spawnErr );
780 $this->spawnErr =
false;
781 if ( $this->spawnProc ) {
782 proc_close( $this->spawnProc );
784 $this->spawnProc =
false;
785 AtEase::restoreWarnings();
792 private function getTextSpawnedOnce( $address ) {
793 if ( is_int( $address ) || intval( $address ) ) {
794 $address = SqlBlobStore::makeAddressFromTextId( (
int)$address );
797 $ok = fwrite( $this->spawnWrite,
"$address\n" );
803 $ok = fflush( $this->spawnWrite );
811 $newAddress = fgets( $this->spawnRead );
812 if ( $newAddress ===
false ) {
815 $newAddress = trim( $newAddress );
816 if ( !str_contains( $newAddress,
':' ) ) {
817 $newAddress = SqlBlobStore::makeAddressFromTextId( intval( $newAddress ) );
820 if ( $newAddress !== $address ) {
824 $len = fgets( $this->spawnRead );
826 if ( $len ===
false ) {
830 $nbytes = intval( $len );
839 while ( $nbytes > strlen( $text ) ) {
840 $buffer = fread( $this->spawnRead, $nbytes - strlen( $text ) );
841 if ( $buffer ===
false ) {
847 $gotbytes = strlen( $text );
848 if ( $gotbytes != $nbytes ) {
849 $this->progress(
"Expected $nbytes bytes from database subprocess, got $gotbytes " );
855 $stripped = str_replace(
"\r",
"", $text );
856 $normalized = $this->getServiceContainer()->getContentLanguage()->
857 normalize( $stripped );
867 protected function startElement( $parser,
string $name, array $attribs ) {
868 $this->checkpointJustWritten =
false;
870 $this->clearOpenElement(
null );
871 $this->lastName = $name;
873 if ( $name ==
'revision' ) {
874 $this->state = $name;
875 $this->egress->writeOpenPage(
null, $this->buffer );
877 } elseif ( $name ==
'page' ) {
878 $this->state = $name;
879 if ( $this->atStart ) {
880 $this->egress->writeOpenStream( $this->buffer );
882 $this->atStart =
false;
884 } elseif ( $name ===
'mediawiki' ) {
885 if ( isset( $attribs[
'version'] ) ) {
886 if ( $attribs[
'version'] !== $this->schemaVersion ) {
887 throw new RuntimeException(
'Mismatching schema version. '
888 .
'Use the --schema-version option to set the output schema version to '
889 .
'the version declared by the stub file, namely ' . $attribs[
'version'] );
894 if ( $name ==
"text" && ( isset( $attribs[
'id'] ) || isset( $attribs[
'location'] ) ) ) {
895 $id = $attribs[
'location'] ?? $attribs[
'id'];
896 $model = trim( $this->thisRevModel );
897 $format = trim( $this->thisRevFormat );
899 $model = $model ===
'' ? null : $model;
900 $format = $format ===
'' ? null : $format;
902 ? (int)$attribs[
'bytes'] :
null;
904 $text = $this->getText( $id, $model, $format, $expSize );
906 unset( $attribs[
'id'] );
907 unset( $attribs[
'location'] );
908 if ( $text !==
'' ) {
909 $attribs[
'xml:space'] =
'preserve';
912 $this->openElement = [ $name, $attribs ];
913 if ( $text !==
'' ) {
914 $this->characterData( $parser, $text );
917 $this->openElement = [ $name, $attribs ];
926 $this->checkpointJustWritten =
false;
928 if ( $this->openElement ) {
929 $this->clearOpenElement(
"" );
931 $this->buffer .=
"</$name>";
934 if ( $name ==
'revision' ) {
935 $this->egress->writeRevision(
null, $this->buffer );
938 $this->thisRole =
null;
939 $this->thisRevModel =
null;
940 $this->thisRevFormat =
null;
941 } elseif ( $name ==
'page' ) {
942 if ( !$this->firstPageWritten ) {
943 $this->firstPageWritten = trim( $this->thisPage );
945 $this->lastPageWritten = trim( $this->thisPage );
946 if ( $this->timeExceeded ) {
947 $this->egress->writeClosePage( $this->buffer );
950 $this->egress->sink->write(
"\n" );
952 $this->buffer = $this->xmlwriterobj->closeStream();
953 $this->egress->writeCloseStream( $this->buffer );
956 $this->thisPage =
"";
959 $filenameList = (array)$this->egress->getFilenames();
961 $firstPageID = str_pad( $this->firstPageWritten, 9,
"0", STR_PAD_LEFT );
962 $lastPageID = str_pad( $this->lastPageWritten, 9,
"0", STR_PAD_LEFT );
963 $filenamesCount = count( $filenameList );
964 for ( $i = 0; $i < $filenamesCount; $i++ ) {
965 $checkpointNameFilledIn = sprintf( $this->checkpointFiles[$i], $firstPageID, $lastPageID );
966 $fileinfo = pathinfo( $filenameList[$i] );
967 $newFilenames[] = $fileinfo[
'dirname'] .
'/' . $checkpointNameFilledIn;
969 $this->egress->closeRenameAndReopen( $newFilenames );
970 $this->buffer = $this->xmlwriterobj->openStream();
971 $this->timeExceeded =
false;
972 $this->timeOfCheckpoint = $this->lastTime;
973 $this->firstPageWritten =
false;
974 $this->checkpointJustWritten =
true;
976 $this->egress->writeClosePage( $this->buffer );
978 $this->thisPage =
"";
980 } elseif ( $name ==
'mediawiki' ) {
981 $this->egress->writeCloseStream( $this->buffer );
991 $this->clearOpenElement(
null );
992 if ( $this->lastName ==
"id" ) {
993 if ( $this->state ==
"revision" ) {
994 $this->thisRev .= $data;
995 $this->thisRole = SlotRecord::MAIN;
996 } elseif ( $this->state ==
"page" ) {
997 $this->thisPage .= $data;
999 } elseif ( $this->lastName ==
"model" ) {
1000 $this->thisRevModel .= $data;
1001 } elseif ( $this->lastName ==
"format" ) {
1002 $this->thisRevFormat .= $data;
1003 } elseif ( $this->lastName ==
"content" ) {
1004 $this->thisRole =
"";
1005 $this->thisRevModel =
"";
1006 $this->thisRevFormat =
"";
1007 } elseif ( $this->lastName ==
"role" ) {
1008 $this->thisRole .= $data;
1013 if ( $this->checkpointJustWritten ) {
1014 if ( $data[0] ==
"\n" ) {
1015 $data = substr( $data, 1 );
1017 $this->checkpointJustWritten =
false;
1019 $this->buffer .= htmlspecialchars( $data, ENT_COMPAT );
1023 if ( $this->openElement ) {
1024 $this->buffer .= Xml::element( $this->openElement[0], $this->openElement[1], $style );
1025 $this->openElement =
false;
1029 private function isValidTextId(
string $id ): bool {
1030 if ( preg_match(
'/:/', $id ) ) {
1031 return $id !==
'tt:0';
1032 } elseif ( preg_match(
'/^\d+$/', $id ) ) {
1033 return intval( $id ) > 0;
1042class_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(!defined( 'MW_ENTRY_POINT')) global $IP
Environment checks.
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.