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
29 * @ingroup Maintenance
31 class TextPassDumper extends BackupDumper {
33 var $input = "php://stdin";
34 var $history = WikiExporter::FULL;
36 var $prefetchCount = 0;
37 var $prefetchCountLast = 0;
38 var $fetchCountLast = 0;
41 var $maxConsecutiveFailedTextRetrievals = 200;
42 var $failureTimeout = 5; // Seconds to sleep after db failure
50 var $spawnProc = false;
55 var $spawnWrite = false;
60 var $spawnRead = false;
65 var $spawnErr = false;
67 var $xmlwriterobj = false;
69 // when we spend more than maxTimeAllowed seconds on this run, we continue
70 // processing until we write out the next complete page, then save output file(s),
71 // rename it/them and open new one(s)
72 var $maxTimeAllowed = 0; // 0 = no limit
73 var $timeExceeded = false;
74 var $firstPageWritten = false;
75 var $lastPageWritten = false;
76 var $checkpointJustWritten = false;
77 var $checkpointFiles = array();
86 * Drop the database connection $this->db and try to get a new one.
88 * This function tries to get a /different/ connection if this is
89 * possible. Hence, (if this is possible) it switches to a different
90 * failover upon each call.
92 * This function resets $this->lb and closes all connections on it.
97 // Cleaning up old connections
98 if ( isset( $this->lb ) ) {
99 $this->lb->closeAll();
103 if ( $this->forcedDb !== null ) {
104 $this->db = $this->forcedDb;
108 if ( isset( $this->db ) && $this->db->isOpen() ) {
109 throw new MWException( 'DB is set and has not been closed by the Load Balancer' );
114 // Trying to set up new connection.
115 // We do /not/ retry upon failure, but delegate to encapsulating logic, to avoid
116 // individually retrying at different layers of code.
118 // 1. The LoadBalancer.
120 $this->lb = wfGetLBFactory()->newMainLB();
121 } catch ( Exception $e ) {
122 throw new MWException( __METHOD__ . " rotating DB failed to obtain new load balancer (" . $e->getMessage() . ")" );
126 // 2. The Connection, through the load balancer.
128 $this->db = $this->lb->getConnection( DB_SLAVE, 'backup' );
129 } catch ( Exception $e ) {
130 throw new MWException( __METHOD__ . " rotating DB failed to obtain new database (" . $e->getMessage() . ")" );
135 function initProgress( $history = WikiExporter::FULL ) {
136 parent::initProgress();
137 $this->timeOfCheckpoint = $this->startTime;
140 function dump( $history, $text = WikiExporter::TEXT ) {
141 // Notice messages will foul up your XML output even if they're
142 // relatively harmless.
143 if ( ini_get( 'display_errors' ) )
144 ini_set( 'display_errors', 'stderr' );
146 $this->initProgress( $this->history );
148 // We are trying to get an initial database connection to avoid that the
149 // first try of this request's first call to getText fails. However, if
150 // obtaining a good DB connection fails it's not a serious issue, as
151 // getText does retry upon failure and can start without having a working
155 } catch ( Exception $e ) {
156 // We do not even count this as failure. Just let eventual
158 $this->progress( "Getting initial DB connection failed (" .
159 $e->getMessage() . ")" );
162 $this->egress = new ExportProgressFilter( $this->sink, $this );
164 // it would be nice to do it in the constructor, oh well. need egress set
165 $this->finalOptionCheck();
167 // we only want this so we know how to close a stream :-P
168 $this->xmlwriterobj = new XmlDumpWriter();
170 $input = fopen( $this->input, "rt" );
171 $result = $this->readDump( $input );
173 if ( WikiError::isError( $result ) ) {
174 throw new MWException( $result->getMessage() );
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 );
243 * Overridden to include prefetch ratio if enabled.
245 function showReport() {
246 if ( !$this->prefetch ) {
247 parent::showReport();
251 if ( $this->reporting ) {
252 $now = wfTimestamp( TS_DB );
254 $deltaAll = wfTime() - $this->startTime;
255 $deltaPart = wfTime() - $this->lastTime;
256 $this->pageCountPart = $this->pageCount - $this->pageCountLast;
257 $this->revCountPart = $this->revCount - $this->revCountLast;
260 $portion = $this->revCount / $this->maxCount;
261 $eta = $this->startTime + $deltaAll / $portion;
262 $etats = wfTimestamp( TS_DB, intval( $eta ) );
263 if ( $this->fetchCount ) {
264 $fetchRate = 100.0 * $this->prefetchCount / $this->fetchCount;
268 $pageRate = $this->pageCount / $deltaAll;
269 $revRate = $this->revCount / $deltaAll;
277 if ( $this->fetchCountLast ) {
278 $fetchRatePart = 100.0 * $this->prefetchCountLast / $this->fetchCountLast;
280 $fetchRatePart = '-';
282 $pageRatePart = $this->pageCountPart / $deltaPart;
283 $revRatePart = $this->revCountPart / $deltaPart;
286 $fetchRatePart = '-';
290 $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]",
291 $now, wfWikiID(), $this->ID, $this->pageCount, $pageRate, $pageRatePart, $this->revCount, $revRate, $revRatePart, $fetchRate, $fetchRatePart, $etats, $this->maxCount ) );
292 $this->lastTime = $nowts;
293 $this->revCountLast = $this->revCount;
294 $this->prefetchCountLast = $this->prefetchCount;
295 $this->fetchCountLast = $this->fetchCount;
299 function setTimeExceeded() {
300 $this->timeExceeded = True;
303 function checkIfTimeExceeded() {
304 if ( $this->maxTimeAllowed && ( $this->lastTime - $this->timeOfCheckpoint > $this->maxTimeAllowed ) ) {
310 function finalOptionCheck() {
311 if ( ( $this->checkpointFiles && ! $this->maxTimeAllowed ) ||
312 ( $this->maxTimeAllowed && !$this->checkpointFiles ) ) {
313 throw new MWException( "Options checkpointfile and maxtime must be specified together.\n" );
315 foreach ( $this->checkpointFiles as $checkpointFile ) {
316 $count = substr_count ( $checkpointFile, "%s" );
318 throw new MWException( "Option checkpointfile must contain two '%s' for substitution of first and last pageids, count is $count instead, file is $checkpointFile.\n" );
322 if ( $this->checkpointFiles ) {
323 $filenameList = (array)$this->egress->getFilenames();
324 if ( count( $filenameList ) != count( $this->checkpointFiles ) ) {
325 throw new MWException( "One checkpointfile must be specified for each output option, if maxtime is used.\n" );
330 function readDump( $input ) {
332 $this->openElement = false;
333 $this->atStart = true;
335 $this->lastName = "";
339 $parser = xml_parser_create( "UTF-8" );
340 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
342 xml_set_element_handler( $parser, array( &$this, 'startElement' ), array( &$this, 'endElement' ) );
343 xml_set_character_data_handler( $parser, array( &$this, 'characterData' ) );
345 $offset = 0; // for context extraction on error reporting
346 $bufferSize = 512 * 1024;
348 if ( $this->checkIfTimeExceeded() ) {
349 $this->setTimeExceeded();
351 $chunk = fread( $input, $bufferSize );
352 if ( !xml_parse( $parser, $chunk, feof( $input ) ) ) {
353 wfDebug( "TextDumpPass::readDump encountered XML parsing error\n" );
354 return new WikiXmlError( $parser, 'XML import parse failure', $chunk, $offset );
356 $offset += strlen( $chunk );
357 } while ( $chunk !== false && !feof( $input ) );
358 if ( $this->maxTimeAllowed ) {
359 $filenameList = (array)$this->egress->getFilenames();
360 // we wrote some stuff after last checkpoint that needs renamed
361 if ( file_exists( $filenameList[0] ) ) {
362 $newFilenames = array();
363 # we might have just written the header and footer and had no
364 # pages or revisions written... perhaps they were all deleted
365 # there's no pageID 0 so we use that. the caller is responsible
366 # for deciding what to do with a file containing only the
367 # siteinfo information and the mw tags.
368 if ( ! $this->firstPageWritten ) {
369 $firstPageID = str_pad( 0, 9, "0", STR_PAD_LEFT );
370 $lastPageID = str_pad( 0, 9, "0", STR_PAD_LEFT );
373 $firstPageID = str_pad( $this->firstPageWritten, 9, "0", STR_PAD_LEFT );
374 $lastPageID = str_pad( $this->lastPageWritten, 9, "0", STR_PAD_LEFT );
376 for ( $i = 0; $i < count( $filenameList ); $i++ ) {
377 $checkpointNameFilledIn = sprintf( $this->checkpointFiles[$i], $firstPageID, $lastPageID );
378 $fileinfo = pathinfo( $filenameList[$i] );
379 $newFilenames[] = $fileinfo['dirname'] . '/' . $checkpointNameFilledIn;
381 $this->egress->closeAndRename( $newFilenames );
384 xml_parser_free( $parser );
390 * Tries to get the revision text for a revision id.
392 * Upon errors, retries (Up to $this->maxFailures tries each call).
393 * If still no good revision get could be found even after this retrying, "" is returned.
394 * If no good revision text could be returned for
395 * $this->maxConsecutiveFailedTextRetrievals consecutive calls to getText, MWException
398 * @param $id string The revision id to get the text for
400 * @return string The revision text for $id, or ""
401 * @throws MWException
403 function getText( $id ) {
404 $prefetchNotTried = true; // Whether or not we already tried to get the text via prefetch.
405 $text = false; // The candidate for a good text. false if no proper value.
406 $failures = 0; // The number of times, this invocation of getText already failed.
408 static $consecutiveFailedTextRetrievals = 0; // The number of times getText failed without
409 // yielding a good text in between.
413 // To allow to simply return on success and do not have to worry about book keeping,
414 // we assume, this fetch works (possible after some retries). Nevertheless, we koop
415 // the old value, so we can restore it, if problems occur (See after the while loop).
416 $oldConsecutiveFailedTextRetrievals = $consecutiveFailedTextRetrievals;
417 $consecutiveFailedTextRetrievals = 0;
419 while ( $failures < $this->maxFailures ) {
421 // As soon as we found a good text for the $id, we will return immediately.
422 // Hence, if we make it past the try catch block, we know that we did not
426 // Step 1: Get some text (or reuse from previous iteratuon if checking
427 // for plausibility failed)
429 // Trying to get prefetch, if it has not been tried before
430 if ( $text === false && isset( $this->prefetch ) && $prefetchNotTried ) {
431 $prefetchNotTried = false;
432 $tryIsPrefetch = true;
433 $text = $this->prefetch->prefetch( $this->thisPage, $this->thisRev );
434 if ( $text === null ) {
439 if ( $text === false ) {
440 // Fallback to asking the database
441 $tryIsPrefetch = false;
442 if ( $this->spawn ) {
443 $text = $this->getTextSpawned( $id );
445 $text = $this->getTextDb( $id );
449 if ( $text === false ) {
450 throw new MWException( "Generic error while obtaining text for id " . $id );
453 // We received a good candidate for the text of $id via some method
455 // Step 2: Checking for plausibility and return the text if it is
457 $revID = intval( $this->thisRev );
458 if ( ! isset( $this->db ) ) {
459 throw new MWException( "No database available" );
461 $revLength = $this->db->selectField( 'revision', 'rev_len', array( 'rev_id' => $revID ) );
462 if ( strlen( $text ) == $revLength ) {
463 if ( $tryIsPrefetch ) {
464 $this->prefetchCount++;
470 throw new MWException( "Received text is unplausible for id " . $id );
472 } catch ( Exception $e ) {
473 $msg = "getting/checking text " . $id . " failed (" . $e->getMessage() . ")";
474 if ( $failures + 1 < $this->maxFailures ) {
475 $msg .= " (Will retry " . ( $this->maxFailures - $failures - 1 ) . " more times)";
477 $this->progress( $msg );
480 // Something went wrong; we did not a text that was plausible :(
484 // After backing off for some time, we try to reboot the whole process as
485 // much as possible to not carry over failures from one part to the other
487 sleep( $this->failureTimeout );
490 if ( $this->spawn ) {
494 } catch ( Exception $e ) {
495 $this->progress( "Rebooting getText infrastructure failed (" . $e->getMessage() . ")" .
496 " Trying to continue anyways" );
500 // Retirieving a good text for $id failed (at least) maxFailures times.
501 // We abort for this $id.
503 // Restoring the consecutive failures, and maybe aborting, if the dump
505 $consecutiveFailedTextRetrievals = $oldConsecutiveFailedTextRetrievals + 1;
506 if ( $consecutiveFailedTextRetrievals > $this->maxConsecutiveFailedTextRetrievals ) {
507 throw new MWException( "Graceful storage failure" );
515 * May throw a database error if, say, the server dies during query.
517 * @return bool|string
518 * @throws MWException
520 private function getTextDb( $id ) {
522 if ( ! isset( $this->db ) ) {
523 throw new MWException( __METHOD__ . "No database available" );
525 $row = $this->db->selectRow( 'text',
526 array( 'old_text', 'old_flags' ),
527 array( 'old_id' => $id ),
529 $text = Revision::getRevisionText( $row );
530 if ( $text === false ) {
533 $stripped = str_replace( "\r", "", $text );
534 $normalized = $wgContLang->normalize( $stripped );
538 private function getTextSpawned( $id ) {
539 wfSuppressWarnings();
540 if ( !$this->spawnProc ) {
544 $text = $this->getTextSpawnedOnce( $id );
549 function openSpawn() {
552 if ( file_exists( "$IP/../multiversion/MWScript.php" ) ) {
554 array_map( 'wfEscapeShellArg',
557 "$IP/../multiversion/MWScript.php",
559 '--wiki', wfWikiID() ) ) );
563 array_map( 'wfEscapeShellArg',
566 "$IP/maintenance/fetchText.php",
567 '--wiki', wfWikiID() ) ) );
570 0 => array( "pipe", "r" ),
571 1 => array( "pipe", "w" ),
572 2 => array( "file", "/dev/null", "a" ) );
575 $this->progress( "Spawning database subprocess: $cmd" );
576 $this->spawnProc = proc_open( $cmd, $spec, $pipes );
577 if ( !$this->spawnProc ) {
579 $this->progress( "Subprocess spawn failed." );
583 $this->spawnWrite, // -> stdin
584 $this->spawnRead, // <- stdout
590 private function closeSpawn() {
591 wfSuppressWarnings();
592 if ( $this->spawnRead )
593 fclose( $this->spawnRead );
594 $this->spawnRead = false;
595 if ( $this->spawnWrite )
596 fclose( $this->spawnWrite );
597 $this->spawnWrite = false;
598 if ( $this->spawnErr )
599 fclose( $this->spawnErr );
600 $this->spawnErr = false;
601 if ( $this->spawnProc )
602 pclose( $this->spawnProc );
603 $this->spawnProc = false;
607 private function getTextSpawnedOnce( $id ) {
610 $ok = fwrite( $this->spawnWrite, "$id\n" );
611 // $this->progress( ">> $id" );
612 if ( !$ok ) return false;
614 $ok = fflush( $this->spawnWrite );
615 // $this->progress( ">> [flush]" );
616 if ( !$ok ) return false;
618 // check that the text id they are sending is the one we asked for
619 // this avoids out of sync revision text errors we have encountered in the past
620 $newId = fgets( $this->spawnRead );
621 if ( $newId === false ) {
624 if ( $id != intval( $newId ) ) {
628 $len = fgets( $this->spawnRead );
629 // $this->progress( "<< " . trim( $len ) );
630 if ( $len === false ) return false;
632 $nbytes = intval( $len );
633 // actual error, not zero-length text
634 if ( $nbytes < 0 ) return false;
638 // Subprocess may not send everything at once, we have to loop.
639 while ( $nbytes > strlen( $text ) ) {
640 $buffer = fread( $this->spawnRead, $nbytes - strlen( $text ) );
641 if ( $buffer === false ) break;
645 $gotbytes = strlen( $text );
646 if ( $gotbytes != $nbytes ) {
647 $this->progress( "Expected $nbytes bytes from database subprocess, got $gotbytes " );
651 // Do normalization in the dump thread...
652 $stripped = str_replace( "\r", "", $text );
653 $normalized = $wgContLang->normalize( $stripped );
657 function startElement( $parser, $name, $attribs ) {
658 $this->checkpointJustWritten = false;
660 $this->clearOpenElement( null );
661 $this->lastName = $name;
663 if ( $name == 'revision' ) {
664 $this->state = $name;
665 $this->egress->writeOpenPage( null, $this->buffer );
667 } elseif ( $name == 'page' ) {
668 $this->state = $name;
669 if ( $this->atStart ) {
670 $this->egress->writeOpenStream( $this->buffer );
672 $this->atStart = false;
676 if ( $name == "text" && isset( $attribs['id'] ) ) {
677 $text = $this->getText( $attribs['id'] );
678 $this->openElement = array( $name, array( 'xml:space' => 'preserve' ) );
679 if ( strlen( $text ) > 0 ) {
680 $this->characterData( $parser, $text );
683 $this->openElement = array( $name, $attribs );
687 function endElement( $parser, $name ) {
688 $this->checkpointJustWritten = false;
690 if ( $this->openElement ) {
691 $this->clearOpenElement( "" );
693 $this->buffer .= "</$name>";
696 if ( $name == 'revision' ) {
697 $this->egress->writeRevision( null, $this->buffer );
700 } elseif ( $name == 'page' ) {
701 if ( ! $this->firstPageWritten ) {
702 $this->firstPageWritten = trim( $this->thisPage );
704 $this->lastPageWritten = trim( $this->thisPage );
705 if ( $this->timeExceeded ) {
706 $this->egress->writeClosePage( $this->buffer );
707 // nasty hack, we can't just write the chardata after the
708 // page tag, it will include leading blanks from the next line
709 $this->egress->sink->write( "\n" );
711 $this->buffer = $this->xmlwriterobj->closeStream();
712 $this->egress->writeCloseStream( $this->buffer );
715 $this->thisPage = "";
716 // this could be more than one file if we had more than one output arg
718 $filenameList = (array)$this->egress->getFilenames();
719 $newFilenames = array();
720 $firstPageID = str_pad( $this->firstPageWritten, 9, "0", STR_PAD_LEFT );
721 $lastPageID = str_pad( $this->lastPageWritten, 9, "0", STR_PAD_LEFT );
722 for ( $i = 0; $i < count( $filenameList ); $i++ ) {
723 $checkpointNameFilledIn = sprintf( $this->checkpointFiles[$i], $firstPageID, $lastPageID );
724 $fileinfo = pathinfo( $filenameList[$i] );
725 $newFilenames[] = $fileinfo['dirname'] . '/' . $checkpointNameFilledIn;
727 $this->egress->closeRenameAndReopen( $newFilenames );
728 $this->buffer = $this->xmlwriterobj->openStream();
729 $this->timeExceeded = false;
730 $this->timeOfCheckpoint = $this->lastTime;
731 $this->firstPageWritten = false;
732 $this->checkpointJustWritten = true;
735 $this->egress->writeClosePage( $this->buffer );
737 $this->thisPage = "";
740 } elseif ( $name == 'mediawiki' ) {
741 $this->egress->writeCloseStream( $this->buffer );
746 function characterData( $parser, $data ) {
747 $this->clearOpenElement( null );
748 if ( $this->lastName == "id" ) {
749 if ( $this->state == "revision" ) {
750 $this->thisRev .= $data;
751 } elseif ( $this->state == "page" ) {
752 $this->thisPage .= $data;
755 // have to skip the newline left over from closepagetag line of
756 // end of checkpoint files. nasty hack!!
757 if ( $this->checkpointJustWritten ) {
758 if ( $data[0] == "\n" ) {
759 $data = substr( $data, 1 );
761 $this->checkpointJustWritten = false;
763 $this->buffer .= htmlspecialchars( $data );
766 function clearOpenElement( $style ) {
767 if ( $this->openElement ) {
768 $this->buffer .= Xml::element( $this->openElement[0], $this->openElement[1], $style );
769 $this->openElement = false;