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' );
147 $this->initProgress( $this->history );
149 // We are trying to get an initial database connection to avoid that the
150 // first try of this request's first call to getText fails. However, if
151 // obtaining a good DB connection fails it's not a serious issue, as
152 // getText does retry upon failure and can start without having a working
156 } catch ( Exception $e ) {
157 // We do not even count this as failure. Just let eventual
159 $this->progress( "Getting initial DB connection failed (" .
160 $e->getMessage() . ")" );
163 $this->egress = new ExportProgressFilter( $this->sink, $this );
165 // it would be nice to do it in the constructor, oh well. need egress set
166 $this->finalOptionCheck();
168 // we only want this so we know how to close a stream :-P
169 $this->xmlwriterobj = new XmlDumpWriter();
171 $input = fopen( $this->input, "rt" );
172 $this->readDump( $input );
174 if ( $this->spawnProc ) {
178 $this->report( true );
181 function processOption( $opt, $val, $param ) {
183 $url = $this->processFileOpt( $val, $param );
187 require_once "$IP/maintenance/backupPrefetch.inc";
188 $this->prefetch = new BaseDump( $url );
194 $this->maxTimeAllowed = intval( $val ) * 60;
196 case 'checkpointfile':
197 $this->checkpointFiles[] = $val;
200 $this->history = WikiExporter::CURRENT;
203 $this->history = WikiExporter::FULL;
214 function processFileOpt( $val, $param ) {
215 $fileURIs = explode( ';', $param );
216 foreach ( $fileURIs as $URI ) {
222 $newURI = "compress.zlib://$URI";
225 $newURI = "compress.bzip2://$URI";
228 $newURI = "mediawiki.compress.7z://$URI";
233 $newFileURIs[] = $newURI;
235 $val = implode( ';', $newFileURIs );
240 * Overridden to include prefetch ratio if enabled.
242 function showReport() {
243 if ( !$this->prefetch ) {
244 parent::showReport();
248 if ( $this->reporting ) {
249 $now = wfTimestamp( TS_DB );
250 $nowts = microtime( true );
251 $deltaAll = $nowts - $this->startTime;
252 $deltaPart = $nowts - $this->lastTime;
253 $this->pageCountPart = $this->pageCount - $this->pageCountLast;
254 $this->revCountPart = $this->revCount - $this->revCountLast;
257 $portion = $this->revCount / $this->maxCount;
258 $eta = $this->startTime + $deltaAll / $portion;
259 $etats = wfTimestamp( TS_DB, intval( $eta ) );
260 if ( $this->fetchCount ) {
261 $fetchRate = 100.0 * $this->prefetchCount / $this->fetchCount;
265 $pageRate = $this->pageCount / $deltaAll;
266 $revRate = $this->revCount / $deltaAll;
274 if ( $this->fetchCountLast ) {
275 $fetchRatePart = 100.0 * $this->prefetchCountLast / $this->fetchCountLast;
277 $fetchRatePart = '-';
279 $pageRatePart = $this->pageCountPart / $deltaPart;
280 $revRatePart = $this->revCountPart / $deltaPart;
283 $fetchRatePart = '-';
287 $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]",
288 $now, wfWikiID(), $this->ID, $this->pageCount, $pageRate, $pageRatePart, $this->revCount, $revRate, $revRatePart, $fetchRate, $fetchRatePart, $etats, $this->maxCount ) );
289 $this->lastTime = $nowts;
290 $this->revCountLast = $this->revCount;
291 $this->prefetchCountLast = $this->prefetchCount;
292 $this->fetchCountLast = $this->fetchCount;
296 function setTimeExceeded() {
297 $this->timeExceeded = true;
300 function checkIfTimeExceeded() {
301 if ( $this->maxTimeAllowed && ( $this->lastTime - $this->timeOfCheckpoint > $this->maxTimeAllowed ) ) {
307 function finalOptionCheck() {
308 if ( ( $this->checkpointFiles && ! $this->maxTimeAllowed ) ||
309 ( $this->maxTimeAllowed && !$this->checkpointFiles ) ) {
310 throw new MWException( "Options checkpointfile and maxtime must be specified together.\n" );
312 foreach ( $this->checkpointFiles as $checkpointFile ) {
313 $count = substr_count ( $checkpointFile, "%s" );
315 throw new MWException( "Option checkpointfile must contain two '%s' for substitution of first and last pageids, count is $count instead, file is $checkpointFile.\n" );
319 if ( $this->checkpointFiles ) {
320 $filenameList = (array)$this->egress->getFilenames();
321 if ( count( $filenameList ) != count( $this->checkpointFiles ) ) {
322 throw new MWException( "One checkpointfile must be specified for each output option, if maxtime is used.\n" );
328 * @throws MWException Failure to parse XML input
331 function readDump( $input ) {
333 $this->openElement = false;
334 $this->atStart = true;
336 $this->lastName = "";
340 $parser = xml_parser_create( "UTF-8" );
341 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
343 xml_set_element_handler( $parser, array( &$this, 'startElement' ), array( &$this, 'endElement' ) );
344 xml_set_character_data_handler( $parser, array( &$this, 'characterData' ) );
346 $offset = 0; // for context extraction on error reporting
347 $bufferSize = 512 * 1024;
349 if ( $this->checkIfTimeExceeded() ) {
350 $this->setTimeExceeded();
352 $chunk = fread( $input, $bufferSize );
353 if ( !xml_parse( $parser, $chunk, feof( $input ) ) ) {
354 wfDebug( "TextDumpPass::readDump encountered XML parsing error\n" );
356 $byte = xml_get_current_byte_index( $parser );
357 $msg = wfMessage( 'xml-error-string',
358 'XML import parse failure',
359 xml_get_current_line_number( $parser ),
360 xml_get_current_column_number( $parser ),
361 $byte . ( is_null( $chunk ) ? null : ( '; "' . substr( $chunk, $byte -$offset, 16 ) . '"' ) ),
362 xml_error_string( xml_get_error_code( $parser ) ) )->escaped();
364 xml_parser_free( $parser );
366 throw new MWException( $msg );
368 $offset += strlen( $chunk );
369 } while ( $chunk !== false && !feof( $input ) );
370 if ( $this->maxTimeAllowed ) {
371 $filenameList = (array)$this->egress->getFilenames();
372 // we wrote some stuff after last checkpoint that needs renamed
373 if ( file_exists( $filenameList[0] ) ) {
374 $newFilenames = array();
375 # we might have just written the header and footer and had no
376 # pages or revisions written... perhaps they were all deleted
377 # there's no pageID 0 so we use that. the caller is responsible
378 # for deciding what to do with a file containing only the
379 # siteinfo information and the mw tags.
380 if ( ! $this->firstPageWritten ) {
381 $firstPageID = str_pad( 0, 9, "0", STR_PAD_LEFT );
382 $lastPageID = str_pad( 0, 9, "0", STR_PAD_LEFT );
385 $firstPageID = str_pad( $this->firstPageWritten, 9, "0", STR_PAD_LEFT );
386 $lastPageID = str_pad( $this->lastPageWritten, 9, "0", STR_PAD_LEFT );
388 for ( $i = 0; $i < count( $filenameList ); $i++ ) {
389 $checkpointNameFilledIn = sprintf( $this->checkpointFiles[$i], $firstPageID, $lastPageID );
390 $fileinfo = pathinfo( $filenameList[$i] );
391 $newFilenames[] = $fileinfo['dirname'] . '/' . $checkpointNameFilledIn;
393 $this->egress->closeAndRename( $newFilenames );
396 xml_parser_free( $parser );
402 * Tries to get the revision text for a revision id.
404 * Upon errors, retries (Up to $this->maxFailures tries each call).
405 * If still no good revision get could be found even after this retrying, "" is returned.
406 * If no good revision text could be returned for
407 * $this->maxConsecutiveFailedTextRetrievals consecutive calls to getText, MWException
410 * @param $id string The revision id to get the text for
412 * @return string The revision text for $id, or ""
413 * @throws MWException
415 function getText( $id ) {
416 $prefetchNotTried = true; // Whether or not we already tried to get the text via prefetch.
417 $text = false; // The candidate for a good text. false if no proper value.
418 $failures = 0; // The number of times, this invocation of getText already failed.
420 static $consecutiveFailedTextRetrievals = 0; // The number of times getText failed without
421 // yielding a good text in between.
425 // To allow to simply return on success and do not have to worry about book keeping,
426 // we assume, this fetch works (possible after some retries). Nevertheless, we koop
427 // the old value, so we can restore it, if problems occur (See after the while loop).
428 $oldConsecutiveFailedTextRetrievals = $consecutiveFailedTextRetrievals;
429 $consecutiveFailedTextRetrievals = 0;
431 while ( $failures < $this->maxFailures ) {
433 // As soon as we found a good text for the $id, we will return immediately.
434 // Hence, if we make it past the try catch block, we know that we did not
438 // Step 1: Get some text (or reuse from previous iteratuon if checking
439 // for plausibility failed)
441 // Trying to get prefetch, if it has not been tried before
442 if ( $text === false && isset( $this->prefetch ) && $prefetchNotTried ) {
443 $prefetchNotTried = false;
444 $tryIsPrefetch = true;
445 $text = $this->prefetch->prefetch( intval( $this->thisPage ),
446 intval( $this->thisRev ) );
447 if ( $text === null ) {
452 if ( $text === false ) {
453 // Fallback to asking the database
454 $tryIsPrefetch = false;
455 if ( $this->spawn ) {
456 $text = $this->getTextSpawned( $id );
458 $text = $this->getTextDb( $id );
461 // No more checks for texts from DB for now.
462 // If we received something that is not false,
463 // We treat it as good text, regardless of whether it actually is or is not
464 if ( $text !== false ) {
469 if ( $text === false ) {
470 throw new MWException( "Generic error while obtaining text for id " . $id );
473 // We received a good candidate for the text of $id via some method
475 // Step 2: Checking for plausibility and return the text if it is
477 $revID = intval( $this->thisRev );
478 if ( ! isset( $this->db ) ) {
479 throw new MWException( "No database available" );
481 $revLength = $this->db->selectField( 'revision', 'rev_len', array( 'rev_id' => $revID ) );
482 if ( strlen( $text ) == $revLength ) {
483 if ( $tryIsPrefetch ) {
484 $this->prefetchCount++;
490 throw new MWException( "Received text is unplausible for id " . $id );
492 } catch ( Exception $e ) {
493 $msg = "getting/checking text " . $id . " failed (" . $e->getMessage() . ")";
494 if ( $failures + 1 < $this->maxFailures ) {
495 $msg .= " (Will retry " . ( $this->maxFailures - $failures - 1 ) . " more times)";
497 $this->progress( $msg );
500 // Something went wrong; we did not a text that was plausible :(
503 // A failure in a prefetch hit does not warrant resetting db connection etc.
504 if ( ! $tryIsPrefetch ) {
505 // After backing off for some time, we try to reboot the whole process as
506 // much as possible to not carry over failures from one part to the other
508 sleep( $this->failureTimeout );
511 if ( $this->spawn ) {
515 } catch ( Exception $e ) {
516 $this->progress( "Rebooting getText infrastructure failed (" . $e->getMessage() . ")" .
517 " Trying to continue anyways" );
522 // Retirieving a good text for $id failed (at least) maxFailures times.
523 // We abort for this $id.
525 // Restoring the consecutive failures, and maybe aborting, if the dump
527 $consecutiveFailedTextRetrievals = $oldConsecutiveFailedTextRetrievals + 1;
528 if ( $consecutiveFailedTextRetrievals > $this->maxConsecutiveFailedTextRetrievals ) {
529 throw new MWException( "Graceful storage failure" );
537 * May throw a database error if, say, the server dies during query.
539 * @return bool|string
540 * @throws MWException
542 private function getTextDb( $id ) {
544 if ( ! isset( $this->db ) ) {
545 throw new MWException( __METHOD__ . "No database available" );
547 $row = $this->db->selectRow( 'text',
548 array( 'old_text', 'old_flags' ),
549 array( 'old_id' => $id ),
551 $text = Revision::getRevisionText( $row );
552 if ( $text === false ) {
555 $stripped = str_replace( "\r", "", $text );
556 $normalized = $wgContLang->normalize( $stripped );
560 private function getTextSpawned( $id ) {
561 wfSuppressWarnings();
562 if ( !$this->spawnProc ) {
566 $text = $this->getTextSpawnedOnce( $id );
571 function openSpawn() {
574 if ( file_exists( "$IP/../multiversion/MWScript.php" ) ) {
576 array_map( 'wfEscapeShellArg',
579 "$IP/../multiversion/MWScript.php",
581 '--wiki', wfWikiID() ) ) );
585 array_map( 'wfEscapeShellArg',
588 "$IP/maintenance/fetchText.php",
589 '--wiki', wfWikiID() ) ) );
592 0 => array( "pipe", "r" ),
593 1 => array( "pipe", "w" ),
594 2 => array( "file", "/dev/null", "a" ) );
597 $this->progress( "Spawning database subprocess: $cmd" );
598 $this->spawnProc = proc_open( $cmd, $spec, $pipes );
599 if ( !$this->spawnProc ) {
601 $this->progress( "Subprocess spawn failed." );
605 $this->spawnWrite, // -> stdin
606 $this->spawnRead, // <- stdout
612 private function closeSpawn() {
613 wfSuppressWarnings();
614 if ( $this->spawnRead )
615 fclose( $this->spawnRead );
616 $this->spawnRead = false;
617 if ( $this->spawnWrite )
618 fclose( $this->spawnWrite );
619 $this->spawnWrite = false;
620 if ( $this->spawnErr )
621 fclose( $this->spawnErr );
622 $this->spawnErr = false;
623 if ( $this->spawnProc )
624 pclose( $this->spawnProc );
625 $this->spawnProc = false;
629 private function getTextSpawnedOnce( $id ) {
632 $ok = fwrite( $this->spawnWrite, "$id\n" );
633 // $this->progress( ">> $id" );
634 if ( !$ok ) return false;
636 $ok = fflush( $this->spawnWrite );
637 // $this->progress( ">> [flush]" );
638 if ( !$ok ) return false;
640 // check that the text id they are sending is the one we asked for
641 // this avoids out of sync revision text errors we have encountered in the past
642 $newId = fgets( $this->spawnRead );
643 if ( $newId === false ) {
646 if ( $id != intval( $newId ) ) {
650 $len = fgets( $this->spawnRead );
651 // $this->progress( "<< " . trim( $len ) );
652 if ( $len === false ) return false;
654 $nbytes = intval( $len );
655 // actual error, not zero-length text
656 if ( $nbytes < 0 ) return false;
660 // Subprocess may not send everything at once, we have to loop.
661 while ( $nbytes > strlen( $text ) ) {
662 $buffer = fread( $this->spawnRead, $nbytes - strlen( $text ) );
663 if ( $buffer === false ) break;
667 $gotbytes = strlen( $text );
668 if ( $gotbytes != $nbytes ) {
669 $this->progress( "Expected $nbytes bytes from database subprocess, got $gotbytes " );
673 // Do normalization in the dump thread...
674 $stripped = str_replace( "\r", "", $text );
675 $normalized = $wgContLang->normalize( $stripped );
679 function startElement( $parser, $name, $attribs ) {
680 $this->checkpointJustWritten = false;
682 $this->clearOpenElement( null );
683 $this->lastName = $name;
685 if ( $name == 'revision' ) {
686 $this->state = $name;
687 $this->egress->writeOpenPage( null, $this->buffer );
689 } elseif ( $name == 'page' ) {
690 $this->state = $name;
691 if ( $this->atStart ) {
692 $this->egress->writeOpenStream( $this->buffer );
694 $this->atStart = false;
698 if ( $name == "text" && isset( $attribs['id'] ) ) {
699 $text = $this->getText( $attribs['id'] );
700 $this->openElement = array( $name, array( 'xml:space' => 'preserve' ) );
701 if ( strlen( $text ) > 0 ) {
702 $this->characterData( $parser, $text );
705 $this->openElement = array( $name, $attribs );
709 function endElement( $parser, $name ) {
710 $this->checkpointJustWritten = false;
712 if ( $this->openElement ) {
713 $this->clearOpenElement( "" );
715 $this->buffer .= "</$name>";
718 if ( $name == 'revision' ) {
719 $this->egress->writeRevision( null, $this->buffer );
722 } elseif ( $name == 'page' ) {
723 if ( ! $this->firstPageWritten ) {
724 $this->firstPageWritten = trim( $this->thisPage );
726 $this->lastPageWritten = trim( $this->thisPage );
727 if ( $this->timeExceeded ) {
728 $this->egress->writeClosePage( $this->buffer );
729 // nasty hack, we can't just write the chardata after the
730 // page tag, it will include leading blanks from the next line
731 $this->egress->sink->write( "\n" );
733 $this->buffer = $this->xmlwriterobj->closeStream();
734 $this->egress->writeCloseStream( $this->buffer );
737 $this->thisPage = "";
738 // this could be more than one file if we had more than one output arg
740 $filenameList = (array)$this->egress->getFilenames();
741 $newFilenames = array();
742 $firstPageID = str_pad( $this->firstPageWritten, 9, "0", STR_PAD_LEFT );
743 $lastPageID = str_pad( $this->lastPageWritten, 9, "0", STR_PAD_LEFT );
744 for ( $i = 0; $i < count( $filenameList ); $i++ ) {
745 $checkpointNameFilledIn = sprintf( $this->checkpointFiles[$i], $firstPageID, $lastPageID );
746 $fileinfo = pathinfo( $filenameList[$i] );
747 $newFilenames[] = $fileinfo['dirname'] . '/' . $checkpointNameFilledIn;
749 $this->egress->closeRenameAndReopen( $newFilenames );
750 $this->buffer = $this->xmlwriterobj->openStream();
751 $this->timeExceeded = false;
752 $this->timeOfCheckpoint = $this->lastTime;
753 $this->firstPageWritten = false;
754 $this->checkpointJustWritten = true;
757 $this->egress->writeClosePage( $this->buffer );
759 $this->thisPage = "";
762 } elseif ( $name == 'mediawiki' ) {
763 $this->egress->writeCloseStream( $this->buffer );
768 function characterData( $parser, $data ) {
769 $this->clearOpenElement( null );
770 if ( $this->lastName == "id" ) {
771 if ( $this->state == "revision" ) {
772 $this->thisRev .= $data;
773 } elseif ( $this->state == "page" ) {
774 $this->thisPage .= $data;
777 // have to skip the newline left over from closepagetag line of
778 // end of checkpoint files. nasty hack!!
779 if ( $this->checkpointJustWritten ) {
780 if ( $data[0] == "\n" ) {
781 $data = substr( $data, 1 );
783 $this->checkpointJustWritten = false;
785 $this->buffer .= htmlspecialchars( $data );
788 function clearOpenElement( $style ) {
789 if ( $this->openElement ) {
790 $this->buffer .= Xml::element( $this->openElement[0], $this->openElement[1], $style );
791 $this->openElement = false;