3 * BackupDumper that postprocesses XML dumps from dumpBackup.php to add page text
5 * Copyright (C) 2005 Brion Vibber <brion@pobox.com>
6 * https://www.mediawiki.org/
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
24 * @ingroup Maintenance
27 require_once __DIR__ . '/backup.inc';
30 * @ingroup Maintenance
32 class TextPassDumper extends BackupDumper {
33 public $prefetch = null;
35 // when we spend more than maxTimeAllowed seconds on this run, we continue
36 // processing until we write out the next complete page, then save output file(s),
37 // rename it/them and open new one(s)
38 public $maxTimeAllowed = 0; // 0 = no limit
40 protected $input = "php://stdin";
41 protected $history = WikiExporter::FULL;
42 protected $fetchCount = 0;
43 protected $prefetchCount = 0;
44 protected $prefetchCountLast = 0;
45 protected $fetchCountLast = 0;
47 protected $maxFailures = 5;
48 protected $maxConsecutiveFailedTextRetrievals = 200;
49 protected $failureTimeout = 5; // Seconds to sleep after db failure
51 protected $php = "php";
52 protected $spawn = false;
57 protected $spawnProc = false;
62 protected $spawnWrite = false;
67 protected $spawnRead = false;
72 protected $spawnErr = false;
74 protected $xmlwriterobj = false;
76 protected $timeExceeded = false;
77 protected $firstPageWritten = false;
78 protected $lastPageWritten = false;
79 protected $checkpointJustWritten = false;
80 protected $checkpointFiles = array();
88 * Drop the database connection $this->db and try to get a new one.
90 * This function tries to get a /different/ connection if this is
91 * possible. Hence, (if this is possible) it switches to a different
92 * failover upon each call.
94 * This function resets $this->lb and closes all connections on it.
99 // Cleaning up old connections
100 if ( isset( $this->lb ) ) {
101 $this->lb->closeAll();
105 if ( $this->forcedDb !== null ) {
106 $this->db = $this->forcedDb;
111 if ( isset( $this->db ) && $this->db->isOpen() ) {
112 throw new MWException( 'DB is set and has not been closed by the Load Balancer' );
117 // Trying to set up new connection.
118 // We do /not/ retry upon failure, but delegate to encapsulating logic, to avoid
119 // individually retrying at different layers of code.
121 // 1. The LoadBalancer.
123 $this->lb = wfGetLBFactory()->newMainLB();
124 } catch ( Exception $e ) {
125 throw new MWException( __METHOD__
126 . " rotating DB failed to obtain new load balancer (" . $e->getMessage() . ")" );
129 // 2. The Connection, through the load balancer.
131 $this->db = $this->lb->getConnection( DB_SLAVE, 'dump' );
132 } catch ( Exception $e ) {
133 throw new MWException( __METHOD__
134 . " rotating DB failed to obtain new database (" . $e->getMessage() . ")" );
138 function initProgress( $history = WikiExporter::FULL ) {
139 parent::initProgress();
140 $this->timeOfCheckpoint = $this->startTime;
143 function dump( $history, $text = WikiExporter::TEXT ) {
144 // Notice messages will foul up your XML output even if they're
145 // relatively harmless.
146 if ( ini_get( 'display_errors' ) ) {
147 ini_set( 'display_errors', 'stderr' );
150 $this->initProgress( $this->history );
152 // We are trying to get an initial database connection to avoid that the
153 // first try of this request's first call to getText fails. However, if
154 // obtaining a good DB connection fails it's not a serious issue, as
155 // getText does retry upon failure and can start without having a working
159 } catch ( Exception $e ) {
160 // We do not even count this as failure. Just let eventual
162 $this->progress( "Getting initial DB connection failed (" .
163 $e->getMessage() . ")" );
166 $this->egress = new ExportProgressFilter( $this->sink, $this );
168 // it would be nice to do it in the constructor, oh well. need egress set
169 $this->finalOptionCheck();
171 // we only want this so we know how to close a stream :-P
172 $this->xmlwriterobj = new XmlDumpWriter();
174 $input = fopen( $this->input, "rt" );
175 $this->readDump( $input );
177 if ( $this->spawnProc ) {
181 $this->report( true );
184 function processOption( $opt, $val, $param ) {
186 $url = $this->processFileOpt( $val, $param );
190 require_once "$IP/maintenance/backupPrefetch.inc";
191 $this->prefetch = new BaseDump( $url );
197 $this->maxTimeAllowed = intval( $val ) * 60;
199 case 'checkpointfile':
200 $this->checkpointFiles[] = $val;
203 $this->history = WikiExporter::CURRENT;
206 $this->history = WikiExporter::FULL;
217 function processFileOpt( $val, $param ) {
218 $fileURIs = explode( ';', $param );
219 foreach ( $fileURIs as $URI ) {
225 $newURI = "compress.zlib://$URI";
228 $newURI = "compress.bzip2://$URI";
231 $newURI = "mediawiki.compress.7z://$URI";
236 $newFileURIs[] = $newURI;
238 $val = implode( ';', $newFileURIs );
244 * Overridden to include prefetch ratio if enabled.
246 function showReport() {
247 if ( !$this->prefetch ) {
248 parent::showReport();
253 if ( $this->reporting ) {
254 $now = wfTimestamp( TS_DB );
255 $nowts = microtime( true );
256 $deltaAll = $nowts - $this->startTime;
257 $deltaPart = $nowts - $this->lastTime;
258 $this->pageCountPart = $this->pageCount - $this->pageCountLast;
259 $this->revCountPart = $this->revCount - $this->revCountLast;
262 $portion = $this->revCount / $this->maxCount;
263 $eta = $this->startTime + $deltaAll / $portion;
264 $etats = wfTimestamp( TS_DB, intval( $eta ) );
265 if ( $this->fetchCount ) {
266 $fetchRate = 100.0 * $this->prefetchCount / $this->fetchCount;
270 $pageRate = $this->pageCount / $deltaAll;
271 $revRate = $this->revCount / $deltaAll;
279 if ( $this->fetchCountLast ) {
280 $fetchRatePart = 100.0 * $this->prefetchCountLast / $this->fetchCountLast;
282 $fetchRatePart = '-';
284 $pageRatePart = $this->pageCountPart / $deltaPart;
285 $revRatePart = $this->revCountPart / $deltaPart;
287 $fetchRatePart = '-';
291 $this->progress( sprintf(
292 "%s: %s (ID %d) %d pages (%0.1f|%0.1f/sec all|curr), "
293 . "%d revs (%0.1f|%0.1f/sec all|curr), %0.1f%%|%0.1f%% "
294 . "prefetched (all|curr), ETA %s [max %d]",
295 $now, wfWikiID(), $this->ID, $this->pageCount, $pageRate,
296 $pageRatePart, $this->revCount, $revRate, $revRatePart,
297 $fetchRate, $fetchRatePart, $etats, $this->maxCount
299 $this->lastTime = $nowts;
300 $this->revCountLast = $this->revCount;
301 $this->prefetchCountLast = $this->prefetchCount;
302 $this->fetchCountLast = $this->fetchCount;
306 function setTimeExceeded() {
307 $this->timeExceeded = true;
310 function checkIfTimeExceeded() {
311 if ( $this->maxTimeAllowed
312 && ( $this->lastTime - $this->timeOfCheckpoint > $this->maxTimeAllowed )
320 function finalOptionCheck() {
321 if ( ( $this->checkpointFiles && !$this->maxTimeAllowed )
322 || ( $this->maxTimeAllowed && !$this->checkpointFiles )
324 throw new MWException( "Options checkpointfile and maxtime must be specified together.\n" );
326 foreach ( $this->checkpointFiles as $checkpointFile ) {
327 $count = substr_count( $checkpointFile, "%s" );
329 throw new MWException( "Option checkpointfile must contain two '%s' "
330 . "for substitution of first and last pageids, count is $count instead, "
331 . "file is $checkpointFile.\n" );
335 if ( $this->checkpointFiles ) {
336 $filenameList = (array)$this->egress->getFilenames();
337 if ( count( $filenameList ) != count( $this->checkpointFiles ) ) {
338 throw new MWException( "One checkpointfile must be specified "
339 . "for each output option, if maxtime is used.\n" );
345 * @throws MWException Failure to parse XML input
348 function readDump( $input ) {
350 $this->openElement = false;
351 $this->atStart = true;
353 $this->lastName = "";
357 $parser = xml_parser_create( "UTF-8" );
358 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
360 xml_set_element_handler(
362 array( &$this, 'startElement' ),
363 array( &$this, 'endElement' )
365 xml_set_character_data_handler( $parser, array( &$this, 'characterData' ) );
367 $offset = 0; // for context extraction on error reporting
368 $bufferSize = 512 * 1024;
370 if ( $this->checkIfTimeExceeded() ) {
371 $this->setTimeExceeded();
373 $chunk = fread( $input, $bufferSize );
374 if ( !xml_parse( $parser, $chunk, feof( $input ) ) ) {
375 wfDebug( "TextDumpPass::readDump encountered XML parsing error\n" );
377 $byte = xml_get_current_byte_index( $parser );
378 $msg = wfMessage( 'xml-error-string',
379 'XML import parse failure',
380 xml_get_current_line_number( $parser ),
381 xml_get_current_column_number( $parser ),
382 $byte . ( is_null( $chunk ) ? null : ( '; "' . substr( $chunk, $byte - $offset, 16 ) . '"' ) ),
383 xml_error_string( xml_get_error_code( $parser ) ) )->escaped();
385 xml_parser_free( $parser );
387 throw new MWException( $msg );
389 $offset += strlen( $chunk );
390 } while ( $chunk !== false && !feof( $input ) );
391 if ( $this->maxTimeAllowed ) {
392 $filenameList = (array)$this->egress->getFilenames();
393 // we wrote some stuff after last checkpoint that needs renamed
394 if ( file_exists( $filenameList[0] ) ) {
395 $newFilenames = array();
396 # we might have just written the header and footer and had no
397 # pages or revisions written... perhaps they were all deleted
398 # there's no pageID 0 so we use that. the caller is responsible
399 # for deciding what to do with a file containing only the
400 # siteinfo information and the mw tags.
401 if ( !$this->firstPageWritten ) {
402 $firstPageID = str_pad( 0, 9, "0", STR_PAD_LEFT );
403 $lastPageID = str_pad( 0, 9, "0", STR_PAD_LEFT );
405 $firstPageID = str_pad( $this->firstPageWritten, 9, "0", STR_PAD_LEFT );
406 $lastPageID = str_pad( $this->lastPageWritten, 9, "0", STR_PAD_LEFT );
409 $filenameCount = count( $filenameList );
410 for ( $i = 0; $i < $filenameCount; $i++ ) {
411 $checkpointNameFilledIn = sprintf( $this->checkpointFiles[$i], $firstPageID, $lastPageID );
412 $fileinfo = pathinfo( $filenameList[$i] );
413 $newFilenames[] = $fileinfo['dirname'] . '/' . $checkpointNameFilledIn;
415 $this->egress->closeAndRename( $newFilenames );
418 xml_parser_free( $parser );
424 * Tries to get the revision text for a revision id.
426 * Upon errors, retries (Up to $this->maxFailures tries each call).
427 * If still no good revision get could be found even after this retrying, "" is returned.
428 * If no good revision text could be returned for
429 * $this->maxConsecutiveFailedTextRetrievals consecutive calls to getText, MWException
432 * @param string $id The revision id to get the text for
434 * @return string The revision text for $id, or ""
435 * @throws MWException
437 function getText( $id ) {
438 global $wgContentHandlerUseDB;
440 $prefetchNotTried = true; // Whether or not we already tried to get the text via prefetch.
441 $text = false; // The candidate for a good text. false if no proper value.
442 $failures = 0; // The number of times, this invocation of getText already failed.
444 // The number of times getText failed without yielding a good text in between.
445 static $consecutiveFailedTextRetrievals = 0;
449 // To allow to simply return on success and do not have to worry about book keeping,
450 // we assume, this fetch works (possible after some retries). Nevertheless, we koop
451 // the old value, so we can restore it, if problems occur (See after the while loop).
452 $oldConsecutiveFailedTextRetrievals = $consecutiveFailedTextRetrievals;
453 $consecutiveFailedTextRetrievals = 0;
455 while ( $failures < $this->maxFailures ) {
457 // As soon as we found a good text for the $id, we will return immediately.
458 // Hence, if we make it past the try catch block, we know that we did not
462 // Step 1: Get some text (or reuse from previous iteratuon if checking
463 // for plausibility failed)
465 // Trying to get prefetch, if it has not been tried before
466 if ( $text === false && isset( $this->prefetch ) && $prefetchNotTried ) {
467 $prefetchNotTried = false;
468 $tryIsPrefetch = true;
469 $text = $this->prefetch->prefetch( intval( $this->thisPage ),
470 intval( $this->thisRev ) );
471 if ( $text === null ) {
476 if ( $text === false ) {
477 // Fallback to asking the database
478 $tryIsPrefetch = false;
479 if ( $this->spawn ) {
480 $text = $this->getTextSpawned( $id );
482 $text = $this->getTextDb( $id );
485 // No more checks for texts from DB for now.
486 // If we received something that is not false,
487 // We treat it as good text, regardless of whether it actually is or is not
488 if ( $text !== false ) {
493 if ( $text === false ) {
494 throw new MWException( "Generic error while obtaining text for id " . $id );
497 // We received a good candidate for the text of $id via some method
499 // Step 2: Checking for plausibility and return the text if it is
501 $revID = intval( $this->thisRev );
502 if ( !isset( $this->db ) ) {
503 throw new MWException( "No database available" );
506 $revLength = strlen( $text );
507 if ( $wgContentHandlerUseDB ) {
508 $row = $this->db->selectRow(
510 array( 'rev_len', 'rev_content_model' ),
511 array( 'rev_id' => $revID ),
515 // only check the length for the wikitext content handler,
516 // it's a wasted (and failed) check otherwise
517 if ( $row->rev_content_model == CONTENT_MODEL_WIKITEXT ) {
518 $revLength = $row->rev_len;
522 $revLength = $this->db->selectField( 'revision', 'rev_len', array( 'rev_id' => $revID ) );
525 if ( strlen( $text ) == $revLength ) {
526 if ( $tryIsPrefetch ) {
527 $this->prefetchCount++;
534 throw new MWException( "Received text is unplausible for id " . $id );
535 } catch ( Exception $e ) {
536 $msg = "getting/checking text " . $id . " failed (" . $e->getMessage() . ")";
537 if ( $failures + 1 < $this->maxFailures ) {
538 $msg .= " (Will retry " . ( $this->maxFailures - $failures - 1 ) . " more times)";
540 $this->progress( $msg );
543 // Something went wrong; we did not a text that was plausible :(
546 // A failure in a prefetch hit does not warrant resetting db connection etc.
547 if ( !$tryIsPrefetch ) {
548 // After backing off for some time, we try to reboot the whole process as
549 // much as possible to not carry over failures from one part to the other
551 sleep( $this->failureTimeout );
554 if ( $this->spawn ) {
558 } catch ( Exception $e ) {
559 $this->progress( "Rebooting getText infrastructure failed (" . $e->getMessage() . ")" .
560 " Trying to continue anyways" );
565 // Retirieving a good text for $id failed (at least) maxFailures times.
566 // We abort for this $id.
568 // Restoring the consecutive failures, and maybe aborting, if the dump
570 $consecutiveFailedTextRetrievals = $oldConsecutiveFailedTextRetrievals + 1;
571 if ( $consecutiveFailedTextRetrievals > $this->maxConsecutiveFailedTextRetrievals ) {
572 throw new MWException( "Graceful storage failure" );
579 * May throw a database error if, say, the server dies during query.
581 * @return bool|string
582 * @throws MWException
584 private function getTextDb( $id ) {
586 if ( !isset( $this->db ) ) {
587 throw new MWException( __METHOD__ . "No database available" );
589 $row = $this->db->selectRow( 'text',
590 array( 'old_text', 'old_flags' ),
591 array( 'old_id' => $id ),
593 $text = Revision::getRevisionText( $row );
594 if ( $text === false ) {
597 $stripped = str_replace( "\r", "", $text );
598 $normalized = $wgContLang->normalize( $stripped );
603 private function getTextSpawned( $id ) {
604 wfSuppressWarnings();
605 if ( !$this->spawnProc ) {
609 $text = $this->getTextSpawnedOnce( $id );
615 function openSpawn() {
618 if ( file_exists( "$IP/../multiversion/MWScript.php" ) ) {
620 array_map( 'wfEscapeShellArg',
623 "$IP/../multiversion/MWScript.php",
625 '--wiki', wfWikiID() ) ) );
628 array_map( 'wfEscapeShellArg',
631 "$IP/maintenance/fetchText.php",
632 '--wiki', wfWikiID() ) ) );
635 0 => array( "pipe", "r" ),
636 1 => array( "pipe", "w" ),
637 2 => array( "file", "/dev/null", "a" ) );
640 $this->progress( "Spawning database subprocess: $cmd" );
641 $this->spawnProc = proc_open( $cmd, $spec, $pipes );
642 if ( !$this->spawnProc ) {
644 $this->progress( "Subprocess spawn failed." );
649 $this->spawnWrite, // -> stdin
650 $this->spawnRead, // <- stdout
656 private function closeSpawn() {
657 wfSuppressWarnings();
658 if ( $this->spawnRead ) {
659 fclose( $this->spawnRead );
661 $this->spawnRead = false;
662 if ( $this->spawnWrite ) {
663 fclose( $this->spawnWrite );
665 $this->spawnWrite = false;
666 if ( $this->spawnErr ) {
667 fclose( $this->spawnErr );
669 $this->spawnErr = false;
670 if ( $this->spawnProc ) {
671 pclose( $this->spawnProc );
673 $this->spawnProc = false;
677 private function getTextSpawnedOnce( $id ) {
680 $ok = fwrite( $this->spawnWrite, "$id\n" );
681 // $this->progress( ">> $id" );
686 $ok = fflush( $this->spawnWrite );
687 // $this->progress( ">> [flush]" );
692 // check that the text id they are sending is the one we asked for
693 // this avoids out of sync revision text errors we have encountered in the past
694 $newId = fgets( $this->spawnRead );
695 if ( $newId === false ) {
698 if ( $id != intval( $newId ) ) {
702 $len = fgets( $this->spawnRead );
703 // $this->progress( "<< " . trim( $len ) );
704 if ( $len === false ) {
708 $nbytes = intval( $len );
709 // actual error, not zero-length text
716 // Subprocess may not send everything at once, we have to loop.
717 while ( $nbytes > strlen( $text ) ) {
718 $buffer = fread( $this->spawnRead, $nbytes - strlen( $text ) );
719 if ( $buffer === false ) {
725 $gotbytes = strlen( $text );
726 if ( $gotbytes != $nbytes ) {
727 $this->progress( "Expected $nbytes bytes from database subprocess, got $gotbytes " );
732 // Do normalization in the dump thread...
733 $stripped = str_replace( "\r", "", $text );
734 $normalized = $wgContLang->normalize( $stripped );
739 function startElement( $parser, $name, $attribs ) {
740 $this->checkpointJustWritten = false;
742 $this->clearOpenElement( null );
743 $this->lastName = $name;
745 if ( $name == 'revision' ) {
746 $this->state = $name;
747 $this->egress->writeOpenPage( null, $this->buffer );
749 } elseif ( $name == 'page' ) {
750 $this->state = $name;
751 if ( $this->atStart ) {
752 $this->egress->writeOpenStream( $this->buffer );
754 $this->atStart = false;
758 if ( $name == "text" && isset( $attribs['id'] ) ) {
759 $text = $this->getText( $attribs['id'] );
760 $this->openElement = array( $name, array( 'xml:space' => 'preserve' ) );
761 if ( strlen( $text ) > 0 ) {
762 $this->characterData( $parser, $text );
765 $this->openElement = array( $name, $attribs );
769 function endElement( $parser, $name ) {
770 $this->checkpointJustWritten = false;
772 if ( $this->openElement ) {
773 $this->clearOpenElement( "" );
775 $this->buffer .= "</$name>";
778 if ( $name == 'revision' ) {
779 $this->egress->writeRevision( null, $this->buffer );
782 } elseif ( $name == 'page' ) {
783 if ( !$this->firstPageWritten ) {
784 $this->firstPageWritten = trim( $this->thisPage );
786 $this->lastPageWritten = trim( $this->thisPage );
787 if ( $this->timeExceeded ) {
788 $this->egress->writeClosePage( $this->buffer );
789 // nasty hack, we can't just write the chardata after the
790 // page tag, it will include leading blanks from the next line
791 $this->egress->sink->write( "\n" );
793 $this->buffer = $this->xmlwriterobj->closeStream();
794 $this->egress->writeCloseStream( $this->buffer );
797 $this->thisPage = "";
798 // this could be more than one file if we had more than one output arg
800 $filenameList = (array)$this->egress->getFilenames();
801 $newFilenames = array();
802 $firstPageID = str_pad( $this->firstPageWritten, 9, "0", STR_PAD_LEFT );
803 $lastPageID = str_pad( $this->lastPageWritten, 9, "0", STR_PAD_LEFT );
804 $filenamesCount = count( $filenameList );
805 for ( $i = 0; $i < $filenamesCount; $i++ ) {
806 $checkpointNameFilledIn = sprintf( $this->checkpointFiles[$i], $firstPageID, $lastPageID );
807 $fileinfo = pathinfo( $filenameList[$i] );
808 $newFilenames[] = $fileinfo['dirname'] . '/' . $checkpointNameFilledIn;
810 $this->egress->closeRenameAndReopen( $newFilenames );
811 $this->buffer = $this->xmlwriterobj->openStream();
812 $this->timeExceeded = false;
813 $this->timeOfCheckpoint = $this->lastTime;
814 $this->firstPageWritten = false;
815 $this->checkpointJustWritten = true;
817 $this->egress->writeClosePage( $this->buffer );
819 $this->thisPage = "";
821 } elseif ( $name == 'mediawiki' ) {
822 $this->egress->writeCloseStream( $this->buffer );
827 function characterData( $parser, $data ) {
828 $this->clearOpenElement( null );
829 if ( $this->lastName == "id" ) {
830 if ( $this->state == "revision" ) {
831 $this->thisRev .= $data;
832 } elseif ( $this->state == "page" ) {
833 $this->thisPage .= $data;
836 // have to skip the newline left over from closepagetag line of
837 // end of checkpoint files. nasty hack!!
838 if ( $this->checkpointJustWritten ) {
839 if ( $data[0] == "\n" ) {
840 $data = substr( $data, 1 );
842 $this->checkpointJustWritten = false;
844 $this->buffer .= htmlspecialchars( $data );
847 function clearOpenElement( $style ) {
848 if ( $this->openElement ) {
849 $this->buffer .= Xml::element( $this->openElement[0], $this->openElement[1], $style );
850 $this->openElement = false;