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 ) {
218 // Entry missing from prefetch dump
219 } elseif ( $text === "" ) {
220 // Blank entries may indicate that the prior dump was broken.
221 // To be safe, reload it.
223 $dbr = wfGetDB( DB_SLAVE
);
224 $revID = intval($this->thisRev
);
225 $revLength = $dbr->selectField( 'revision', 'rev_len', array('rev_id' => $revID ) );
226 // if length of rev text in file doesn't match length in db, we reload
227 // this avoids carrying forward broken data from previous xml dumps
228 if( strlen($text) == $revLength ) {
229 $this->prefetchCount++
;
234 return $this->doGetText( $id );
237 private function doGetText( $id ) {
240 $ex = new MWException( "Graceful storage failure" );
242 if ( $this->spawn
) {
243 if ($this->failures
) {
244 // we don't know why it failed, could be the child process
245 // borked, could be db entry busted, could be db server out to lunch,
246 // so cover all bases
250 $text = $this->getTextSpawned( $id );
252 $text = $this->getTextDbSafe( $id );
254 if ( $text === false ) {
256 if ( $this->failures
> $this->maxFailures
) {
257 $this->progress( "Failed to retrieve revision text for text id ".
258 "$id after $this->maxFailures tries, giving up" );
259 // were there so many bad retrievals in a row we want to bail?
260 // at some point we have to declare the dump irretrievably broken
261 $this->failedTextRetrievals++
;
262 if ($this->failedTextRetrievals
> $this->maxConsecutiveFailedTextRetrievals
) {
266 // would be nice to return something better to the caller someday,
267 // log what we know about the failure and about the revision
271 $this->progress( "Error $this->failures " .
272 "of allowed $this->maxFailures retrieving revision text for text id $id! " .
273 "Pausing $this->failureTimeout seconds before retry..." );
274 sleep( $this->failureTimeout
);
277 $this->failedTextRetrievals
= 0;
285 * Fetch a text revision from the database, retrying in case of failure.
286 * This may survive some transitory errors by reconnecting, but
287 * may not survive a long-term server outage.
289 private function getTextDbSafe( $id ) {
292 $text = $this->getTextDb( $id );
293 } catch ( DBQueryError
$ex ) {
301 * May throw a database error if, say, the server dies during query.
303 private function getTextDb( $id ) {
305 $row = $this->db
->selectRow( 'text',
306 array( 'old_text', 'old_flags' ),
307 array( 'old_id' => $id ),
309 $text = Revision
::getRevisionText( $row );
310 if ( $text === false ) {
313 $stripped = str_replace( "\r", "", $text );
314 $normalized = $wgContLang->normalize( $stripped );
318 private function getTextSpawned( $id ) {
319 wfSuppressWarnings();
320 if ( !$this->spawnProc
) {
324 $text = $this->getTextSpawnedOnce( $id );
329 function openSpawn() {
330 global $IP, $wgDBname;
333 array_map( 'wfEscapeShellArg',
336 "$IP/maintenance/fetchText.php",
339 0 => array( "pipe", "r" ),
340 1 => array( "pipe", "w" ),
341 2 => array( "file", "/dev/null", "a" ) );
344 $this->progress( "Spawning database subprocess: $cmd" );
345 $this->spawnProc
= proc_open( $cmd, $spec, $pipes );
346 if ( !$this->spawnProc
) {
348 $this->progress( "Subprocess spawn failed." );
352 $this->spawnWrite
, // -> stdin
353 $this->spawnRead
, // <- stdout
359 private function closeSpawn() {
360 wfSuppressWarnings();
361 if ( $this->spawnRead
)
362 fclose( $this->spawnRead
);
363 $this->spawnRead
= false;
364 if ( $this->spawnWrite
)
365 fclose( $this->spawnWrite
);
366 $this->spawnWrite
= false;
367 if ( $this->spawnErr
)
368 fclose( $this->spawnErr
);
369 $this->spawnErr
= false;
370 if ( $this->spawnProc
)
371 pclose( $this->spawnProc
);
372 $this->spawnProc
= false;
376 private function getTextSpawnedOnce( $id ) {
379 $ok = fwrite( $this->spawnWrite
, "$id\n" );
380 // $this->progress( ">> $id" );
381 if ( !$ok ) return false;
383 $ok = fflush( $this->spawnWrite
);
384 // $this->progress( ">> [flush]" );
385 if ( !$ok ) return false;
387 // check that the text id they are sending is the one we asked for
388 // this avoids out of sync revision text errors we have encountered in the past
389 $newId = fgets( $this->spawnRead
);
390 if ( $newId === false ) {
393 if ( $id != intval( $newId ) ) {
397 $len = fgets( $this->spawnRead
);
398 // $this->progress( "<< " . trim( $len ) );
399 if ( $len === false ) return false;
401 $nbytes = intval( $len );
402 // actual error, not zero-length text
403 if ($nbytes < 0 ) return false;
407 // Subprocess may not send everything at once, we have to loop.
408 while ( $nbytes > strlen( $text ) ) {
409 $buffer = fread( $this->spawnRead
, $nbytes - strlen( $text ) );
410 if ( $buffer === false ) break;
414 $gotbytes = strlen( $text );
415 if ( $gotbytes != $nbytes ) {
416 $this->progress( "Expected $nbytes bytes from database subprocess, got $gotbytes " );
420 // Do normalization in the dump thread...
421 $stripped = str_replace( "\r", "", $text );
422 $normalized = $wgContLang->normalize( $stripped );
428 $dumper = new TextPassDumper( $argv );
430 if ( !isset( $options['help'] ) ) {
431 $dumper->dump( WikiExporter
::FULL
);
433 $dumper->progress( <<<ENDS
434 This script postprocesses XML dumps from dumpBackup.php to add
435 page text which was stubbed out (using --stub).
437 XML input is accepted on stdin.
438 XML output is sent to stdout; progress reports are sent to stderr.
440 Usage: php dumpTextPass.php [<options>]
442 --stub=<type>:<file> To load a compressed stub dump instead of stdin
443 --prefetch=<type>:<file> Use a prior dump file as a text source, to save
444 pressure on the database.
445 --quiet Don't dump status reports to stderr.
446 --report=n Report position and speed after every n pages processed.
448 --server=h Force reading from MySQL server h
449 --current Base ETA on number of pages in database instead of all revisions
450 --spawn Spawn a subprocess for loading text records
451 --help Display this help message