3 * Copyright (C) 2005 Brion Vibber <brion@pobox.com>
4 * http://www.mediawiki.org/
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 * http://www.gnu.org/copyleft/gpl.html
22 * @ingroup Maintenance
25 $originalDir = getcwd();
27 require_once( dirname( __FILE__
) . '/commandLine.inc' );
28 require_once( 'backup.inc' );
31 * @ingroup Maintenance
33 class TextPassDumper
extends BackupDumper
{
35 var $input = "php://stdin";
36 var $history = WikiExporter
::FULL
;
38 var $prefetchCount = 0;
42 var $failedTextRetrievals = 0;
43 var $maxConsecutiveFailedTextRetrievals = 200;
44 var $failureTimeout = 5; // Seconds to sleep after db failure
48 var $spawnProc = false;
49 var $spawnWrite = false;
50 var $spawnRead = false;
51 var $spawnErr = false;
54 # This shouldn't happen if on console... ;)
55 header( 'Content-type: text/html; charset=UTF-8' );
57 # Notice messages will foul up your XML output even if they're
58 # relatively harmless.
59 if ( ini_get( 'display_errors' ) )
60 ini_set( 'display_errors', 'stderr' );
62 $this->initProgress( $this->history
);
64 $this->db
= $this->backupDb();
66 $this->egress
= new ExportProgressFilter( $this->sink
, $this );
68 $input = fopen( $this->input
, "rt" );
69 $result = $this->readDump( $input );
71 if ( WikiError
::isError( $result ) ) {
72 wfDie( $result->getMessage() );
75 if ( $this->spawnProc
) {
79 $this->report( true );
82 function processOption( $opt, $val, $param ) {
83 $url = $this->processFileOpt( $val, $param );
88 require_once "$IP/maintenance/backupPrefetch.inc";
89 $this->prefetch
= new BaseDump( $url );
95 $this->history
= WikiExporter
::CURRENT
;
98 $this->history
= WikiExporter
::FULL
;
109 function processFileOpt( $val, $param ) {
114 return "compress.zlib://$param";
116 return "compress.bzip2://$param";
118 return "mediawiki.compress.7z://$param";
125 * Overridden to include prefetch ratio if enabled.
127 function showReport() {
128 if ( !$this->prefetch
) {
129 return parent
::showReport();
132 if ( $this->reporting
) {
133 $delta = wfTime() - $this->startTime
;
134 $now = wfTimestamp( TS_DB
);
136 $rate = $this->pageCount
/ $delta;
137 $revrate = $this->revCount
/ $delta;
138 $portion = $this->revCount
/ $this->maxCount
;
139 $eta = $this->startTime +
$delta / $portion;
140 $etats = wfTimestamp( TS_DB
, intval( $eta ) );
141 $fetchrate = 100.0 * $this->prefetchCount
/ $this->fetchCount
;
148 $this->progress( sprintf( "%s: %s %d pages (%0.3f/sec), %d revs (%0.3f/sec), %0.1f%% prefetched, ETA %s [max %d]",
149 $now, wfWikiID(), $this->pageCount
, $rate, $this->revCount
, $revrate, $fetchrate, $etats, $this->maxCount
) );
153 function readDump( $input ) {
155 $this->openElement
= false;
156 $this->atStart
= true;
158 $this->lastName
= "";
162 $parser = xml_parser_create( "UTF-8" );
163 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING
, false );
165 xml_set_element_handler( $parser, array( &$this, 'startElement' ), array( &$this, 'endElement' ) );
166 xml_set_character_data_handler( $parser, array( &$this, 'characterData' ) );
168 $offset = 0; // for context extraction on error reporting
169 $bufferSize = 512 * 1024;
171 $chunk = fread( $input, $bufferSize );
172 if ( !xml_parse( $parser, $chunk, feof( $input ) ) ) {
173 wfDebug( "TextDumpPass::readDump encountered XML parsing error\n" );
174 return new WikiXmlError( $parser, 'XML import parse failure', $chunk, $offset );
176 $offset +
= strlen( $chunk );
177 } while ( $chunk !== false && !feof( $input ) );
178 xml_parser_free( $parser );
183 function getText( $id ) {
185 if ( isset( $this->prefetch
) ) {
186 $text = $this->prefetch
->prefetch( $this->thisPage
, $this->thisRev
);
187 if ( $text === null ) {
188 // Entry missing from prefetch dump
189 } elseif ( $text === "" ) {
190 // Blank entries may indicate that the prior dump was broken.
191 // To be safe, reload it.
193 $dbr = wfGetDB( DB_SLAVE
);
194 $revID = intval($this->thisRev
);
195 $revLength = $dbr->selectField( 'revision', 'rev_len', array('rev_id' => $revID ) );
196 // if length of rev text in file doesn't match length in db, we reload
197 // this avoids carrying forward broken data from previous xml dumps
198 if( strlen($text) == $revLength ) {
199 $this->prefetchCount++
;
204 return $this->doGetText( $id );
207 private function doGetText( $id ) {
210 $ex = new MWException( "Graceful storage failure" );
212 if ( $this->spawn
) {
213 if ($this->failures
) {
214 // we don't know why it failed, could be the child process
215 // borked, could be db entry busted, could be db server out to lunch,
216 // so cover all bases
220 $text = $this->getTextSpawned( $id );
222 $text = $this->getTextDbSafe( $id );
224 if ( $text === false ) {
226 if ( $this->failures
> $this->maxFailures
) {
227 $this->progress( "Failed to retrieve revision text for text id ".
228 "$id after $this->maxFailures tries, giving up" );
229 // were there so many bad retrievals in a row we want to bail?
230 // at some point we have to declare the dump irretrievably broken
231 $this->failedTextRetrievals++
;
232 if ($this->failedTextRetrievals
> $this->maxConsecutiveFailedTextRetrievals
) {
236 // would be nice to return something better to the caller someday,
237 // log what we know about the failure and about the revision
241 $this->progress( "Error $this->failures " .
242 "of allowed $this->maxFailures retrieving revision text for text id $id! " .
243 "Pausing $this->failureTimeout seconds before retry..." );
244 sleep( $this->failureTimeout
);
247 $this->failedTextRetrievals
= 0;
255 * Fetch a text revision from the database, retrying in case of failure.
256 * This may survive some transitory errors by reconnecting, but
257 * may not survive a long-term server outage.
259 private function getTextDbSafe( $id ) {
262 $text = $this->getTextDb( $id );
263 $ex = new MWException( "Graceful storage failure" );
264 } catch ( DBQueryError
$ex ) {
272 * May throw a database error if, say, the server dies during query.
274 private function getTextDb( $id ) {
277 $row = $this->db
->selectRow( 'text',
278 array( 'old_text', 'old_flags' ),
279 array( 'old_id' => $id ),
280 'TextPassDumper::getText' );
281 $text = Revision
::getRevisionText( $row );
282 if ( $text === false ) {
285 $stripped = str_replace( "\r", "", $text );
286 $normalized = $wgContLang->normalize( $stripped );
290 private function getTextSpawned( $id ) {
291 wfSuppressWarnings();
292 if ( !$this->spawnProc
) {
296 $text = $this->getTextSpawnedOnce( $id );
301 function openSpawn() {
302 global $IP, $wgDBname;
305 array_map( 'wfEscapeShellArg',
308 "$IP/maintenance/fetchText.php",
311 0 => array( "pipe", "r" ),
312 1 => array( "pipe", "w" ),
313 2 => array( "file", "/dev/null", "a" ) );
316 $this->progress( "Spawning database subprocess: $cmd" );
317 $this->spawnProc
= proc_open( $cmd, $spec, $pipes );
318 if ( !$this->spawnProc
) {
320 $this->progress( "Subprocess spawn failed." );
324 $this->spawnWrite
, // -> stdin
325 $this->spawnRead
, // <- stdout
331 private function closeSpawn() {
332 wfSuppressWarnings();
333 if ( $this->spawnRead
)
334 fclose( $this->spawnRead
);
335 $this->spawnRead
= false;
336 if ( $this->spawnWrite
)
337 fclose( $this->spawnWrite
);
338 $this->spawnWrite
= false;
339 if ( $this->spawnErr
)
340 fclose( $this->spawnErr
);
341 $this->spawnErr
= false;
342 if ( $this->spawnProc
)
343 pclose( $this->spawnProc
);
344 $this->spawnProc
= false;
348 private function getTextSpawnedOnce( $id ) {
351 $ok = fwrite( $this->spawnWrite
, "$id\n" );
352 // $this->progress( ">> $id" );
353 if ( !$ok ) return false;
355 $ok = fflush( $this->spawnWrite
);
356 // $this->progress( ">> [flush]" );
357 if ( !$ok ) return false;
359 // check that the text id they are sending is the one we asked for
360 // this avoids out of sync revision text errors we have encountered in the past
361 $newId = fgets( $this->spawnRead
);
362 if ( $newId === false ) {
365 if ( $id != intval( $newId ) ) {
369 $len = fgets( $this->spawnRead
);
370 // $this->progress( "<< " . trim( $len ) );
371 if ( $len === false ) return false;
373 $nbytes = intval( $len );
374 // actual error, not zero-length text
375 if ($nbytes < 0 ) return false;
379 // Subprocess may not send everything at once, we have to loop.
380 while ( $nbytes > strlen( $text ) ) {
381 $buffer = fread( $this->spawnRead
, $nbytes - strlen( $text ) );
382 if ( $buffer === false ) break;
386 $gotbytes = strlen( $text );
387 if ( $gotbytes != $nbytes ) {
388 $this->progress( "Expected $nbytes bytes from database subprocess, got $gotbytes " );
392 // Do normalization in the dump thread...
393 $stripped = str_replace( "\r", "", $text );
394 $normalized = $wgContLang->normalize( $stripped );
398 function startElement( $parser, $name, $attribs ) {
399 $this->clearOpenElement( null );
400 $this->lastName
= $name;
402 if ( $name == 'revision' ) {
403 $this->state
= $name;
404 $this->egress
->writeOpenPage( null, $this->buffer
);
406 } elseif ( $name == 'page' ) {
407 $this->state
= $name;
408 if ( $this->atStart
) {
409 $this->egress
->writeOpenStream( $this->buffer
);
411 $this->atStart
= false;
415 if ( $name == "text" && isset( $attribs['id'] ) ) {
416 $text = $this->getText( $attribs['id'] );
417 $this->openElement
= array( $name, array( 'xml:space' => 'preserve' ) );
418 if ( strlen( $text ) > 0 ) {
419 $this->characterData( $parser, $text );
422 $this->openElement
= array( $name, $attribs );
426 function endElement( $parser, $name ) {
427 if ( $this->openElement
) {
428 $this->clearOpenElement( "" );
430 $this->buffer
.= "</$name>";
433 if ( $name == 'revision' ) {
434 $this->egress
->writeRevision( null, $this->buffer
);
437 } elseif ( $name == 'page' ) {
438 $this->egress
->writeClosePage( $this->buffer
);
440 $this->thisPage
= "";
441 } elseif ( $name == 'mediawiki' ) {
442 $this->egress
->writeCloseStream( $this->buffer
);
447 function characterData( $parser, $data ) {
448 $this->clearOpenElement( null );
449 if ( $this->lastName
== "id" ) {
450 if ( $this->state
== "revision" ) {
451 $this->thisRev
.= $data;
452 } elseif ( $this->state
== "page" ) {
453 $this->thisPage
.= $data;
456 $this->buffer
.= htmlspecialchars( $data );
459 function clearOpenElement( $style ) {
460 if ( $this->openElement
) {
461 $this->buffer
.= Xml
::element( $this->openElement
[0], $this->openElement
[1], $style );
462 $this->openElement
= false;
468 $dumper = new TextPassDumper( $argv );
473 $dumper->progress( <<<ENDS
474 This script postprocesses XML dumps from dumpBackup.php to add
475 page text which was stubbed out (using --stub).
477 XML input is accepted on stdin.
478 XML output is sent to stdout; progress reports are sent to stderr.
480 Usage: php dumpTextPass.php [<options>]
482 --stub=<type>:<file> To load a compressed stub dump instead of stdin
483 --prefetch=<type>:<file> Use a prior dump file as a text source, to save
484 pressure on the database.
485 (Requires PHP 5.0+ and the XMLReader PECL extension)
486 --quiet Don't dump status reports to stderr.
487 --report=n Report position and speed after every n pages processed.
489 --server=h Force reading from MySQL server h
490 --current Base ETA on number of pages in database instead of all revisions
491 --spawn Spawn a subprocess for loading text records