3 * Script 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 $originalDir = getcwd();
29 require_once( dirname( __FILE__
) . '/commandLine.inc' );
30 require_once( 'backup.inc' );
33 * @ingroup Maintenance
35 class TextPassDumper
extends BackupDumper
{
37 var $input = "php://stdin";
38 var $history = WikiExporter
::FULL
;
40 var $prefetchCount = 0;
44 var $failedTextRetrievals = 0;
45 var $maxConsecutiveFailedTextRetrievals = 200;
46 var $failureTimeout = 5; // Seconds to sleep after db failure
50 var $spawnProc = false;
51 var $spawnWrite = false;
52 var $spawnRead = false;
53 var $spawnErr = false;
55 function dump( $history, $text = WikiExporter
::TEXT
) {
56 # This shouldn't happen if on console... ;)
57 header( 'Content-type: text/html; charset=UTF-8' );
59 # Notice messages will foul up your XML output even if they're
60 # relatively harmless.
61 if ( ini_get( 'display_errors' ) )
62 ini_set( 'display_errors', 'stderr' );
64 $this->initProgress( $this->history
);
66 $this->db
= $this->backupDb();
68 $this->egress
= new ExportProgressFilter( $this->sink
, $this );
70 $input = fopen( $this->input
, "rt" );
71 $result = $this->readDump( $input );
73 if ( WikiError
::isError( $result ) ) {
74 wfDie( $result->getMessage() );
77 if ( $this->spawnProc
) {
81 $this->report( true );
84 function processOption( $opt, $val, $param ) {
86 $url = $this->processFileOpt( $val, $param );
90 require_once "$IP/maintenance/backupPrefetch.inc";
91 $this->prefetch
= new BaseDump( $url );
97 $this->history
= WikiExporter
::CURRENT
;
100 $this->history
= WikiExporter
::FULL
;
111 function processFileOpt( $val, $param ) {
116 return "compress.zlib://$param";
118 return "compress.bzip2://$param";
120 return "mediawiki.compress.7z://$param";
127 * Overridden to include prefetch ratio if enabled.
129 function showReport() {
130 if ( !$this->prefetch
) {
131 return parent
::showReport();
134 if ( $this->reporting
) {
135 $delta = wfTime() - $this->startTime
;
136 $now = wfTimestamp( TS_DB
);
138 $rate = $this->pageCount
/ $delta;
139 $revrate = $this->revCount
/ $delta;
140 $portion = $this->revCount
/ $this->maxCount
;
141 $eta = $this->startTime +
$delta / $portion;
142 $etats = wfTimestamp( TS_DB
, intval( $eta ) );
143 $fetchrate = 100.0 * $this->prefetchCount
/ $this->fetchCount
;
150 $this->progress( sprintf( "%s: %s %d pages (%0.3f/sec), %d revs (%0.3f/sec), %0.1f%% prefetched, ETA %s [max %d]",
151 $now, wfWikiID(), $this->pageCount
, $rate, $this->revCount
, $revrate, $fetchrate, $etats, $this->maxCount
) );
155 function readDump( $input ) {
157 $this->openElement
= false;
158 $this->atStart
= true;
160 $this->lastName
= "";
164 $parser = xml_parser_create( "UTF-8" );
165 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING
, false );
167 xml_set_element_handler( $parser, array( &$this, 'startElement' ), array( &$this, 'endElement' ) );
168 xml_set_character_data_handler( $parser, array( &$this, 'characterData' ) );
170 $offset = 0; // for context extraction on error reporting
171 $bufferSize = 512 * 1024;
173 $chunk = fread( $input, $bufferSize );
174 if ( !xml_parse( $parser, $chunk, feof( $input ) ) ) {
175 wfDebug( "TextDumpPass::readDump encountered XML parsing error\n" );
176 return new WikiXmlError( $parser, 'XML import parse failure', $chunk, $offset );
178 $offset +
= strlen( $chunk );
179 } while ( $chunk !== false && !feof( $input ) );
180 xml_parser_free( $parser );
185 function getText( $id ) {
187 if ( isset( $this->prefetch
) ) {
188 $text = $this->prefetch
->prefetch( $this->thisPage
, $this->thisRev
);
189 if ( $text === null ) {
190 // Entry missing from prefetch dump
191 } elseif ( $text === "" ) {
192 // Blank entries may indicate that the prior dump was broken.
193 // To be safe, reload it.
195 $dbr = wfGetDB( DB_SLAVE
);
196 $revID = intval($this->thisRev
);
197 $revLength = $dbr->selectField( 'revision', 'rev_len', array('rev_id' => $revID ) );
198 // if length of rev text in file doesn't match length in db, we reload
199 // this avoids carrying forward broken data from previous xml dumps
200 if( strlen($text) == $revLength ) {
201 $this->prefetchCount++
;
206 return $this->doGetText( $id );
209 private function doGetText( $id ) {
213 $ex = new MWException( "Graceful storage failure" );
215 if ( $this->spawn
) {
216 if ($this->failures
) {
217 // we don't know why it failed, could be the child process
218 // borked, could be db entry busted, could be db server out to lunch,
219 // so cover all bases
223 $text = $this->getTextSpawned( $id );
225 $text = $this->getTextDbSafe( $id );
227 if ( $text === false ) {
229 if ( $this->failures
> $this->maxFailures
) {
230 $this->progress( "Failed to retrieve revision text for text id ".
231 "$id after $this->maxFailures tries, giving up" );
232 // were there so many bad retrievals in a row we want to bail?
233 // at some point we have to declare the dump irretrievably broken
234 $this->failedTextRetrievals++
;
235 if ($this->failedTextRetrievals
> $this->maxConsecutiveFailedTextRetrievals
) {
239 // would be nice to return something better to the caller someday,
240 // log what we know about the failure and about the revision
244 $this->progress( "Error $this->failures " .
245 "of allowed $this->maxFailures retrieving revision text for text id $id! " .
246 "Pausing $this->failureTimeout seconds before retry..." );
247 sleep( $this->failureTimeout
);
250 $this->failedTextRetrievals
= 0;
258 * Fetch a text revision from the database, retrying in case of failure.
259 * This may survive some transitory errors by reconnecting, but
260 * may not survive a long-term server outage.
262 private function getTextDbSafe( $id ) {
265 $text = $this->getTextDb( $id );
266 $ex = new MWException( "Graceful storage failure" );
267 } catch ( DBQueryError
$ex ) {
275 * May throw a database error if, say, the server dies during query.
277 private function getTextDb( $id ) {
279 $row = $this->db
->selectRow( 'text',
280 array( 'old_text', 'old_flags' ),
281 array( 'old_id' => $id ),
283 $text = Revision
::getRevisionText( $row );
284 if ( $text === false ) {
287 $stripped = str_replace( "\r", "", $text );
288 $normalized = $wgContLang->normalize( $stripped );
292 private function getTextSpawned( $id ) {
293 wfSuppressWarnings();
294 if ( !$this->spawnProc
) {
298 $text = $this->getTextSpawnedOnce( $id );
303 function openSpawn() {
304 global $IP, $wgDBname;
307 array_map( 'wfEscapeShellArg',
310 "$IP/maintenance/fetchText.php",
313 0 => array( "pipe", "r" ),
314 1 => array( "pipe", "w" ),
315 2 => array( "file", "/dev/null", "a" ) );
318 $this->progress( "Spawning database subprocess: $cmd" );
319 $this->spawnProc
= proc_open( $cmd, $spec, $pipes );
320 if ( !$this->spawnProc
) {
322 $this->progress( "Subprocess spawn failed." );
326 $this->spawnWrite
, // -> stdin
327 $this->spawnRead
, // <- stdout
333 private function closeSpawn() {
334 wfSuppressWarnings();
335 if ( $this->spawnRead
)
336 fclose( $this->spawnRead
);
337 $this->spawnRead
= false;
338 if ( $this->spawnWrite
)
339 fclose( $this->spawnWrite
);
340 $this->spawnWrite
= false;
341 if ( $this->spawnErr
)
342 fclose( $this->spawnErr
);
343 $this->spawnErr
= false;
344 if ( $this->spawnProc
)
345 pclose( $this->spawnProc
);
346 $this->spawnProc
= false;
350 private function getTextSpawnedOnce( $id ) {
353 $ok = fwrite( $this->spawnWrite
, "$id\n" );
354 // $this->progress( ">> $id" );
355 if ( !$ok ) return false;
357 $ok = fflush( $this->spawnWrite
);
358 // $this->progress( ">> [flush]" );
359 if ( !$ok ) return false;
361 // check that the text id they are sending is the one we asked for
362 // this avoids out of sync revision text errors we have encountered in the past
363 $newId = fgets( $this->spawnRead
);
364 if ( $newId === false ) {
367 if ( $id != intval( $newId ) ) {
371 $len = fgets( $this->spawnRead
);
372 // $this->progress( "<< " . trim( $len ) );
373 if ( $len === false ) return false;
375 $nbytes = intval( $len );
376 // actual error, not zero-length text
377 if ($nbytes < 0 ) return false;
381 // Subprocess may not send everything at once, we have to loop.
382 while ( $nbytes > strlen( $text ) ) {
383 $buffer = fread( $this->spawnRead
, $nbytes - strlen( $text ) );
384 if ( $buffer === false ) break;
388 $gotbytes = strlen( $text );
389 if ( $gotbytes != $nbytes ) {
390 $this->progress( "Expected $nbytes bytes from database subprocess, got $gotbytes " );
394 // Do normalization in the dump thread...
395 $stripped = str_replace( "\r", "", $text );
396 $normalized = $wgContLang->normalize( $stripped );
400 function startElement( $parser, $name, $attribs ) {
401 $this->clearOpenElement( null );
402 $this->lastName
= $name;
404 if ( $name == 'revision' ) {
405 $this->state
= $name;
406 $this->egress
->writeOpenPage( null, $this->buffer
);
408 } elseif ( $name == 'page' ) {
409 $this->state
= $name;
410 if ( $this->atStart
) {
411 $this->egress
->writeOpenStream( $this->buffer
);
413 $this->atStart
= false;
417 if ( $name == "text" && isset( $attribs['id'] ) ) {
418 $text = $this->getText( $attribs['id'] );
419 $this->openElement
= array( $name, array( 'xml:space' => 'preserve' ) );
420 if ( strlen( $text ) > 0 ) {
421 $this->characterData( $parser, $text );
424 $this->openElement
= array( $name, $attribs );
428 function endElement( $parser, $name ) {
429 if ( $this->openElement
) {
430 $this->clearOpenElement( "" );
432 $this->buffer
.= "</$name>";
435 if ( $name == 'revision' ) {
436 $this->egress
->writeRevision( null, $this->buffer
);
439 } elseif ( $name == 'page' ) {
440 $this->egress
->writeClosePage( $this->buffer
);
442 $this->thisPage
= "";
443 } elseif ( $name == 'mediawiki' ) {
444 $this->egress
->writeCloseStream( $this->buffer
);
449 function characterData( $parser, $data ) {
450 $this->clearOpenElement( null );
451 if ( $this->lastName
== "id" ) {
452 if ( $this->state
== "revision" ) {
453 $this->thisRev
.= $data;
454 } elseif ( $this->state
== "page" ) {
455 $this->thisPage
.= $data;
458 $this->buffer
.= htmlspecialchars( $data );
461 function clearOpenElement( $style ) {
462 if ( $this->openElement
) {
463 $this->buffer
.= Xml
::element( $this->openElement
[0], $this->openElement
[1], $style );
464 $this->openElement
= false;
470 $dumper = new TextPassDumper( $argv );
472 if ( !isset( $options['help'] ) ) {
473 $dumper->dump( true );
475 $dumper->progress( <<<ENDS
476 This script postprocesses XML dumps from dumpBackup.php to add
477 page text which was stubbed out (using --stub).
479 XML input is accepted on stdin.
480 XML output is sent to stdout; progress reports are sent to stderr.
482 Usage: php dumpTextPass.php [<options>]
484 --stub=<type>:<file> To load a compressed stub dump instead of stdin
485 --prefetch=<type>:<file> Use a prior dump file as a text source, to save
486 pressure on the database.
487 (Requires the XMLReader extension)
488 --quiet Don't dump status reports to stderr.
489 --report=n Report position and speed after every n pages processed.
491 --server=h Force reading from MySQL server h
492 --current Base ETA on number of pages in database instead of all revisions
493 --spawn Spawn a subprocess for loading text records
494 --help Display this help message