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 global $wgContentHandlerUseDB;
419 $prefetchNotTried = true; // Whether or not we already tried to get the text via prefetch.
420 $text = false; // The candidate for a good text. false if no proper value.
421 $failures = 0; // The number of times, this invocation of getText already failed.
423 static $consecutiveFailedTextRetrievals = 0; // The number of times getText failed without
424 // yielding a good text in between.
428 // To allow to simply return on success and do not have to worry about book keeping,
429 // we assume, this fetch works (possible after some retries). Nevertheless, we koop
430 // the old value, so we can restore it, if problems occur (See after the while loop).
431 $oldConsecutiveFailedTextRetrievals = $consecutiveFailedTextRetrievals;
432 $consecutiveFailedTextRetrievals = 0;
434 while ( $failures < $this->maxFailures ) {
436 // As soon as we found a good text for the $id, we will return immediately.
437 // Hence, if we make it past the try catch block, we know that we did not
441 // Step 1: Get some text (or reuse from previous iteratuon if checking
442 // for plausibility failed)
444 // Trying to get prefetch, if it has not been tried before
445 if ( $text === false && isset( $this->prefetch ) && $prefetchNotTried ) {
446 $prefetchNotTried = false;
447 $tryIsPrefetch = true;
448 $text = $this->prefetch->prefetch( intval( $this->thisPage ),
449 intval( $this->thisRev ) );
450 if ( $text === null ) {
455 if ( $text === false ) {
456 // Fallback to asking the database
457 $tryIsPrefetch = false;
458 if ( $this->spawn ) {
459 $text = $this->getTextSpawned( $id );
461 $text = $this->getTextDb( $id );
464 // No more checks for texts from DB for now.
465 // If we received something that is not false,
466 // We treat it as good text, regardless of whether it actually is or is not
467 if ( $text !== false ) {
472 if ( $text === false ) {
473 throw new MWException( "Generic error while obtaining text for id " . $id );
476 // We received a good candidate for the text of $id via some method
478 // Step 2: Checking for plausibility and return the text if it is
480 $revID = intval( $this->thisRev );
481 if ( ! isset( $this->db ) ) {
482 throw new MWException( "No database available" );
485 $revLength = strlen( $text );
486 if ( $wgContentHandlerUseDB ) {
487 $row = $this->db->selectRow( 'revision', array( 'rev_len', 'rev_content_model' ), array( 'rev_id' => $revID ), __METHOD__ );
489 // only check the length for the wikitext content handler,
490 // it's a wasted (and failed) check otherwise
491 if ( $row->rev_content_model == CONTENT_MODEL_WIKITEXT ) {
492 $revLength = $row->rev_len;
498 $revLength = $this->db->selectField( 'revision', 'rev_len', array( 'rev_id' => $revID ) );
501 if ( strlen( $text ) == $revLength ) {
502 if ( $tryIsPrefetch ) {
503 $this->prefetchCount++;
509 throw new MWException( "Received text is unplausible for id " . $id );
511 } catch ( Exception $e ) {
512 $msg = "getting/checking text " . $id . " failed (" . $e->getMessage() . ")";
513 if ( $failures + 1 < $this->maxFailures ) {
514 $msg .= " (Will retry " . ( $this->maxFailures - $failures - 1 ) . " more times)";
516 $this->progress( $msg );
519 // Something went wrong; we did not a text that was plausible :(
522 // A failure in a prefetch hit does not warrant resetting db connection etc.
523 if ( ! $tryIsPrefetch ) {
524 // After backing off for some time, we try to reboot the whole process as
525 // much as possible to not carry over failures from one part to the other
527 sleep( $this->failureTimeout );
530 if ( $this->spawn ) {
534 } catch ( Exception $e ) {
535 $this->progress( "Rebooting getText infrastructure failed (" . $e->getMessage() . ")" .
536 " Trying to continue anyways" );
541 // Retirieving a good text for $id failed (at least) maxFailures times.
542 // We abort for this $id.
544 // Restoring the consecutive failures, and maybe aborting, if the dump
546 $consecutiveFailedTextRetrievals = $oldConsecutiveFailedTextRetrievals + 1;
547 if ( $consecutiveFailedTextRetrievals > $this->maxConsecutiveFailedTextRetrievals ) {
548 throw new MWException( "Graceful storage failure" );
556 * May throw a database error if, say, the server dies during query.
558 * @return bool|string
559 * @throws MWException
561 private function getTextDb( $id ) {
563 if ( ! isset( $this->db ) ) {
564 throw new MWException( __METHOD__ . "No database available" );
566 $row = $this->db->selectRow( 'text',
567 array( 'old_text', 'old_flags' ),
568 array( 'old_id' => $id ),
570 $text = Revision::getRevisionText( $row );
571 if ( $text === false ) {
574 $stripped = str_replace( "\r", "", $text );
575 $normalized = $wgContLang->normalize( $stripped );
579 private function getTextSpawned( $id ) {
580 wfSuppressWarnings();
581 if ( !$this->spawnProc ) {
585 $text = $this->getTextSpawnedOnce( $id );
590 function openSpawn() {
593 if ( file_exists( "$IP/../multiversion/MWScript.php" ) ) {
595 array_map( 'wfEscapeShellArg',
598 "$IP/../multiversion/MWScript.php",
600 '--wiki', wfWikiID() ) ) );
604 array_map( 'wfEscapeShellArg',
607 "$IP/maintenance/fetchText.php",
608 '--wiki', wfWikiID() ) ) );
611 0 => array( "pipe", "r" ),
612 1 => array( "pipe", "w" ),
613 2 => array( "file", "/dev/null", "a" ) );
616 $this->progress( "Spawning database subprocess: $cmd" );
617 $this->spawnProc = proc_open( $cmd, $spec, $pipes );
618 if ( !$this->spawnProc ) {
620 $this->progress( "Subprocess spawn failed." );
624 $this->spawnWrite, // -> stdin
625 $this->spawnRead, // <- stdout
631 private function closeSpawn() {
632 wfSuppressWarnings();
633 if ( $this->spawnRead ) {
634 fclose( $this->spawnRead );
636 $this->spawnRead = false;
637 if ( $this->spawnWrite ) {
638 fclose( $this->spawnWrite );
640 $this->spawnWrite = false;
641 if ( $this->spawnErr ) {
642 fclose( $this->spawnErr );
644 $this->spawnErr = false;
645 if ( $this->spawnProc ) {
646 pclose( $this->spawnProc );
648 $this->spawnProc = false;
652 private function getTextSpawnedOnce( $id ) {
655 $ok = fwrite( $this->spawnWrite, "$id\n" );
656 // $this->progress( ">> $id" );
661 $ok = fflush( $this->spawnWrite );
662 // $this->progress( ">> [flush]" );
667 // check that the text id they are sending is the one we asked for
668 // this avoids out of sync revision text errors we have encountered in the past
669 $newId = fgets( $this->spawnRead );
670 if ( $newId === false ) {
673 if ( $id != intval( $newId ) ) {
677 $len = fgets( $this->spawnRead );
678 // $this->progress( "<< " . trim( $len ) );
679 if ( $len === false ) {
683 $nbytes = intval( $len );
684 // actual error, not zero-length text
691 // Subprocess may not send everything at once, we have to loop.
692 while ( $nbytes > strlen( $text ) ) {
693 $buffer = fread( $this->spawnRead, $nbytes - strlen( $text ) );
694 if ( $buffer === false ) {
700 $gotbytes = strlen( $text );
701 if ( $gotbytes != $nbytes ) {
702 $this->progress( "Expected $nbytes bytes from database subprocess, got $gotbytes " );
706 // Do normalization in the dump thread...
707 $stripped = str_replace( "\r", "", $text );
708 $normalized = $wgContLang->normalize( $stripped );
712 function startElement( $parser, $name, $attribs ) {
713 $this->checkpointJustWritten = false;
715 $this->clearOpenElement( null );
716 $this->lastName = $name;
718 if ( $name == 'revision' ) {
719 $this->state = $name;
720 $this->egress->writeOpenPage( null, $this->buffer );
722 } elseif ( $name == 'page' ) {
723 $this->state = $name;
724 if ( $this->atStart ) {
725 $this->egress->writeOpenStream( $this->buffer );
727 $this->atStart = false;
731 if ( $name == "text" && isset( $attribs['id'] ) ) {
732 $text = $this->getText( $attribs['id'] );
733 $this->openElement = array( $name, array( 'xml:space' => 'preserve' ) );
734 if ( strlen( $text ) > 0 ) {
735 $this->characterData( $parser, $text );
738 $this->openElement = array( $name, $attribs );
742 function endElement( $parser, $name ) {
743 $this->checkpointJustWritten = false;
745 if ( $this->openElement ) {
746 $this->clearOpenElement( "" );
748 $this->buffer .= "</$name>";
751 if ( $name == 'revision' ) {
752 $this->egress->writeRevision( null, $this->buffer );
755 } elseif ( $name == 'page' ) {
756 if ( ! $this->firstPageWritten ) {
757 $this->firstPageWritten = trim( $this->thisPage );
759 $this->lastPageWritten = trim( $this->thisPage );
760 if ( $this->timeExceeded ) {
761 $this->egress->writeClosePage( $this->buffer );
762 // nasty hack, we can't just write the chardata after the
763 // page tag, it will include leading blanks from the next line
764 $this->egress->sink->write( "\n" );
766 $this->buffer = $this->xmlwriterobj->closeStream();
767 $this->egress->writeCloseStream( $this->buffer );
770 $this->thisPage = "";
771 // this could be more than one file if we had more than one output arg
773 $filenameList = (array)$this->egress->getFilenames();
774 $newFilenames = array();
775 $firstPageID = str_pad( $this->firstPageWritten, 9, "0", STR_PAD_LEFT );
776 $lastPageID = str_pad( $this->lastPageWritten, 9, "0", STR_PAD_LEFT );
777 for ( $i = 0; $i < count( $filenameList ); $i++ ) {
778 $checkpointNameFilledIn = sprintf( $this->checkpointFiles[$i], $firstPageID, $lastPageID );
779 $fileinfo = pathinfo( $filenameList[$i] );
780 $newFilenames[] = $fileinfo['dirname'] . '/' . $checkpointNameFilledIn;
782 $this->egress->closeRenameAndReopen( $newFilenames );
783 $this->buffer = $this->xmlwriterobj->openStream();
784 $this->timeExceeded = false;
785 $this->timeOfCheckpoint = $this->lastTime;
786 $this->firstPageWritten = false;
787 $this->checkpointJustWritten = true;
790 $this->egress->writeClosePage( $this->buffer );
792 $this->thisPage = "";
795 } elseif ( $name == 'mediawiki' ) {
796 $this->egress->writeCloseStream( $this->buffer );
801 function characterData( $parser, $data ) {
802 $this->clearOpenElement( null );
803 if ( $this->lastName == "id" ) {
804 if ( $this->state == "revision" ) {
805 $this->thisRev .= $data;
806 } elseif ( $this->state == "page" ) {
807 $this->thisPage .= $data;
810 // have to skip the newline left over from closepagetag line of
811 // end of checkpoint files. nasty hack!!
812 if ( $this->checkpointJustWritten ) {
813 if ( $data[0] == "\n" ) {
814 $data = substr( $data, 1 );
816 $this->checkpointJustWritten = false;
818 $this->buffer .= htmlspecialchars( $data );
821 function clearOpenElement( $style ) {
822 if ( $this->openElement ) {
823 $this->buffer .= Xml::element( $this->openElement[0], $this->openElement[1], $style );
824 $this->openElement = false;