3 * BackupDumper that postprocesses XML dumps from dumpBackup.php to add page text
5 * Copyright (C) 2005 Brion Vibber <brion@pobox.com>
6 * http://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 {
34 var $input = "php://stdin";
35 var $history = WikiExporter::FULL;
37 var $prefetchCount = 0;
38 var $prefetchCountLast = 0;
39 var $fetchCountLast = 0;
42 var $maxConsecutiveFailedTextRetrievals = 200;
43 var $failureTimeout = 5; // Seconds to sleep after db failure
51 var $spawnProc = false;
56 var $spawnWrite = false;
61 var $spawnRead = false;
66 var $spawnErr = false;
68 var $xmlwriterobj = false;
70 // when we spend more than maxTimeAllowed seconds on this run, we continue
71 // processing until we write out the next complete page, then save output file(s),
72 // rename it/them and open new one(s)
73 var $maxTimeAllowed = 0; // 0 = no limit
74 var $timeExceeded = false;
75 var $firstPageWritten = false;
76 var $lastPageWritten = false;
77 var $checkpointJustWritten = false;
78 var $checkpointFiles = array();
87 * Drop the database connection $this->db and try to get a new one.
89 * This function tries to get a /different/ connection if this is
90 * possible. Hence, (if this is possible) it switches to a different
91 * failover upon each call.
93 * This function resets $this->lb and closes all connections on it.
98 // Cleaning up old connections
99 if ( isset( $this->lb ) ) {
100 $this->lb->closeAll();
104 if ( $this->forcedDb !== null ) {
105 $this->db = $this->forcedDb;
109 if ( isset( $this->db ) && $this->db->isOpen() ) {
110 throw new MWException( 'DB is set and has not been closed by the Load Balancer' );
115 // Trying to set up new connection.
116 // We do /not/ retry upon failure, but delegate to encapsulating logic, to avoid
117 // individually retrying at different layers of code.
119 // 1. The LoadBalancer.
121 $this->lb = wfGetLBFactory()->newMainLB();
122 } catch ( Exception $e ) {
123 throw new MWException( __METHOD__ . " rotating DB failed to obtain new load balancer (" . $e->getMessage() . ")" );
127 // 2. The Connection, through the load balancer.
129 $this->db = $this->lb->getConnection( DB_SLAVE, 'backup' );
130 } catch ( Exception $e ) {
131 throw new MWException( __METHOD__ . " rotating DB failed to obtain new database (" . $e->getMessage() . ")" );
136 function initProgress( $history = WikiExporter::FULL ) {
137 parent::initProgress();
138 $this->timeOfCheckpoint = $this->startTime;
141 function dump( $history, $text = WikiExporter::TEXT ) {
142 // Notice messages will foul up your XML output even if they're
143 // relatively harmless.
144 if ( ini_get( 'display_errors' ) ) {
145 ini_set( 'display_errors', 'stderr' );
148 $this->initProgress( $this->history );
150 // We are trying to get an initial database connection to avoid that the
151 // first try of this request's first call to getText fails. However, if
152 // obtaining a good DB connection fails it's not a serious issue, as
153 // getText does retry upon failure and can start without having a working
157 } catch ( Exception $e ) {
158 // We do not even count this as failure. Just let eventual
160 $this->progress( "Getting initial DB connection failed (" .
161 $e->getMessage() . ")" );
164 $this->egress = new ExportProgressFilter( $this->sink, $this );
166 // it would be nice to do it in the constructor, oh well. need egress set
167 $this->finalOptionCheck();
169 // we only want this so we know how to close a stream :-P
170 $this->xmlwriterobj = new XmlDumpWriter();
172 $input = fopen( $this->input, "rt" );
173 $this->readDump( $input );
175 if ( $this->spawnProc ) {
179 $this->report( true );
182 function processOption( $opt, $val, $param ) {
184 $url = $this->processFileOpt( $val, $param );
188 require_once "$IP/maintenance/backupPrefetch.inc";
189 $this->prefetch = new BaseDump( $url );
195 $this->maxTimeAllowed = intval( $val ) * 60;
197 case 'checkpointfile':
198 $this->checkpointFiles[] = $val;
201 $this->history = WikiExporter::CURRENT;
204 $this->history = WikiExporter::FULL;
215 function processFileOpt( $val, $param ) {
216 $fileURIs = explode( ';', $param );
217 foreach ( $fileURIs as $URI ) {
223 $newURI = "compress.zlib://$URI";
226 $newURI = "compress.bzip2://$URI";
229 $newURI = "mediawiki.compress.7z://$URI";
234 $newFileURIs[] = $newURI;
236 $val = implode( ';', $newFileURIs );
241 * Overridden to include prefetch ratio if enabled.
243 function showReport() {
244 if ( !$this->prefetch ) {
245 parent::showReport();
249 if ( $this->reporting ) {
250 $now = wfTimestamp( TS_DB );
251 $nowts = microtime( true );
252 $deltaAll = $nowts - $this->startTime;
253 $deltaPart = $nowts - $this->lastTime;
254 $this->pageCountPart = $this->pageCount - $this->pageCountLast;
255 $this->revCountPart = $this->revCount - $this->revCountLast;
258 $portion = $this->revCount / $this->maxCount;
259 $eta = $this->startTime + $deltaAll / $portion;
260 $etats = wfTimestamp( TS_DB, intval( $eta ) );
261 if ( $this->fetchCount ) {
262 $fetchRate = 100.0 * $this->prefetchCount / $this->fetchCount;
266 $pageRate = $this->pageCount / $deltaAll;
267 $revRate = $this->revCount / $deltaAll;
275 if ( $this->fetchCountLast ) {
276 $fetchRatePart = 100.0 * $this->prefetchCountLast / $this->fetchCountLast;
278 $fetchRatePart = '-';
280 $pageRatePart = $this->pageCountPart / $deltaPart;
281 $revRatePart = $this->revCountPart / $deltaPart;
284 $fetchRatePart = '-';
288 $this->progress( sprintf( "%s: %s (ID %d) %d pages (%0.1f|%0.1f/sec all|curr), %d revs (%0.1f|%0.1f/sec all|curr), %0.1f%%|%0.1f%% prefetched (all|curr), ETA %s [max %d]",
289 $now, wfWikiID(), $this->ID, $this->pageCount, $pageRate, $pageRatePart, $this->revCount, $revRate, $revRatePart, $fetchRate, $fetchRatePart, $etats, $this->maxCount ) );
290 $this->lastTime = $nowts;
291 $this->revCountLast = $this->revCount;
292 $this->prefetchCountLast = $this->prefetchCount;
293 $this->fetchCountLast = $this->fetchCount;
297 function setTimeExceeded() {
298 $this->timeExceeded = true;
301 function checkIfTimeExceeded() {
302 if ( $this->maxTimeAllowed && ( $this->lastTime - $this->timeOfCheckpoint > $this->maxTimeAllowed ) ) {
308 function finalOptionCheck() {
309 if ( ( $this->checkpointFiles && ! $this->maxTimeAllowed ) ||
310 ( $this->maxTimeAllowed && !$this->checkpointFiles ) ) {
311 throw new MWException( "Options checkpointfile and maxtime must be specified together.\n" );
313 foreach ( $this->checkpointFiles as $checkpointFile ) {
314 $count = substr_count ( $checkpointFile, "%s" );
316 throw new MWException( "Option checkpointfile must contain two '%s' for substitution of first and last pageids, count is $count instead, file is $checkpointFile.\n" );
320 if ( $this->checkpointFiles ) {
321 $filenameList = (array)$this->egress->getFilenames();
322 if ( count( $filenameList ) != count( $this->checkpointFiles ) ) {
323 throw new MWException( "One checkpointfile must be specified for each output option, if maxtime is used.\n" );
329 * @throws MWException Failure to parse XML input
332 function readDump( $input ) {
334 $this->openElement = false;
335 $this->atStart = true;
337 $this->lastName = "";
341 $parser = xml_parser_create( "UTF-8" );
342 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
344 xml_set_element_handler( $parser, array( &$this, 'startElement' ), array( &$this, 'endElement' ) );
345 xml_set_character_data_handler( $parser, array( &$this, 'characterData' ) );
347 $offset = 0; // for context extraction on error reporting
348 $bufferSize = 512 * 1024;
350 if ( $this->checkIfTimeExceeded() ) {
351 $this->setTimeExceeded();
353 $chunk = fread( $input, $bufferSize );
354 if ( !xml_parse( $parser, $chunk, feof( $input ) ) ) {
355 wfDebug( "TextDumpPass::readDump encountered XML parsing error\n" );
357 $byte = xml_get_current_byte_index( $parser );
358 $msg = wfMessage( 'xml-error-string',
359 'XML import parse failure',
360 xml_get_current_line_number( $parser ),
361 xml_get_current_column_number( $parser ),
362 $byte . ( is_null( $chunk ) ? null : ( '; "' . substr( $chunk, $byte -$offset, 16 ) . '"' ) ),
363 xml_error_string( xml_get_error_code( $parser ) ) )->escaped();
365 xml_parser_free( $parser );
367 throw new MWException( $msg );
369 $offset += strlen( $chunk );
370 } while ( $chunk !== false && !feof( $input ) );
371 if ( $this->maxTimeAllowed ) {
372 $filenameList = (array)$this->egress->getFilenames();
373 // we wrote some stuff after last checkpoint that needs renamed
374 if ( file_exists( $filenameList[0] ) ) {
375 $newFilenames = array();
376 # we might have just written the header and footer and had no
377 # pages or revisions written... perhaps they were all deleted
378 # there's no pageID 0 so we use that. the caller is responsible
379 # for deciding what to do with a file containing only the
380 # siteinfo information and the mw tags.
381 if ( ! $this->firstPageWritten ) {
382 $firstPageID = str_pad( 0, 9, "0", STR_PAD_LEFT );
383 $lastPageID = str_pad( 0, 9, "0", STR_PAD_LEFT );
386 $firstPageID = str_pad( $this->firstPageWritten, 9, "0", STR_PAD_LEFT );
387 $lastPageID = str_pad( $this->lastPageWritten, 9, "0", STR_PAD_LEFT );
389 for ( $i = 0; $i < count( $filenameList ); $i++ ) {
390 $checkpointNameFilledIn = sprintf( $this->checkpointFiles[$i], $firstPageID, $lastPageID );
391 $fileinfo = pathinfo( $filenameList[$i] );
392 $newFilenames[] = $fileinfo['dirname'] . '/' . $checkpointNameFilledIn;
394 $this->egress->closeAndRename( $newFilenames );
397 xml_parser_free( $parser );
403 * Tries to get the revision text for a revision id.
405 * Upon errors, retries (Up to $this->maxFailures tries each call).
406 * If still no good revision get could be found even after this retrying, "" is returned.
407 * If no good revision text could be returned for
408 * $this->maxConsecutiveFailedTextRetrievals consecutive calls to getText, MWException
411 * @param $id string The revision id to get the text for
413 * @return string The revision text for $id, or ""
414 * @throws MWException
416 function getText( $id ) {
417 $prefetchNotTried = true; // Whether or not we already tried to get the text via prefetch.
418 $text = false; // The candidate for a good text. false if no proper value.
419 $failures = 0; // The number of times, this invocation of getText already failed.
421 static $consecutiveFailedTextRetrievals = 0; // The number of times getText failed without
422 // yielding a good text in between.
426 // To allow to simply return on success and do not have to worry about book keeping,
427 // we assume, this fetch works (possible after some retries). Nevertheless, we koop
428 // the old value, so we can restore it, if problems occur (See after the while loop).
429 $oldConsecutiveFailedTextRetrievals = $consecutiveFailedTextRetrievals;
430 $consecutiveFailedTextRetrievals = 0;
432 while ( $failures < $this->maxFailures ) {
434 // As soon as we found a good text for the $id, we will return immediately.
435 // Hence, if we make it past the try catch block, we know that we did not
439 // Step 1: Get some text (or reuse from previous iteratuon if checking
440 // for plausibility failed)
442 // Trying to get prefetch, if it has not been tried before
443 if ( $text === false && isset( $this->prefetch ) && $prefetchNotTried ) {
444 $prefetchNotTried = false;
445 $tryIsPrefetch = true;
446 $text = $this->prefetch->prefetch( intval( $this->thisPage ),
447 intval( $this->thisRev ) );
448 if ( $text === null ) {
453 if ( $text === false ) {
454 // Fallback to asking the database
455 $tryIsPrefetch = false;
456 if ( $this->spawn ) {
457 $text = $this->getTextSpawned( $id );
459 $text = $this->getTextDb( $id );
462 // No more checks for texts from DB for now.
463 // If we received something that is not false,
464 // We treat it as good text, regardless of whether it actually is or is not
465 if ( $text !== false ) {
470 if ( $text === false ) {
471 throw new MWException( "Generic error while obtaining text for id " . $id );
474 // We received a good candidate for the text of $id via some method
476 // Step 2: Checking for plausibility and return the text if it is
478 $revID = intval( $this->thisRev );
479 if ( ! isset( $this->db ) ) {
480 throw new MWException( "No database available" );
482 $revLength = $this->db->selectField( 'revision', 'rev_len', array( 'rev_id' => $revID ) );
483 if ( strlen( $text ) == $revLength ) {
484 if ( $tryIsPrefetch ) {
485 $this->prefetchCount++;
491 throw new MWException( "Received text is unplausible for id " . $id );
493 } catch ( Exception $e ) {
494 $msg = "getting/checking text " . $id . " failed (" . $e->getMessage() . ")";
495 if ( $failures + 1 < $this->maxFailures ) {
496 $msg .= " (Will retry " . ( $this->maxFailures - $failures - 1 ) . " more times)";
498 $this->progress( $msg );
501 // Something went wrong; we did not a text that was plausible :(
504 // A failure in a prefetch hit does not warrant resetting db connection etc.
505 if ( ! $tryIsPrefetch ) {
506 // After backing off for some time, we try to reboot the whole process as
507 // much as possible to not carry over failures from one part to the other
509 sleep( $this->failureTimeout );
512 if ( $this->spawn ) {
516 } catch ( Exception $e ) {
517 $this->progress( "Rebooting getText infrastructure failed (" . $e->getMessage() . ")" .
518 " Trying to continue anyways" );
523 // Retirieving a good text for $id failed (at least) maxFailures times.
524 // We abort for this $id.
526 // Restoring the consecutive failures, and maybe aborting, if the dump
528 $consecutiveFailedTextRetrievals = $oldConsecutiveFailedTextRetrievals + 1;
529 if ( $consecutiveFailedTextRetrievals > $this->maxConsecutiveFailedTextRetrievals ) {
530 throw new MWException( "Graceful storage failure" );
538 * May throw a database error if, say, the server dies during query.
540 * @return bool|string
541 * @throws MWException
543 private function getTextDb( $id ) {
545 if ( ! isset( $this->db ) ) {
546 throw new MWException( __METHOD__ . "No database available" );
548 $row = $this->db->selectRow( 'text',
549 array( 'old_text', 'old_flags' ),
550 array( 'old_id' => $id ),
552 $text = Revision::getRevisionText( $row );
553 if ( $text === false ) {
556 $stripped = str_replace( "\r", "", $text );
557 $normalized = $wgContLang->normalize( $stripped );
561 private function getTextSpawned( $id ) {
562 wfSuppressWarnings();
563 if ( !$this->spawnProc ) {
567 $text = $this->getTextSpawnedOnce( $id );
572 function openSpawn() {
575 if ( file_exists( "$IP/../multiversion/MWScript.php" ) ) {
577 array_map( 'wfEscapeShellArg',
580 "$IP/../multiversion/MWScript.php",
582 '--wiki', wfWikiID() ) ) );
586 array_map( 'wfEscapeShellArg',
589 "$IP/maintenance/fetchText.php",
590 '--wiki', wfWikiID() ) ) );
593 0 => array( "pipe", "r" ),
594 1 => array( "pipe", "w" ),
595 2 => array( "file", "/dev/null", "a" ) );
598 $this->progress( "Spawning database subprocess: $cmd" );
599 $this->spawnProc = proc_open( $cmd, $spec, $pipes );
600 if ( !$this->spawnProc ) {
602 $this->progress( "Subprocess spawn failed." );
606 $this->spawnWrite, // -> stdin
607 $this->spawnRead, // <- stdout
613 private function closeSpawn() {
614 wfSuppressWarnings();
615 if ( $this->spawnRead ) {
616 fclose( $this->spawnRead );
618 $this->spawnRead = false;
619 if ( $this->spawnWrite ) {
620 fclose( $this->spawnWrite );
622 $this->spawnWrite = false;
623 if ( $this->spawnErr ) {
624 fclose( $this->spawnErr );
626 $this->spawnErr = false;
627 if ( $this->spawnProc ) {
628 pclose( $this->spawnProc );
630 $this->spawnProc = false;
634 private function getTextSpawnedOnce( $id ) {
637 $ok = fwrite( $this->spawnWrite, "$id\n" );
638 // $this->progress( ">> $id" );
643 $ok = fflush( $this->spawnWrite );
644 // $this->progress( ">> [flush]" );
649 // check that the text id they are sending is the one we asked for
650 // this avoids out of sync revision text errors we have encountered in the past
651 $newId = fgets( $this->spawnRead );
652 if ( $newId === false ) {
655 if ( $id != intval( $newId ) ) {
659 $len = fgets( $this->spawnRead );
660 // $this->progress( "<< " . trim( $len ) );
661 if ( $len === false ) {
665 $nbytes = intval( $len );
666 // actual error, not zero-length text
673 // Subprocess may not send everything at once, we have to loop.
674 while ( $nbytes > strlen( $text ) ) {
675 $buffer = fread( $this->spawnRead, $nbytes - strlen( $text ) );
676 if ( $buffer === false ) {
682 $gotbytes = strlen( $text );
683 if ( $gotbytes != $nbytes ) {
684 $this->progress( "Expected $nbytes bytes from database subprocess, got $gotbytes " );
688 // Do normalization in the dump thread...
689 $stripped = str_replace( "\r", "", $text );
690 $normalized = $wgContLang->normalize( $stripped );
694 function startElement( $parser, $name, $attribs ) {
695 $this->checkpointJustWritten = false;
697 $this->clearOpenElement( null );
698 $this->lastName = $name;
700 if ( $name == 'revision' ) {
701 $this->state = $name;
702 $this->egress->writeOpenPage( null, $this->buffer );
704 } elseif ( $name == 'page' ) {
705 $this->state = $name;
706 if ( $this->atStart ) {
707 $this->egress->writeOpenStream( $this->buffer );
709 $this->atStart = false;
713 if ( $name == "text" && isset( $attribs['id'] ) ) {
714 $text = $this->getText( $attribs['id'] );
715 $this->openElement = array( $name, array( 'xml:space' => 'preserve' ) );
716 if ( strlen( $text ) > 0 ) {
717 $this->characterData( $parser, $text );
720 $this->openElement = array( $name, $attribs );
724 function endElement( $parser, $name ) {
725 $this->checkpointJustWritten = false;
727 if ( $this->openElement ) {
728 $this->clearOpenElement( "" );
730 $this->buffer .= "</$name>";
733 if ( $name == 'revision' ) {
734 $this->egress->writeRevision( null, $this->buffer );
737 } elseif ( $name == 'page' ) {
738 if ( ! $this->firstPageWritten ) {
739 $this->firstPageWritten = trim( $this->thisPage );
741 $this->lastPageWritten = trim( $this->thisPage );
742 if ( $this->timeExceeded ) {
743 $this->egress->writeClosePage( $this->buffer );
744 // nasty hack, we can't just write the chardata after the
745 // page tag, it will include leading blanks from the next line
746 $this->egress->sink->write( "\n" );
748 $this->buffer = $this->xmlwriterobj->closeStream();
749 $this->egress->writeCloseStream( $this->buffer );
752 $this->thisPage = "";
753 // this could be more than one file if we had more than one output arg
755 $filenameList = (array)$this->egress->getFilenames();
756 $newFilenames = array();
757 $firstPageID = str_pad( $this->firstPageWritten, 9, "0", STR_PAD_LEFT );
758 $lastPageID = str_pad( $this->lastPageWritten, 9, "0", STR_PAD_LEFT );
759 for ( $i = 0; $i < count( $filenameList ); $i++ ) {
760 $checkpointNameFilledIn = sprintf( $this->checkpointFiles[$i], $firstPageID, $lastPageID );
761 $fileinfo = pathinfo( $filenameList[$i] );
762 $newFilenames[] = $fileinfo['dirname'] . '/' . $checkpointNameFilledIn;
764 $this->egress->closeRenameAndReopen( $newFilenames );
765 $this->buffer = $this->xmlwriterobj->openStream();
766 $this->timeExceeded = false;
767 $this->timeOfCheckpoint = $this->lastTime;
768 $this->firstPageWritten = false;
769 $this->checkpointJustWritten = true;
772 $this->egress->writeClosePage( $this->buffer );
774 $this->thisPage = "";
777 } elseif ( $name == 'mediawiki' ) {
778 $this->egress->writeCloseStream( $this->buffer );
783 function characterData( $parser, $data ) {
784 $this->clearOpenElement( null );
785 if ( $this->lastName == "id" ) {
786 if ( $this->state == "revision" ) {
787 $this->thisRev .= $data;
788 } elseif ( $this->state == "page" ) {
789 $this->thisPage .= $data;
792 // have to skip the newline left over from closepagetag line of
793 // end of checkpoint files. nasty hack!!
794 if ( $this->checkpointJustWritten ) {
795 if ( $data[0] == "\n" ) {
796 $data = substr( $data, 1 );
798 $this->checkpointJustWritten = false;
800 $this->buffer .= htmlspecialchars( $data );
803 function clearOpenElement( $style ) {
804 if ( $this->openElement ) {
805 $this->buffer .= Xml::element( $this->openElement[0], $this->openElement[1], $style );
806 $this->openElement = false;