28 require_once __DIR__ .
'/BackupDumper.php';
29 require_once __DIR__ .
'/SevenZipStream.php';
30 require_once __DIR__ .
'/../../includes/export/WikiExporter.php';
112 parent::__construct();
115 This script postprocesses XML dumps from dumpBackup.php to add
116 page text which was stubbed out (
using --stub).
118 XML input is accepted on stdin.
119 XML
output is sent to stdout;
progress reports are sent to stderr.
122 $this->stderr = fopen(
"php://stderr",
"wt" );
124 $this->
addOption(
'stub',
'To load a compressed stub dump instead of stdin. ' .
125 'Specify as --stub=<type>:<file>.',
false,
true );
126 $this->
addOption(
'prefetch',
'Use a prior dump file as a text source, to savepressure on the ' .
127 'database. (Requires the XMLReader extension). Specify as --prefetch=<type>:<file>',
129 $this->
addOption(
'maxtime',
'Write out checkpoint file after this many minutes (writing' .
130 'out complete page, closing xml file properly, and opening new one' .
131 'with header). This option requires the checkpointfile option.',
false,
true );
132 $this->
addOption(
'checkpointfile',
'Use this string for checkpoint filenames,substituting ' .
133 'first pageid written for the first %s (required) and the last pageid written for the ' .
134 'second %s if it exists.',
false,
true,
false,
true );
135 $this->
addOption(
'quiet',
'Don\'t dump status reports to stderr.' );
136 $this->
addOption(
'full',
'Dump all revisions of every page' );
137 $this->
addOption(
'current',
'Base ETA on number of pages in database instead of all revisions' );
138 $this->
addOption(
'spawn',
'Spawn a subprocess for loading text records, optionally specify ' .
139 'php[,mwscript] paths' );
140 $this->
addOption(
'buffersize',
'Buffer size in bytes to use for reading the stub. ' .
141 '(Default: 512KB, Minimum: 4KB)',
false,
true );
153 return MediaWikiServices::getInstance()->getBlobStore();
162 parent::processOptions();
164 if ( $this->
hasOption(
'buffersize' ) ) {
165 $this->bufferSize = max( intval( $this->
getOption(
'buffersize' ) ), 4 * 1024 );
170 $this->prefetch =
new BaseDump( $url );
178 $this->maxTimeAllowed = intval( $this->
getOption(
'maxtime' ) ) * 60;
181 if ( $this->
hasOption(
'checkpointfile' ) ) {
182 $this->checkpointFiles = $this->
getOption(
'checkpointfile' );
197 $this->php = explode(
',', $val, 2 );
216 if ( isset( $this->lb ) ) {
217 $this->lb->closeAll();
221 if ( $this->forcedDb !==
null ) {
227 if ( isset( $this->db ) && $this->db->isOpen() ) {
228 throw new MWException(
'DB is set and has not been closed by the Load Balancer' );
238 $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
239 $this->lb = $lbFactory->newMainLB();
240 }
catch ( Exception $e ) {
242 .
" rotating DB failed to obtain new load balancer (" . $e->getMessage() .
")" );
246 $this->db = $this->lb->getMaintenanceConnectionRef(
DB_REPLICA,
'dump' );
247 }
catch ( Exception $e ) {
249 .
" rotating DB failed to obtain new database (" . $e->getMessage() .
")" );
254 parent::initProgress();
261 if ( ini_get(
'display_errors' ) ) {
262 ini_set(
'display_errors',
'stderr' );
274 }
catch ( Exception $e ) {
277 $this->
progress(
"Getting initial DB connection failed (" .
278 $e->getMessage() .
")" );
289 $input = fopen( $this->input,
"rt" );
292 if ( $this->spawnProc ) {
300 $split = explode(
':', $opt, 2 );
303 if ( count( $split ) === 2 ) {
306 $fileURIs = explode(
';', $param );
308 foreach ( $fileURIs as $URI ) {
314 $newURI =
"compress.zlib://$URI";
317 $newURI =
"compress.bzip2://$URI";
320 $newURI =
"mediawiki.compress.7z://$URI";
325 $newFileURIs[] = $newURI;
327 $val = implode(
';', $newFileURIs );
336 if ( !$this->prefetch ) {
337 parent::showReport();
342 if ( $this->reporting ) {
344 $nowts = microtime(
true );
352 $eta = $this->startTime + $deltaAll / $portion;
354 if ( $this->fetchCount ) {
359 $pageRate = $this->pageCount / $deltaAll;
360 $revRate = $this->
revCount / $deltaAll;
368 if ( $this->fetchCountLast ) {
371 $fetchRatePart =
'-';
373 $pageRatePart = $this->pageCountPart / $deltaPart;
374 $revRatePart = $this->revCountPart / $deltaPart;
376 $fetchRatePart =
'-';
383 "%s: %s (ID %d) %d pages (%0.1f|%0.1f/sec all|curr), "
384 .
"%d revs (%0.1f|%0.1f/sec all|curr), %0.1f%%|%0.1f%% "
385 .
"prefetched (all|curr), ETA %s [max %d]",
386 $now, $dbDomain, $this->ID, $this->pageCount, $pageRate,
387 $pageRatePart, $this->
revCount, $revRate, $revRatePart,
388 $fetchRate, $fetchRatePart, $etats, $this->maxCount
390 $this->lastTime = $nowts;
398 $this->timeExceeded =
true;
402 if ( $this->maxTimeAllowed
403 && ( $this->lastTime - $this->timeOfCheckpoint > $this->maxTimeAllowed )
412 if ( ( $this->checkpointFiles && !$this->maxTimeAllowed )
413 || ( $this->maxTimeAllowed && !$this->checkpointFiles )
415 throw new MWException(
"Options checkpointfile and maxtime must be specified together.\n" );
417 foreach ( $this->checkpointFiles as $checkpointFile ) {
418 $count = substr_count( $checkpointFile,
"%s" );
420 throw new MWException(
"Option checkpointfile must contain two '%s' "
421 .
"for substitution of first and last pageids, count is $count instead, "
422 .
"file is $checkpointFile.\n" );
426 if ( $this->checkpointFiles ) {
427 $filenameList = (array)$this->egress->getFilenames();
428 if ( count( $filenameList ) != count( $this->checkpointFiles ) ) {
429 throw new MWException(
"One checkpointfile must be specified "
430 .
"for each output option, if maxtime is used.\n" );
442 $this->openElement =
false;
443 $this->atStart =
true;
445 $this->lastName =
"";
448 $this->thisRevModel =
null;
449 $this->thisRevFormat =
null;
451 $parser = xml_parser_create(
"UTF-8" );
452 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING,
false );
454 xml_set_element_handler(
456 [ $this,
'startElement' ],
457 [ $this,
'endElement' ]
459 xml_set_character_data_handler( $parser, [ $this,
'characterData' ] );
466 $chunk = fread(
$input, $this->bufferSize );
467 if ( !xml_parse( $parser, $chunk, feof(
$input ) ) ) {
468 wfDebug(
"TextDumpPass::readDump encountered XML parsing error\n" );
470 $byte = xml_get_current_byte_index( $parser );
472 'XML import parse failure',
473 xml_get_current_line_number( $parser ),
474 xml_get_current_column_number( $parser ),
475 $byte . ( is_null( $chunk ) ?
null : (
'; "' . substr( $chunk, $byte - $offset, 16 ) .
'"' ) ),
476 xml_error_string( xml_get_error_code( $parser ) ) )->escaped();
478 xml_parser_free( $parser );
482 $offset += strlen( $chunk );
483 }
while ( $chunk !==
false && !feof(
$input ) );
484 if ( $this->maxTimeAllowed ) {
485 $filenameList = (array)$this->egress->getFilenames();
487 if ( file_exists( $filenameList[0] ) ) {
489 # we might have just written the header and footer and had no
490 # pages or revisions written... perhaps they were all deleted
491 # there's no pageID 0 so we use that. the caller is responsible
492 # for deciding what to do with a file containing only the
493 # siteinfo information and the mw tags.
494 if ( !$this->firstPageWritten ) {
495 $firstPageID = str_pad( 0, 9,
"0", STR_PAD_LEFT );
496 $lastPageID = str_pad( 0, 9,
"0", STR_PAD_LEFT );
498 $firstPageID = str_pad( $this->firstPageWritten, 9,
"0", STR_PAD_LEFT );
499 $lastPageID = str_pad( $this->lastPageWritten, 9,
"0", STR_PAD_LEFT );
502 $filenameCount = count( $filenameList );
503 for ( $i = 0; $i < $filenameCount; $i++ ) {
504 $checkpointNameFilledIn = sprintf( $this->checkpointFiles[$i], $firstPageID, $lastPageID );
505 $fileinfo = pathinfo( $filenameList[$i] );
506 $newFilenames[] =
$fileinfo[
'dirname'] .
'/' . $checkpointNameFilledIn;
508 $this->egress->closeAndRename( $newFilenames );
511 xml_parser_free( $parser );
528 $text = $handler->exportTransform( $text, $format );
532 "Unable to apply export transformation for content model '$model': " .
560 function getText( $id, $model =
null, $format =
null ) {
563 $prefetchNotTried =
true;
568 static $consecutiveFailedTextRetrievals = 0;
575 $oldConsecutiveFailedTextRetrievals = $consecutiveFailedTextRetrievals;
576 $consecutiveFailedTextRetrievals = 0;
580 $row = $this->db->selectRow(
582 [
'rev_content_model',
'rev_content_format' ],
583 [
'rev_id' => $this->thisRev ],
588 $model = $row->rev_content_model;
589 $format = $row->rev_content_format;
593 if ( $model ===
null || $model ===
'' ) {
597 while ( $failures < $this->maxFailures ) {
607 if ( $text ===
false && isset( $this->prefetch ) && $prefetchNotTried ) {
608 $prefetchNotTried =
false;
609 $tryIsPrefetch =
true;
610 $text = $this->prefetch->prefetch( (
int)$this->thisPage, (
int)$this->thisRev );
612 if ( $text ===
null ) {
616 if ( is_string( $text ) && $model !==
false ) {
626 if ( $text ===
false ) {
628 $tryIsPrefetch =
false;
629 if ( $this->spawn ) {
635 if ( $text !==
false && $model !==
false ) {
644 if ( $text !==
false ) {
649 if ( $text ===
false ) {
650 throw new MWException(
"Generic error while obtaining text for id " . $id );
657 $revID = intval( $this->thisRev );
658 if ( !isset( $this->db ) ) {
663 $revLength = strlen( $text );
665 $revLength = $this->db->selectField(
'revision',
'rev_len', [
'rev_id' => $revID ] );
668 if ( strlen( $text ) == $revLength ) {
669 if ( $tryIsPrefetch ) {
670 $this->prefetchCount++;
677 throw new MWException(
"Received text is unplausible for id " . $id );
678 }
catch ( Exception $e ) {
679 $msg =
"getting/checking text " . $id .
" failed (" . $e->getMessage() .
")";
680 if ( $failures + 1 < $this->maxFailures ) {
681 $msg .=
" (Will retry " . ( $this->maxFailures - $failures - 1 ) .
" more times)";
690 if ( !$tryIsPrefetch ) {
694 sleep( $this->failureTimeout );
697 if ( $this->spawn ) {
701 }
catch ( Exception $e ) {
702 $this->
progress(
"Rebooting getText infrastructure failed (" . $e->getMessage() .
")" .
703 " Trying to continue anyways" );
713 $consecutiveFailedTextRetrievals = $oldConsecutiveFailedTextRetrievals + 1;
714 if ( $consecutiveFailedTextRetrievals > $this->maxConsecutiveFailedTextRetrievals ) {
715 throw new MWException(
"Graceful storage failure" );
729 $address = ( is_int( $id ) || strpos( $id,
':' ) === false )
730 ? SqlBlobStore::makeAddressFromTextId( (
int)$id )
734 $text = $store->getBlob( $address );
736 $stripped = str_replace(
"\r",
"", $text );
737 $normalized = MediaWikiServices::getInstance()->getContentLanguage()
738 ->normalize( $stripped );
752 Wikimedia\suppressWarnings();
753 if ( !$this->spawnProc ) {
758 Wikimedia\restoreWarnings();
767 if ( count( $this->php ) == 2 ) {
768 $mwscriptpath = $this->php[1];
770 $mwscriptpath =
"$IP/../multiversion/MWScript.php";
772 if ( file_exists( $mwscriptpath ) ) {
774 array_map( [ Shell::class,
'escape' ],
779 '--wiki', $wiki ] ) );
782 array_map( [ Shell::class,
'escape' ],
785 "$IP/maintenance/fetchText.php",
786 '--wiki', $wiki ] ) );
789 0 => [
"pipe",
"r" ],
790 1 => [
"pipe",
"w" ],
791 2 => [
"file",
"/dev/null",
"a" ] ];
794 $this->
progress(
"Spawning database subprocess: $cmd" );
795 $this->spawnProc = proc_open( $cmd, $spec, $pipes );
796 if ( !$this->spawnProc ) {
797 $this->
progress(
"Subprocess spawn failed." );
810 Wikimedia\suppressWarnings();
811 if ( $this->spawnRead ) {
812 fclose( $this->spawnRead );
814 $this->spawnRead =
null;
815 if ( $this->spawnWrite ) {
816 fclose( $this->spawnWrite );
818 $this->spawnWrite =
null;
819 if ( $this->spawnErr ) {
820 fclose( $this->spawnErr );
822 $this->spawnErr =
false;
823 if ( $this->spawnProc ) {
824 pclose( $this->spawnProc );
826 $this->spawnProc =
false;
827 Wikimedia\restoreWarnings();
835 if ( is_int( $address ) || intval( $address ) ) {
836 $address = SqlBlobStore::makeAddressFromTextId( (
int)$address );
839 $ok = fwrite( $this->spawnWrite,
"$address\n" );
845 $ok = fflush( $this->spawnWrite );
853 $newAddress = fgets( $this->spawnRead );
854 if ( $newAddress ===
false ) {
857 $newAddress = trim( $newAddress );
858 if ( strpos( $newAddress,
':' ) ===
false ) {
859 $newAddress = SqlBlobStore::makeAddressFromTextId( intval( $newAddress ) );
862 if ( $newAddress !== $address ) {
866 $len = fgets( $this->spawnRead );
868 if ( $len ===
false ) {
872 $nbytes = intval( $len );
881 while ( $nbytes > strlen( $text ) ) {
882 $buffer = fread( $this->spawnRead, $nbytes - strlen( $text ) );
889 $gotbytes = strlen( $text );
890 if ( $gotbytes != $nbytes ) {
891 $this->
progress(
"Expected $nbytes bytes from database subprocess, got $gotbytes " );
897 $stripped = str_replace(
"\r",
"", $text );
898 $normalized = MediaWikiServices::getInstance()->getContentLanguage()->
899 normalize( $stripped );
905 $this->checkpointJustWritten =
false;
908 $this->lastName = $name;
910 if ( $name ==
'revision' ) {
911 $this->state = $name;
912 $this->egress->writeOpenPage(
null, $this->buffer );
914 } elseif ( $name ==
'page' ) {
915 $this->state = $name;
916 if ( $this->atStart ) {
917 $this->egress->writeOpenStream( $this->buffer );
919 $this->atStart =
false;
923 if ( $name ==
"text" && isset( $attribs[
'id'] ) ) {
924 $id = $attribs[
'id'];
925 $model = trim( $this->thisRevModel );
926 $format = trim( $this->thisRevFormat );
928 $model = $model ===
'' ? null : $model;
929 $format = $format ===
'' ? null : $format;
931 $text = $this->
getText( $id, $model, $format );
932 $this->openElement = [ $name, [
'xml:space' =>
'preserve' ] ];
933 if ( strlen( $text ) > 0 ) {
937 $this->openElement = [ $name, $attribs ];
942 $this->checkpointJustWritten =
false;
944 if ( $this->openElement ) {
947 $this->buffer .=
"</$name>";
950 if ( $name ==
'revision' ) {
951 $this->egress->writeRevision(
null, $this->buffer );
954 $this->thisRevModel =
null;
955 $this->thisRevFormat =
null;
956 } elseif ( $name ==
'page' ) {
957 if ( !$this->firstPageWritten ) {
958 $this->firstPageWritten = trim( $this->thisPage );
960 $this->lastPageWritten = trim( $this->thisPage );
961 if ( $this->timeExceeded ) {
962 $this->egress->writeClosePage( $this->buffer );
965 $this->egress->sink->write(
"\n" );
967 $this->buffer = $this->xmlwriterobj->closeStream();
968 $this->egress->writeCloseStream( $this->buffer );
971 $this->thisPage =
"";
974 $filenameList = (array)$this->egress->getFilenames();
976 $firstPageID = str_pad( $this->firstPageWritten, 9,
"0", STR_PAD_LEFT );
977 $lastPageID = str_pad( $this->lastPageWritten, 9,
"0", STR_PAD_LEFT );
978 $filenamesCount = count( $filenameList );
979 for ( $i = 0; $i < $filenamesCount; $i++ ) {
980 $checkpointNameFilledIn = sprintf( $this->checkpointFiles[$i], $firstPageID, $lastPageID );
981 $fileinfo = pathinfo( $filenameList[$i] );
982 $newFilenames[] =
$fileinfo[
'dirname'] .
'/' . $checkpointNameFilledIn;
984 $this->egress->closeRenameAndReopen( $newFilenames );
985 $this->buffer = $this->xmlwriterobj->openStream();
986 $this->timeExceeded =
false;
988 $this->firstPageWritten =
false;
989 $this->checkpointJustWritten =
true;
991 $this->egress->writeClosePage( $this->buffer );
993 $this->thisPage =
"";
995 } elseif ( $name ==
'mediawiki' ) {
996 $this->egress->writeCloseStream( $this->buffer );
1003 if ( $this->lastName ==
"id" ) {
1004 if ( $this->state ==
"revision" ) {
1005 $this->thisRev .= $data;
1006 } elseif ( $this->state ==
"page" ) {
1007 $this->thisPage .= $data;
1009 } elseif ( $this->lastName ==
"model" ) {
1010 $this->thisRevModel .= $data;
1011 } elseif ( $this->lastName ==
"format" ) {
1012 $this->thisRevFormat .= $data;
1017 if ( $this->checkpointJustWritten ) {
1018 if ( $data[0] ==
"\n" ) {
1019 $data = substr( $data, 1 );
1021 $this->checkpointJustWritten =
false;
1023 $this->buffer .= htmlspecialchars( $data );
1027 if ( $this->openElement ) {
1028 $this->buffer .=
Xml::element( $this->openElement[0], $this->openElement[1], $style );
1029 $this->openElement =
false;