28require_once __DIR__ .
'/BackupDumper.php';
29require_once __DIR__ .
'/../../includes/export/WikiExporter.php';
39use Wikimedia\AtEase\AtEase;
53 private $thisRole =
null;
86 protected $php = [ PHP_BINARY ];
135 parent::__construct();
138This script postprocesses XML dumps from dumpBackup.php to add
139page text which was stubbed out (
using --stub).
141XML input is accepted on stdin.
145 $this->stderr = fopen(
"php://stderr",
"wt" );
147 $this->
addOption(
'stub',
'To load a compressed stub dump instead of stdin. ' .
148 'Specify as --stub=<type>:<file>.',
false,
true );
149 $this->
addOption(
'prefetch',
'Use a prior dump file as a text source, to savepressure on the ' .
150 'database. (Requires the XMLReader extension). Specify as --prefetch=<type>:<file>',
152 $this->
addOption(
'maxtime',
'Write out checkpoint file after this many minutes (writing' .
153 'out complete page, closing xml file properly, and opening new one' .
154 'with header). This option requires the checkpointfile option.',
false,
true );
155 $this->
addOption(
'checkpointfile',
'Use this string for checkpoint filenames,substituting ' .
156 'first pageid written for the first %s (required) and the last pageid written for the ' .
157 'second %s if it exists.',
false,
true,
false,
true );
158 $this->
addOption(
'quiet',
'Don\'t dump status reports to stderr.' );
159 $this->
addOption(
'full',
'Dump all revisions of every page' );
160 $this->
addOption(
'current',
'Base ETA on number of pages in database instead of all revisions' );
161 $this->
addOption(
'spawn',
'Spawn a subprocess for loading text records, optionally specify ' .
162 'php[,mwscript] paths' );
163 $this->
addOption(
'buffersize',
'Buffer size in bytes to use for reading the stub. ' .
164 '(Default: 512 KiB, Minimum: 4 KiB)',
false,
true );
173 parent::finalSetup( $settingsBuilder );
181 private function getBlobStore() {
182 return MediaWikiServices::getInstance()->getBlobStore();
191 parent::processOptions();
193 if ( $this->
hasOption(
'buffersize' ) ) {
194 $this->bufferSize = max( intval( $this->
getOption(
'buffersize' ) ), 4 * 1024 );
199 $this->prefetch =
new BaseDump( $url );
207 $this->maxTimeAllowed = intval( $this->
getOption(
'maxtime' ) ) * 60;
210 if ( $this->
hasOption(
'checkpointfile' ) ) {
211 $this->checkpointFiles = $this->
getOption(
'checkpointfile' );
215 $this->history = WikiExporter::CURRENT;
219 $this->history = WikiExporter::FULL;
226 $this->php = explode(
',', $val, 2 );
245 if ( isset( $this->lb ) ) {
246 $this->lb->closeAll( __METHOD__ );
250 if ( $this->forcedDb !==
null ) {
256 if ( isset( $this->db ) && $this->db->isOpen() ) {
257 throw new MWException(
'DB is set and has not been closed by the Load Balancer' );
267 $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
268 $this->lb = $lbFactory->newMainLB();
269 }
catch ( Exception $e ) {
271 .
" rotating DB failed to obtain new load balancer (" . $e->getMessage() .
")" );
275 $this->db = $this->lb->getMaintenanceConnectionRef(
DB_REPLICA,
'dump' );
276 }
catch ( Exception $e ) {
278 .
" rotating DB failed to obtain new database (" . $e->getMessage() .
")" );
283 parent::initProgress();
290 if ( ini_get(
'display_errors' ) ) {
291 ini_set(
'display_errors',
'stderr' );
303 }
catch ( Exception $e ) {
306 $this->
progress(
"Getting initial DB connection failed (" .
307 $e->getMessage() .
")" );
313 $this->finalOptionCheck();
316 $this->xmlwriterobj =
new XmlDumpWriter( XmlDumpWriter::WRITE_CONTENT, $this->schemaVersion );
318 $input = fopen( $this->input,
"rt" );
321 if ( $this->spawnProc ) {
329 $split = explode(
':', $opt, 2 );
332 if ( count( $split ) === 2 ) {
335 $fileURIs = explode(
';', $param );
337 foreach ( $fileURIs as $URI ) {
343 $newURI =
"compress.zlib://$URI";
346 $newURI =
"compress.bzip2://$URI";
349 $newURI =
"mediawiki.compress.7z://$URI";
354 $newFileURIs[] = $newURI;
356 $val = implode(
';', $newFileURIs );
365 if ( !$this->prefetch ) {
366 parent::showReport();
371 if ( $this->reporting ) {
373 $nowts = microtime(
true );
381 $eta = $this->startTime + $deltaAll / $portion;
383 if ( $this->fetchCount ) {
388 $pageRate = $this->pageCount / $deltaAll;
389 $revRate = $this->
revCount / $deltaAll;
397 if ( $this->fetchCountLast ) {
400 $fetchRatePart =
'-';
402 $pageRatePart = $this->pageCountPart / $deltaPart;
403 $revRatePart = $this->revCountPart / $deltaPart;
405 $fetchRatePart =
'-';
410 $dbDomain = WikiMap::getCurrentWikiDbDomain()->getId();
412 "%s: %s (ID %d) %d pages (%0.1f|%0.1f/sec all|curr), "
413 .
"%d revs (%0.1f|%0.1f/sec all|curr), %0.1f%%|%0.1f%% "
414 .
"prefetched (all|curr), ETA %s [max %d]",
415 $now, $dbDomain, $this->ID, $this->pageCount, $pageRate,
416 $pageRatePart, $this->
revCount, $revRate, $revRatePart,
417 $fetchRate, $fetchRatePart, $etats, $this->maxCount
419 $this->lastTime = $nowts;
426 private function setTimeExceeded() {
427 $this->timeExceeded =
true;
430 private function checkIfTimeExceeded() {
431 if ( $this->maxTimeAllowed
432 && ( $this->lastTime - $this->timeOfCheckpoint > $this->maxTimeAllowed )
440 private function finalOptionCheck() {
441 if ( ( $this->checkpointFiles && !$this->maxTimeAllowed )
442 || ( $this->maxTimeAllowed && !$this->checkpointFiles )
444 throw new MWException(
"Options checkpointfile and maxtime must be specified together.\n" );
446 foreach ( $this->checkpointFiles as $checkpointFile ) {
447 $count = substr_count( $checkpointFile,
"%s" );
449 throw new MWException(
"Option checkpointfile must contain two '%s' "
450 .
"for substitution of first and last pageids, count is $count instead, "
451 .
"file is $checkpointFile.\n" );
455 if ( $this->checkpointFiles ) {
456 $filenameList = (array)$this->egress->getFilenames();
457 if ( count( $filenameList ) != count( $this->checkpointFiles ) ) {
458 throw new MWException(
"One checkpointfile must be specified "
459 .
"for each output option, if maxtime is used.\n" );
471 $this->openElement =
false;
472 $this->atStart =
true;
474 $this->lastName =
"";
475 $this->thisPage =
"";
477 $this->thisRole =
null;
478 $this->thisRevModel =
null;
479 $this->thisRevFormat =
null;
481 $parser = xml_parser_create(
"UTF-8" );
482 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, 0 );
484 xml_set_element_handler(
486 [ $this,
'startElement' ],
487 [ $this,
'endElement' ]
489 xml_set_character_data_handler( $parser, [ $this,
'characterData' ] );
493 if ( $this->checkIfTimeExceeded() ) {
494 $this->setTimeExceeded();
496 $chunk = fread(
$input, $this->bufferSize );
497 if ( !xml_parse( $parser, $chunk, feof(
$input ) ) ) {
498 wfDebug(
"TextDumpPass::readDump encountered XML parsing error" );
500 $byte = xml_get_current_byte_index( $parser );
502 'XML import parse failure',
503 xml_get_current_line_number( $parser ),
504 xml_get_current_column_number( $parser ),
505 $byte . ( $chunk ===
false ?
'' : (
'; "' . substr( $chunk, $byte - $offset, 16 ) .
'"' ) ),
506 xml_error_string( xml_get_error_code( $parser ) ) )->escaped();
508 xml_parser_free( $parser );
512 $offset += strlen( $chunk );
513 }
while ( $chunk !==
false && !feof(
$input ) );
514 if ( $this->maxTimeAllowed ) {
515 $filenameList = (array)$this->egress->getFilenames();
517 if ( file_exists( $filenameList[0] ) ) {
519 # we might have just written the header and footer and had no
520 # pages or revisions written... perhaps they were all deleted
521 # there's no pageID 0 so we use that. the caller is responsible
522 # for deciding what to do with a file containing only the
523 # siteinfo information and the mw tags.
524 if ( !$this->firstPageWritten ) {
525 $firstPageID = str_pad(
'0', 9,
"0", STR_PAD_LEFT );
526 $lastPageID = str_pad(
'0', 9,
"0", STR_PAD_LEFT );
528 $firstPageID = str_pad( $this->firstPageWritten, 9,
"0", STR_PAD_LEFT );
529 $lastPageID = str_pad( $this->lastPageWritten, 9,
"0", STR_PAD_LEFT );
532 $filenameCount = count( $filenameList );
533 for ( $i = 0; $i < $filenameCount; $i++ ) {
534 $checkpointNameFilledIn = sprintf( $this->checkpointFiles[$i], $firstPageID, $lastPageID );
535 $fileinfo = pathinfo( $filenameList[$i] );
536 $newFilenames[] =
$fileinfo[
'dirname'] .
'/' . $checkpointNameFilledIn;
538 $this->egress->closeAndRename( $newFilenames );
541 xml_parser_free( $parser );
555 private function exportTransform( $text, $model, $format =
null ) {
557 $text = MediaWikiServices::getInstance()
558 ->getContentHandlerFactory()
559 ->getContentHandler( $model )
560 ->exportTransform( $text, $format );
562 wfWarn(
"Unable to apply export transformation for content model '$model': " .
566 "Unable to apply export transformation for content model '$model': " .
594 protected function getText( $id, $model =
null, $format =
null, $expSize =
null ) {
595 if ( !$this->isValidTextId( $id ) ) {
596 $msg =
"Skipping bad text id " . $id .
" of revision " . $this->thisRev;
601 $model = $model ?:
null;
602 $prefetchNotTried =
true;
607 static $consecutiveFailedTextRetrievals = 0;
614 $oldConsecutiveFailedTextRetrievals = $consecutiveFailedTextRetrievals;
615 $consecutiveFailedTextRetrievals = 0;
617 while ( $failures < $this->maxFailures ) {
628 if ( $text ===
false && isset( $this->prefetch ) && $prefetchNotTried ) {
629 $prefetchNotTried =
false;
630 $tryIsPrefetch =
true;
631 $text = $this->prefetch->prefetch(
632 (
int)$this->thisPage,
634 trim( $this->thisRole )
637 if ( $text ===
null ) {
641 if ( is_string( $text ) && $model !==
null ) {
647 $text = $this->exportTransform( $text, $model, $format );
651 if ( $text ===
false ) {
653 $tryIsPrefetch =
false;
654 if ( $this->spawn ) {
655 $text = $this->getTextSpawned( $id );
657 $text = $this->getTextDb( $id );
660 if ( $text !==
false && $model !==
null ) {
663 $text = $this->exportTransform( $text, $model, $format );
669 if ( $text !==
false ) {
674 if ( $text ===
false ) {
675 throw new MWException(
"Generic error while obtaining text for id " . $id );
683 if ( $expSize ===
null || strlen( $text ) == $expSize ) {
685 if ( $tryIsPrefetch ) {
686 $this->prefetchCount++;
693 throw new MWException(
"Received text is unplausible for id " . $id );
694 }
catch ( Exception $e ) {
695 $msg =
"getting/checking text " . $id .
" failed (" . $e->getMessage()
696 .
") for revision " . $this->thisRev;
697 if ( $failures + 1 < $this->maxFailures ) {
698 $msg .=
" (Will retry " . ( $this->maxFailures - $failures - 1 ) .
" more times)";
708 if ( !$tryIsPrefetch ) {
712 sleep( $this->failureTimeout );
715 if ( $this->spawn ) {
719 }
catch ( Exception $e ) {
720 $this->
progress(
"Rebooting getText infrastructure failed (" . $e->getMessage() .
")" .
721 " Trying to continue anyways" );
731 $consecutiveFailedTextRetrievals = $oldConsecutiveFailedTextRetrievals + 1;
732 if ( $consecutiveFailedTextRetrievals > $this->maxConsecutiveFailedTextRetrievals ) {
733 throw new MWException(
"Graceful storage failure" );
745 private function getTextDb( $id ) {
746 $store = $this->getBlobStore();
747 $address = ( is_int( $id ) || strpos( $id,
':' ) === false )
748 ? SqlBlobStore::makeAddressFromTextId( (
int)$id )
752 $text = $store->getBlob( $address );
754 $stripped = str_replace(
"\r",
"", $text );
755 $normalized = MediaWikiServices::getInstance()->getContentLanguage()
756 ->normalize( $stripped );
769 private function getTextSpawned( $address ) {
770 AtEase::suppressWarnings();
771 if ( !$this->spawnProc ) {
775 $text = $this->getTextSpawnedOnce( $address );
776 AtEase::restoreWarnings();
784 $wiki = WikiMap::getCurrentWikiId();
785 if ( count( $this->php ) == 2 ) {
786 $mwscriptpath = $this->php[1];
788 $mwscriptpath =
"$IP/../multiversion/MWScript.php";
790 if ( file_exists( $mwscriptpath ) ) {
792 array_map( [ Shell::class,
'escape' ],
797 '--wiki', $wiki ] ) );
800 array_map( [ Shell::class,
'escape' ],
803 "$IP/maintenance/fetchText.php",
804 '--wiki', $wiki ] ) );
807 0 => [
"pipe",
"r" ],
808 1 => [
"pipe",
"w" ],
809 2 => [
"file",
"/dev/null",
"a" ] ];
812 $this->
progress(
"Spawning database subprocess: $cmd" );
813 $this->spawnProc = proc_open( $cmd, $spec, $pipes );
814 if ( !$this->spawnProc ) {
815 $this->
progress(
"Subprocess spawn failed." );
827 private function closeSpawn() {
828 AtEase::suppressWarnings();
829 if ( $this->spawnRead ) {
830 fclose( $this->spawnRead );
832 $this->spawnRead =
null;
833 if ( $this->spawnWrite ) {
834 fclose( $this->spawnWrite );
836 $this->spawnWrite =
null;
837 if ( $this->spawnErr ) {
838 fclose( $this->spawnErr );
840 $this->spawnErr =
false;
841 if ( $this->spawnProc ) {
842 pclose( $this->spawnProc );
844 $this->spawnProc =
false;
845 AtEase::restoreWarnings();
852 private function getTextSpawnedOnce( $address ) {
853 if ( is_int( $address ) || intval( $address ) ) {
854 $address = SqlBlobStore::makeAddressFromTextId( (
int)$address );
857 $ok = fwrite( $this->spawnWrite,
"$address\n" );
863 $ok = fflush( $this->spawnWrite );
871 $newAddress = fgets( $this->spawnRead );
872 if ( $newAddress ===
false ) {
875 $newAddress = trim( $newAddress );
876 if ( strpos( $newAddress,
':' ) ===
false ) {
877 $newAddress = SqlBlobStore::makeAddressFromTextId( intval( $newAddress ) );
880 if ( $newAddress !== $address ) {
884 $len = fgets( $this->spawnRead );
886 if ( $len ===
false ) {
890 $nbytes = intval( $len );
899 while ( $nbytes > strlen( $text ) ) {
900 $buffer = fread( $this->spawnRead, $nbytes - strlen( $text ) );
907 $gotbytes = strlen( $text );
908 if ( $gotbytes != $nbytes ) {
909 $this->
progress(
"Expected $nbytes bytes from database subprocess, got $gotbytes " );
915 $stripped = str_replace(
"\r",
"", $text );
916 $normalized = MediaWikiServices::getInstance()->getContentLanguage()->
917 normalize( $stripped );
923 $this->checkpointJustWritten =
false;
926 $this->lastName = $name;
928 if ( $name ==
'revision' ) {
929 $this->state = $name;
930 $this->egress->writeOpenPage(
null, $this->buffer );
932 } elseif ( $name ==
'page' ) {
933 $this->state = $name;
934 if ( $this->atStart ) {
935 $this->egress->writeOpenStream( $this->buffer );
937 $this->atStart =
false;
939 } elseif ( $name ===
'mediawiki' ) {
940 if ( isset( $attribs[
'version'] ) ) {
941 if ( $attribs[
'version'] !== $this->schemaVersion ) {
942 throw new MWException(
'Mismatching schema version. '
943 .
'Use the --schema-version option to set the output schema version to '
944 .
'the version declared by the stub file, namely ' . $attribs[
'version'] );
949 if ( $name ==
"text" && ( isset( $attribs[
'id'] ) || isset( $attribs[
'location'] ) ) ) {
950 $id = $attribs[
'location'] ?? $attribs[
'id'];
951 $model = trim( $this->thisRevModel );
952 $format = trim( $this->thisRevFormat );
954 $model = $model ===
'' ? null : $model;
955 $format = $format ===
'' ? null : $format;
957 ? (int)$attribs[
'bytes'] :
null;
959 $text = $this->
getText( $id, $model, $format, $expSize );
961 unset( $attribs[
'id'] );
962 unset( $attribs[
'location'] );
963 if ( strlen( $text ) > 0 ) {
964 $attribs[
'xml:space'] =
'preserve';
967 $this->openElement = [ $name, $attribs ];
968 if ( strlen( $text ) > 0 ) {
972 $this->openElement = [ $name, $attribs ];
977 $this->checkpointJustWritten =
false;
979 if ( $this->openElement ) {
982 $this->buffer .=
"</$name>";
985 if ( $name ==
'revision' ) {
986 $this->egress->writeRevision(
null, $this->buffer );
989 $this->thisRole =
null;
990 $this->thisRevModel =
null;
991 $this->thisRevFormat =
null;
992 } elseif ( $name ==
'page' ) {
993 if ( !$this->firstPageWritten ) {
994 $this->firstPageWritten = trim( $this->thisPage );
996 $this->lastPageWritten = trim( $this->thisPage );
997 if ( $this->timeExceeded ) {
998 $this->egress->writeClosePage( $this->buffer );
1001 $this->egress->sink->write(
"\n" );
1003 $this->buffer = $this->xmlwriterobj->closeStream();
1004 $this->egress->writeCloseStream( $this->buffer );
1007 $this->thisPage =
"";
1010 $filenameList = (array)$this->egress->getFilenames();
1012 $firstPageID = str_pad( $this->firstPageWritten, 9,
"0", STR_PAD_LEFT );
1013 $lastPageID = str_pad( $this->lastPageWritten, 9,
"0", STR_PAD_LEFT );
1014 $filenamesCount = count( $filenameList );
1015 for ( $i = 0; $i < $filenamesCount; $i++ ) {
1016 $checkpointNameFilledIn = sprintf( $this->checkpointFiles[$i], $firstPageID, $lastPageID );
1017 $fileinfo = pathinfo( $filenameList[$i] );
1018 $newFilenames[] =
$fileinfo[
'dirname'] .
'/' . $checkpointNameFilledIn;
1020 $this->egress->closeRenameAndReopen( $newFilenames );
1021 $this->buffer = $this->xmlwriterobj->openStream();
1022 $this->timeExceeded =
false;
1024 $this->firstPageWritten =
false;
1025 $this->checkpointJustWritten =
true;
1027 $this->egress->writeClosePage( $this->buffer );
1029 $this->thisPage =
"";
1031 } elseif ( $name ==
'mediawiki' ) {
1032 $this->egress->writeCloseStream( $this->buffer );
1039 if ( $this->lastName ==
"id" ) {
1040 if ( $this->state ==
"revision" ) {
1041 $this->thisRev .= $data;
1042 $this->thisRole = SlotRecord::MAIN;
1043 } elseif ( $this->state ==
"page" ) {
1044 $this->thisPage .= $data;
1046 } elseif ( $this->lastName ==
"model" ) {
1047 $this->thisRevModel .= $data;
1048 } elseif ( $this->lastName ==
"format" ) {
1049 $this->thisRevFormat .= $data;
1050 } elseif ( $this->lastName ==
"content" ) {
1051 $this->thisRole =
"";
1052 $this->thisRevModel =
"";
1053 $this->thisRevFormat =
"";
1054 } elseif ( $this->lastName ==
"role" ) {
1055 $this->thisRole .= $data;
1060 if ( $this->checkpointJustWritten ) {
1061 if ( $data[0] ==
"\n" ) {
1062 $data = substr( $data, 1 );
1064 $this->checkpointJustWritten =
false;
1066 $this->buffer .= htmlspecialchars( $data, ENT_COMPAT );
1070 if ( $this->openElement ) {
1071 $this->buffer .= Xml::element( $this->openElement[0], $this->openElement[1], $style );
1072 $this->openElement =
false;
1076 private function isValidTextId( $id ) {
1077 if ( preg_match(
'/:/', $id ) ) {
1078 return $id !==
'tt:0';
1079 } elseif ( preg_match(
'/^\d+$/', $id ) ) {
1080 return intval( $id ) > 0;
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.
IMaintainableDatabase null $forcedDb
The dependency-injected database to use.
Readahead helper for making large MediaWiki data dumps; reads in a previous XML dump to sequentially ...
output( $out, $channel=null)
Throw some output to the user.
hasOption( $name)
Checks to see if a particular option was set.
addDescription( $text)
Set the description text.
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.
getOption( $name, $default=null)
Get an option, or return the default.
showReport()
Overridden to include prefetch ratio if enabled.
string false $lastPageWritten
endElement( $parser, $name)
clearOpenElement( $style)
string false $firstPageWritten
bool $checkpointJustWritten
startElement( $parser, $name, $attribs)
finalSetup(SettingsBuilder $settingsBuilder=null)
Handle some last-minute setup here.
int $maxConsecutiveFailedTextRetrievals
int $failureTimeout
Seconds to sleep after db failure.
processOptions()
Processes arguments and sets $this->$sink accordingly.
getText( $id, $model=null, $format=null, $expSize=null)
Tries to load revision text.
characterData( $parser, $data)
resource false $spawnProc
initProgress( $history=WikiExporter::FULL)
Initialise starting time and maximum revision count.
execute()
Do the actual work.
dump( $history, $text=WikiExporter::TEXT)
string[] $checkpointFiles
XmlDumpWriter false $xmlwriterobj
int $maxTimeAllowed
when we spend more than maxTimeAllowed seconds on this run, we continue processing until we write out...
IMaintainableDatabase $db
resource null $spawnWrite
rotateDb()
Drop the database connection $this->db and try to get a new one.
Advanced database interface for IDatabase handles that include maintenance methods.