3 * Script that postprocesses XML dumps from dumpBackup.php to add page text
5 * Copyright © 2005 Brion Vibber <brion@pobox.com>, 2010 Alexandre Emsenhuber
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";
39 var $prefetchCount = 0;
43 var $failedTextRetrievals = 0;
44 var $maxConsecutiveFailedTextRetrievals = 200;
45 var $failureTimeout = 5; // Seconds to sleep after db failure
49 var $spawnProc = false;
50 var $spawnWrite = false;
51 var $spawnRead = false;
52 var $spawnErr = false;
54 function dump( $history, $text = WikiExporter
::TEXT
) {
55 # This shouldn't happen if on console... ;)
56 header( 'Content-type: text/html; charset=UTF-8' );
58 # Notice messages will foul up your XML output even if they're
59 # relatively harmless.
60 if ( ini_get( 'display_errors' ) )
61 ini_set( 'display_errors', 'stderr' );
63 $this->initProgress( $history );
65 $this->db
= $this->backupDb();
69 if ( $this->spawnProc
) {
73 $this->report( true );
76 function processOption( $opt, $val, $param ) {
78 $url = $this->processFileOpt( $val, $param );
82 require_once "$IP/maintenance/backupPrefetch.inc";
83 $this->prefetch
= new BaseDump( $url );
97 function processFileOpt( $val, $param ) {
102 return "compress.zlib://$param";
104 return "compress.bzip2://$param";
106 return "mediawiki.compress.7z://$param";
113 * Overridden to include prefetch ratio if enabled.
115 function showReport() {
116 if ( !$this->prefetch
) {
117 return parent
::showReport();
120 if ( $this->reporting
) {
121 $delta = wfTime() - $this->startTime
;
122 $now = wfTimestamp( TS_DB
);
124 $rate = $this->pageCount
/ $delta;
125 $revrate = $this->revCount
/ $delta;
126 $portion = $this->revCount
/ $this->maxCount
;
127 $eta = $this->startTime +
$delta / $portion;
128 $etats = wfTimestamp( TS_DB
, intval( $eta ) );
129 $fetchrate = 100.0 * $this->prefetchCount
/ $this->fetchCount
;
136 $this->progress( sprintf( "%s: %s %d pages (%0.3f/sec), %d revs (%0.3f/sec), %0.1f%% prefetched, ETA %s [max %d]",
137 $now, wfWikiID(), $this->pageCount
, $rate, $this->revCount
, $revrate, $fetchrate, $etats, $this->maxCount
) );
141 function readDump() {
147 $reader = new XMLReader();
148 $reader->open( $this->input
);
149 $writer = new XMLWriter();
150 $writer->openURI( 'php://stdout' );
153 while ( $reader->read() ) {
154 $tag = $reader->name
;
155 $type = $reader->nodeType
;
157 if ( $type == XmlReader
::END_ELEMENT
) {
158 $writer->endElement();
160 if ( $tag == 'revision' ) {
163 } elseif ( $tag == 'page' ) {
165 $this->thisPage
= '';
167 } elseif ( $type == XmlReader
::ELEMENT
) {
169 if ( $reader->hasAttributes
) {
170 for ( $i = 0; $reader->moveToAttributeNo( $i ); $i++
) {
171 $attribs[$reader->name
] = $reader->value
;
175 if ( $reader->isEmptyElement
&& $tag == 'text' && isset( $attribs['id'] ) ) {
176 $writer->startElement( 'text' );
177 $writer->writeAttribute( 'xml:space', 'preserve' );
178 $text = $this->getText( $attribs['id'] );
179 if ( strlen( $text ) ) {
180 $writer->text( $text );
182 $writer->endElement();
184 $writer->startElement( $tag );
185 foreach( $attribs as $name => $val ) {
186 $writer->writeAttribute( $name, $val );
188 if ( $reader->isEmptyElement
) {
189 $writer->endElement();
194 if ( $tag == 'revision' ) {
196 } elseif ( $tag == 'page' ) {
199 } elseif ( $type == XMLReader
::SIGNIFICANT_WHITESPACE ||
$type = XMLReader
::TEXT
) {
200 if ( $lastName == 'id' ) {
201 if ( $state == 'revision' ) {
202 $this->thisRev
.= $reader->value
;
203 } elseif ( $state == 'page' ) {
204 $this->thisPage
.= $reader->value
;
207 $writer->text( $reader->value
);
213 function getText( $id ) {
215 if ( isset( $this->prefetch
) ) {
216 $text = $this->prefetch
->prefetch( $this->thisPage
, $this->thisRev
);
217 if ( $text !== null ) { // Entry missing from prefetch dump
218 $dbr = wfGetDB( DB_SLAVE
);
219 $revID = intval( $this->thisRev
);
220 $revLength = $dbr->selectField( 'revision', 'rev_len', array( 'rev_id' => $revID ) );
221 // if length of rev text in file doesn't match length in db, we reload
222 // this avoids carrying forward broken data from previous xml dumps
223 if( strlen( $text ) == $revLength ) {
224 $this->prefetchCount++
;
229 return $this->doGetText( $id );
232 private function doGetText( $id ) {
235 $ex = new MWException( "Graceful storage failure" );
237 if ( $this->spawn
) {
238 if ($this->failures
) {
239 // we don't know why it failed, could be the child process
240 // borked, could be db entry busted, could be db server out to lunch,
241 // so cover all bases
245 $text = $this->getTextSpawned( $id );
247 $text = $this->getTextDbSafe( $id );
249 if ( $text === false ) {
251 if ( $this->failures
> $this->maxFailures
) {
252 $this->progress( "Failed to retrieve revision text for text id ".
253 "$id after $this->maxFailures tries, giving up" );
254 // were there so many bad retrievals in a row we want to bail?
255 // at some point we have to declare the dump irretrievably broken
256 $this->failedTextRetrievals++
;
257 if ($this->failedTextRetrievals
> $this->maxConsecutiveFailedTextRetrievals
) {
261 // would be nice to return something better to the caller someday,
262 // log what we know about the failure and about the revision
266 $this->progress( "Error $this->failures " .
267 "of allowed $this->maxFailures retrieving revision text for text id $id! " .
268 "Pausing $this->failureTimeout seconds before retry..." );
269 sleep( $this->failureTimeout
);
272 $this->failedTextRetrievals
= 0;
280 * Fetch a text revision from the database, retrying in case of failure.
281 * This may survive some transitory errors by reconnecting, but
282 * may not survive a long-term server outage.
284 private function getTextDbSafe( $id ) {
287 $text = $this->getTextDb( $id );
288 } catch ( DBQueryError
$ex ) {
296 * May throw a database error if, say, the server dies during query.
298 private function getTextDb( $id ) {
300 $row = $this->db
->selectRow( 'text',
301 array( 'old_text', 'old_flags' ),
302 array( 'old_id' => $id ),
304 $text = Revision
::getRevisionText( $row );
305 if ( $text === false ) {
308 $stripped = str_replace( "\r", "", $text );
309 $normalized = $wgContLang->normalize( $stripped );
313 private function getTextSpawned( $id ) {
314 wfSuppressWarnings();
315 if ( !$this->spawnProc
) {
319 $text = $this->getTextSpawnedOnce( $id );
324 function openSpawn() {
328 array_map( 'wfEscapeShellArg',
331 "$IP/maintenance/fetchText.php",
332 '--wiki', wfWikiID() ) ) );
334 0 => array( "pipe", "r" ),
335 1 => array( "pipe", "w" ),
336 2 => array( "file", "/dev/null", "a" ) );
339 $this->progress( "Spawning database subprocess: $cmd" );
340 $this->spawnProc
= proc_open( $cmd, $spec, $pipes );
341 if ( !$this->spawnProc
) {
343 $this->progress( "Subprocess spawn failed." );
347 $this->spawnWrite
, // -> stdin
348 $this->spawnRead
, // <- stdout
354 private function closeSpawn() {
355 wfSuppressWarnings();
356 if ( $this->spawnRead
)
357 fclose( $this->spawnRead
);
358 $this->spawnRead
= false;
359 if ( $this->spawnWrite
)
360 fclose( $this->spawnWrite
);
361 $this->spawnWrite
= false;
362 if ( $this->spawnErr
)
363 fclose( $this->spawnErr
);
364 $this->spawnErr
= false;
365 if ( $this->spawnProc
)
366 pclose( $this->spawnProc
);
367 $this->spawnProc
= false;
371 private function getTextSpawnedOnce( $id ) {
374 $ok = fwrite( $this->spawnWrite
, "$id\n" );
375 // $this->progress( ">> $id" );
376 if ( !$ok ) return false;
378 $ok = fflush( $this->spawnWrite
);
379 // $this->progress( ">> [flush]" );
380 if ( !$ok ) return false;
382 // check that the text id they are sending is the one we asked for
383 // this avoids out of sync revision text errors we have encountered in the past
384 $newId = fgets( $this->spawnRead
);
385 if ( $newId === false ) {
388 if ( $id != intval( $newId ) ) {
392 $len = fgets( $this->spawnRead
);
393 // $this->progress( "<< " . trim( $len ) );
394 if ( $len === false ) return false;
396 $nbytes = intval( $len );
397 // actual error, not zero-length text
398 if ($nbytes < 0 ) return false;
402 // Subprocess may not send everything at once, we have to loop.
403 while ( $nbytes > strlen( $text ) ) {
404 $buffer = fread( $this->spawnRead
, $nbytes - strlen( $text ) );
405 if ( $buffer === false ) break;
409 $gotbytes = strlen( $text );
410 if ( $gotbytes != $nbytes ) {
411 $this->progress( "Expected $nbytes bytes from database subprocess, got $gotbytes " );
415 // Do normalization in the dump thread...
416 $stripped = str_replace( "\r", "", $text );
417 $normalized = $wgContLang->normalize( $stripped );
423 $dumper = new TextPassDumper( $argv );
425 if ( !isset( $options['help'] ) ) {
426 $dumper->dump( WikiExporter
::FULL
);
428 $dumper->progress( <<<ENDS
429 This script postprocesses XML dumps from dumpBackup.php to add
430 page text which was stubbed out (using --stub).
432 XML input is accepted on stdin.
433 XML output is sent to stdout; progress reports are sent to stderr.
435 Usage: php dumpTextPass.php [<options>]
437 --stub=<type>:<file> To load a compressed stub dump instead of stdin
438 --prefetch=<type>:<file> Use a prior dump file as a text source, to save
439 pressure on the database.
440 --quiet Don't dump status reports to stderr.
441 --report=n Report position and speed after every n pages processed.
443 --server=h Force reading from MySQL server h
444 --current Base ETA on number of pages in database instead of all revisions
445 --spawn Spawn a subprocess for loading text records
446 --help Display this help message