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;
34 protected $input = "php://stdin";
35 protected $history = WikiExporter::FULL;
36 protected $fetchCount = 0;
37 protected $prefetchCount = 0;
38 protected $prefetchCountLast = 0;
39 protected $fetchCountLast = 0;
41 protected $maxFailures = 5;
42 protected $maxConsecutiveFailedTextRetrievals = 200;
43 protected $failureTimeout = 5; // Seconds to sleep after db failure
45 protected $php = "php";
46 protected $spawn = false;
51 protected $spawnProc = false;
56 protected $spawnWrite = false;
61 protected $spawnRead = false;
66 protected $spawnErr = false;
68 protected $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 protected $maxTimeAllowed = 0; // 0 = no limit
74 protected $timeExceeded = false;
75 protected $firstPageWritten = false;
76 protected $lastPageWritten = false;
77 protected $checkpointJustWritten = false;
78 protected $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;
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__
124 . " 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, 'dump' );
130 } catch ( Exception $e ) {
131 throw new MWException( __METHOD__
132 . " 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 );
242 * Overridden to include prefetch ratio if enabled.
244 function showReport() {
245 if ( !$this->prefetch ) {
246 parent::showReport();
251 if ( $this->reporting ) {
252 $now = wfTimestamp( TS_DB );
253 $nowts = microtime( true );
254 $deltaAll = $nowts - $this->startTime;
255 $deltaPart = $nowts - $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;
285 $fetchRatePart = '-';
289 $this->progress( sprintf(
290 "%s: %s (ID %d) %d pages (%0.1f|%0.1f/sec all|curr), "
291 . "%d revs (%0.1f|%0.1f/sec all|curr), %0.1f%%|%0.1f%% "
292 . "prefetched (all|curr), ETA %s [max %d]",
293 $now, wfWikiID(), $this->ID, $this->pageCount, $pageRate,
294 $pageRatePart, $this->revCount, $revRate, $revRatePart,
295 $fetchRate, $fetchRatePart, $etats, $this->maxCount
297 $this->lastTime = $nowts;
298 $this->revCountLast = $this->revCount;
299 $this->prefetchCountLast = $this->prefetchCount;
300 $this->fetchCountLast = $this->fetchCount;
304 function setTimeExceeded() {
305 $this->timeExceeded = true;
308 function checkIfTimeExceeded() {
309 if ( $this->maxTimeAllowed
310 && ( $this->lastTime - $this->timeOfCheckpoint > $this->maxTimeAllowed )
318 function finalOptionCheck() {
319 if ( ( $this->checkpointFiles && !$this->maxTimeAllowed )
320 || ( $this->maxTimeAllowed && !$this->checkpointFiles )
322 throw new MWException( "Options checkpointfile and maxtime must be specified together.\n" );
324 foreach ( $this->checkpointFiles as $checkpointFile ) {
325 $count = substr_count( $checkpointFile, "%s" );
327 throw new MWException( "Option checkpointfile must contain two '%s' "
328 . "for substitution of first and last pageids, count is $count instead, "
329 . "file is $checkpointFile.\n" );
333 if ( $this->checkpointFiles ) {
334 $filenameList = (array)$this->egress->getFilenames();
335 if ( count( $filenameList ) != count( $this->checkpointFiles ) ) {
336 throw new MWException( "One checkpointfile must be specified "
337 . "for each output option, if maxtime is used.\n" );
343 * @throws MWException Failure to parse XML input
346 function readDump( $input ) {
348 $this->openElement = false;
349 $this->atStart = true;
351 $this->lastName = "";
355 $parser = xml_parser_create( "UTF-8" );
356 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
358 xml_set_element_handler(
360 array( &$this, 'startElement' ),
361 array( &$this, 'endElement' )
363 xml_set_character_data_handler( $parser, array( &$this, 'characterData' ) );
365 $offset = 0; // for context extraction on error reporting
366 $bufferSize = 512 * 1024;
368 if ( $this->checkIfTimeExceeded() ) {
369 $this->setTimeExceeded();
371 $chunk = fread( $input, $bufferSize );
372 if ( !xml_parse( $parser, $chunk, feof( $input ) ) ) {
373 wfDebug( "TextDumpPass::readDump encountered XML parsing error\n" );
375 $byte = xml_get_current_byte_index( $parser );
376 $msg = wfMessage( 'xml-error-string',
377 'XML import parse failure',
378 xml_get_current_line_number( $parser ),
379 xml_get_current_column_number( $parser ),
380 $byte . ( is_null( $chunk ) ? null : ( '; "' . substr( $chunk, $byte - $offset, 16 ) . '"' ) ),
381 xml_error_string( xml_get_error_code( $parser ) ) )->escaped();
383 xml_parser_free( $parser );
385 throw new MWException( $msg );
387 $offset += strlen( $chunk );
388 } while ( $chunk !== false && !feof( $input ) );
389 if ( $this->maxTimeAllowed ) {
390 $filenameList = (array)$this->egress->getFilenames();
391 // we wrote some stuff after last checkpoint that needs renamed
392 if ( file_exists( $filenameList[0] ) ) {
393 $newFilenames = array();
394 # we might have just written the header and footer and had no
395 # pages or revisions written... perhaps they were all deleted
396 # there's no pageID 0 so we use that. the caller is responsible
397 # for deciding what to do with a file containing only the
398 # siteinfo information and the mw tags.
399 if ( !$this->firstPageWritten ) {
400 $firstPageID = str_pad( 0, 9, "0", STR_PAD_LEFT );
401 $lastPageID = str_pad( 0, 9, "0", STR_PAD_LEFT );
403 $firstPageID = str_pad( $this->firstPageWritten, 9, "0", STR_PAD_LEFT );
404 $lastPageID = str_pad( $this->lastPageWritten, 9, "0", STR_PAD_LEFT );
407 $filenameCount = count( $filenameList );
408 for ( $i = 0; $i < $filenameCount; $i++ ) {
409 $checkpointNameFilledIn = sprintf( $this->checkpointFiles[$i], $firstPageID, $lastPageID );
410 $fileinfo = pathinfo( $filenameList[$i] );
411 $newFilenames[] = $fileinfo['dirname'] . '/' . $checkpointNameFilledIn;
413 $this->egress->closeAndRename( $newFilenames );
416 xml_parser_free( $parser );
422 * Tries to get the revision text for a revision id.
424 * Upon errors, retries (Up to $this->maxFailures tries each call).
425 * If still no good revision get could be found even after this retrying, "" is returned.
426 * If no good revision text could be returned for
427 * $this->maxConsecutiveFailedTextRetrievals consecutive calls to getText, MWException
430 * @param string $id The revision id to get the text for
432 * @return string The revision text for $id, or ""
433 * @throws MWException
435 function getText( $id ) {
436 global $wgContentHandlerUseDB;
438 $prefetchNotTried = true; // Whether or not we already tried to get the text via prefetch.
439 $text = false; // The candidate for a good text. false if no proper value.
440 $failures = 0; // The number of times, this invocation of getText already failed.
442 // The number of times getText failed without yielding a good text in between.
443 static $consecutiveFailedTextRetrievals = 0;
447 // To allow to simply return on success and do not have to worry about book keeping,
448 // we assume, this fetch works (possible after some retries). Nevertheless, we koop
449 // the old value, so we can restore it, if problems occur (See after the while loop).
450 $oldConsecutiveFailedTextRetrievals = $consecutiveFailedTextRetrievals;
451 $consecutiveFailedTextRetrievals = 0;
453 while ( $failures < $this->maxFailures ) {
455 // As soon as we found a good text for the $id, we will return immediately.
456 // Hence, if we make it past the try catch block, we know that we did not
460 // Step 1: Get some text (or reuse from previous iteratuon if checking
461 // for plausibility failed)
463 // Trying to get prefetch, if it has not been tried before
464 if ( $text === false && isset( $this->prefetch ) && $prefetchNotTried ) {
465 $prefetchNotTried = false;
466 $tryIsPrefetch = true;
467 $text = $this->prefetch->prefetch( intval( $this->thisPage ),
468 intval( $this->thisRev ) );
469 if ( $text === null ) {
474 if ( $text === false ) {
475 // Fallback to asking the database
476 $tryIsPrefetch = false;
477 if ( $this->spawn ) {
478 $text = $this->getTextSpawned( $id );
480 $text = $this->getTextDb( $id );
483 // No more checks for texts from DB for now.
484 // If we received something that is not false,
485 // We treat it as good text, regardless of whether it actually is or is not
486 if ( $text !== false ) {
491 if ( $text === false ) {
492 throw new MWException( "Generic error while obtaining text for id " . $id );
495 // We received a good candidate for the text of $id via some method
497 // Step 2: Checking for plausibility and return the text if it is
499 $revID = intval( $this->thisRev );
500 if ( !isset( $this->db ) ) {
501 throw new MWException( "No database available" );
504 $revLength = strlen( $text );
505 if ( $wgContentHandlerUseDB ) {
506 $row = $this->db->selectRow(
508 array( 'rev_len', 'rev_content_model' ),
509 array( 'rev_id' => $revID ),
513 // only check the length for the wikitext content handler,
514 // it's a wasted (and failed) check otherwise
515 if ( $row->rev_content_model == CONTENT_MODEL_WIKITEXT ) {
516 $revLength = $row->rev_len;
520 $revLength = $this->db->selectField( 'revision', 'rev_len', array( 'rev_id' => $revID ) );
523 if ( strlen( $text ) == $revLength ) {
524 if ( $tryIsPrefetch ) {
525 $this->prefetchCount++;
532 throw new MWException( "Received text is unplausible for id " . $id );
533 } catch ( Exception $e ) {
534 $msg = "getting/checking text " . $id . " failed (" . $e->getMessage() . ")";
535 if ( $failures + 1 < $this->maxFailures ) {
536 $msg .= " (Will retry " . ( $this->maxFailures - $failures - 1 ) . " more times)";
538 $this->progress( $msg );
541 // Something went wrong; we did not a text that was plausible :(
544 // A failure in a prefetch hit does not warrant resetting db connection etc.
545 if ( !$tryIsPrefetch ) {
546 // After backing off for some time, we try to reboot the whole process as
547 // much as possible to not carry over failures from one part to the other
549 sleep( $this->failureTimeout );
552 if ( $this->spawn ) {
556 } catch ( Exception $e ) {
557 $this->progress( "Rebooting getText infrastructure failed (" . $e->getMessage() . ")" .
558 " Trying to continue anyways" );
563 // Retirieving a good text for $id failed (at least) maxFailures times.
564 // We abort for this $id.
566 // Restoring the consecutive failures, and maybe aborting, if the dump
568 $consecutiveFailedTextRetrievals = $oldConsecutiveFailedTextRetrievals + 1;
569 if ( $consecutiveFailedTextRetrievals > $this->maxConsecutiveFailedTextRetrievals ) {
570 throw new MWException( "Graceful storage failure" );
577 * May throw a database error if, say, the server dies during query.
579 * @return bool|string
580 * @throws MWException
582 private function getTextDb( $id ) {
584 if ( !isset( $this->db ) ) {
585 throw new MWException( __METHOD__ . "No database available" );
587 $row = $this->db->selectRow( 'text',
588 array( 'old_text', 'old_flags' ),
589 array( 'old_id' => $id ),
591 $text = Revision::getRevisionText( $row );
592 if ( $text === false ) {
595 $stripped = str_replace( "\r", "", $text );
596 $normalized = $wgContLang->normalize( $stripped );
601 private function getTextSpawned( $id ) {
602 wfSuppressWarnings();
603 if ( !$this->spawnProc ) {
607 $text = $this->getTextSpawnedOnce( $id );
613 function openSpawn() {
616 if ( file_exists( "$IP/../multiversion/MWScript.php" ) ) {
618 array_map( 'wfEscapeShellArg',
621 "$IP/../multiversion/MWScript.php",
623 '--wiki', wfWikiID() ) ) );
626 array_map( 'wfEscapeShellArg',
629 "$IP/maintenance/fetchText.php",
630 '--wiki', wfWikiID() ) ) );
633 0 => array( "pipe", "r" ),
634 1 => array( "pipe", "w" ),
635 2 => array( "file", "/dev/null", "a" ) );
638 $this->progress( "Spawning database subprocess: $cmd" );
639 $this->spawnProc = proc_open( $cmd, $spec, $pipes );
640 if ( !$this->spawnProc ) {
642 $this->progress( "Subprocess spawn failed." );
647 $this->spawnWrite, // -> stdin
648 $this->spawnRead, // <- stdout
654 private function closeSpawn() {
655 wfSuppressWarnings();
656 if ( $this->spawnRead ) {
657 fclose( $this->spawnRead );
659 $this->spawnRead = false;
660 if ( $this->spawnWrite ) {
661 fclose( $this->spawnWrite );
663 $this->spawnWrite = false;
664 if ( $this->spawnErr ) {
665 fclose( $this->spawnErr );
667 $this->spawnErr = false;
668 if ( $this->spawnProc ) {
669 pclose( $this->spawnProc );
671 $this->spawnProc = false;
675 private function getTextSpawnedOnce( $id ) {
678 $ok = fwrite( $this->spawnWrite, "$id\n" );
679 // $this->progress( ">> $id" );
684 $ok = fflush( $this->spawnWrite );
685 // $this->progress( ">> [flush]" );
690 // check that the text id they are sending is the one we asked for
691 // this avoids out of sync revision text errors we have encountered in the past
692 $newId = fgets( $this->spawnRead );
693 if ( $newId === false ) {
696 if ( $id != intval( $newId ) ) {
700 $len = fgets( $this->spawnRead );
701 // $this->progress( "<< " . trim( $len ) );
702 if ( $len === false ) {
706 $nbytes = intval( $len );
707 // actual error, not zero-length text
714 // Subprocess may not send everything at once, we have to loop.
715 while ( $nbytes > strlen( $text ) ) {
716 $buffer = fread( $this->spawnRead, $nbytes - strlen( $text ) );
717 if ( $buffer === false ) {
723 $gotbytes = strlen( $text );
724 if ( $gotbytes != $nbytes ) {
725 $this->progress( "Expected $nbytes bytes from database subprocess, got $gotbytes " );
730 // Do normalization in the dump thread...
731 $stripped = str_replace( "\r", "", $text );
732 $normalized = $wgContLang->normalize( $stripped );
737 function startElement( $parser, $name, $attribs ) {
738 $this->checkpointJustWritten = false;
740 $this->clearOpenElement( null );
741 $this->lastName = $name;
743 if ( $name == 'revision' ) {
744 $this->state = $name;
745 $this->egress->writeOpenPage( null, $this->buffer );
747 } elseif ( $name == 'page' ) {
748 $this->state = $name;
749 if ( $this->atStart ) {
750 $this->egress->writeOpenStream( $this->buffer );
752 $this->atStart = false;
756 if ( $name == "text" && isset( $attribs['id'] ) ) {
757 $text = $this->getText( $attribs['id'] );
758 $this->openElement = array( $name, array( 'xml:space' => 'preserve' ) );
759 if ( strlen( $text ) > 0 ) {
760 $this->characterData( $parser, $text );
763 $this->openElement = array( $name, $attribs );
767 function endElement( $parser, $name ) {
768 $this->checkpointJustWritten = false;
770 if ( $this->openElement ) {
771 $this->clearOpenElement( "" );
773 $this->buffer .= "</$name>";
776 if ( $name == 'revision' ) {
777 $this->egress->writeRevision( null, $this->buffer );
780 } elseif ( $name == 'page' ) {
781 if ( !$this->firstPageWritten ) {
782 $this->firstPageWritten = trim( $this->thisPage );
784 $this->lastPageWritten = trim( $this->thisPage );
785 if ( $this->timeExceeded ) {
786 $this->egress->writeClosePage( $this->buffer );
787 // nasty hack, we can't just write the chardata after the
788 // page tag, it will include leading blanks from the next line
789 $this->egress->sink->write( "\n" );
791 $this->buffer = $this->xmlwriterobj->closeStream();
792 $this->egress->writeCloseStream( $this->buffer );
795 $this->thisPage = "";
796 // this could be more than one file if we had more than one output arg
798 $filenameList = (array)$this->egress->getFilenames();
799 $newFilenames = array();
800 $firstPageID = str_pad( $this->firstPageWritten, 9, "0", STR_PAD_LEFT );
801 $lastPageID = str_pad( $this->lastPageWritten, 9, "0", STR_PAD_LEFT );
802 $filenamesCount = count( $filenameList );
803 for ( $i = 0; $i < $filenamesCount; $i++ ) {
804 $checkpointNameFilledIn = sprintf( $this->checkpointFiles[$i], $firstPageID, $lastPageID );
805 $fileinfo = pathinfo( $filenameList[$i] );
806 $newFilenames[] = $fileinfo['dirname'] . '/' . $checkpointNameFilledIn;
808 $this->egress->closeRenameAndReopen( $newFilenames );
809 $this->buffer = $this->xmlwriterobj->openStream();
810 $this->timeExceeded = false;
811 $this->timeOfCheckpoint = $this->lastTime;
812 $this->firstPageWritten = false;
813 $this->checkpointJustWritten = true;
815 $this->egress->writeClosePage( $this->buffer );
817 $this->thisPage = "";
819 } elseif ( $name == 'mediawiki' ) {
820 $this->egress->writeCloseStream( $this->buffer );
825 function characterData( $parser, $data ) {
826 $this->clearOpenElement( null );
827 if ( $this->lastName == "id" ) {
828 if ( $this->state == "revision" ) {
829 $this->thisRev .= $data;
830 } elseif ( $this->state == "page" ) {
831 $this->thisPage .= $data;
834 // have to skip the newline left over from closepagetag line of
835 // end of checkpoint files. nasty hack!!
836 if ( $this->checkpointJustWritten ) {
837 if ( $data[0] == "\n" ) {
838 $data = substr( $data, 1 );
840 $this->checkpointJustWritten = false;
842 $this->buffer .= htmlspecialchars( $data );
845 function clearOpenElement( $style ) {
846 if ( $this->openElement ) {
847 $this->buffer .= Xml::element( $this->openElement[0], $this->openElement[1], $style );
848 $this->openElement = false;