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 ) {
98 $fileURIs = explode(';',$param);
99 foreach ( $fileURIs as $URI ) {
105 $newURI = "compress.zlib://$URI";
108 $newURI = "compress.bzip2://$URI";
111 $newURI = "mediawiki.compress.7z://$URI";
116 $newFileURIs[] = $newURI;
118 $val = implode( ';', $newFileURIs );
123 * Overridden to include prefetch ratio if enabled.
125 function showReport() {
126 if ( !$this->prefetch
) {
127 return parent
::showReport();
130 if ( $this->reporting
) {
131 $delta = wfTime() - $this->startTime
;
132 $now = wfTimestamp( TS_DB
);
134 $rate = $this->pageCount
/ $delta;
135 $revrate = $this->revCount
/ $delta;
136 $portion = $this->revCount
/ $this->maxCount
;
137 $eta = $this->startTime +
$delta / $portion;
138 $etats = wfTimestamp( TS_DB
, intval( $eta ) );
139 $fetchrate = 100.0 * $this->prefetchCount
/ $this->fetchCount
;
146 $this->progress( sprintf( "%s: %s %d pages (%0.3f/sec), %d revs (%0.3f/sec), %0.1f%% prefetched, ETA %s [max %d]",
147 $now, wfWikiID(), $this->pageCount
, $rate, $this->revCount
, $revrate, $fetchrate, $etats, $this->maxCount
) );
151 function readDump() {
157 $reader = new XMLReader();
158 $reader->open( $this->input
);
159 $writer = new XMLWriter();
160 $writer->openMemory();
163 while ( $reader->read() ) {
164 $tag = $reader->name
;
165 $type = $reader->nodeType
;
167 if ( $type == XmlReader
::END_ELEMENT
) {
168 $writer->endElement();
170 if ( $tag == 'revision' ) {
173 } elseif ( $tag == 'page' ) {
175 $this->thisPage
= '';
177 } elseif ( $type == XmlReader
::ELEMENT
) {
179 if ( $reader->hasAttributes
) {
180 for ( $i = 0; $reader->moveToAttributeNo( $i ); $i++
) {
181 $attribs[$reader->name
] = $reader->value
;
185 if ( $reader->isEmptyElement
&& $tag == 'text' && isset( $attribs['id'] ) ) {
186 $writer->startElement( 'text' );
187 $writer->writeAttribute( 'xml:space', 'preserve' );
188 $text = $this->getText( $attribs['id'] );
189 if ( strlen( $text ) ) {
190 $writer->text( $text );
192 $writer->endElement();
194 $writer->startElement( $tag );
195 foreach( $attribs as $name => $val ) {
196 $writer->writeAttribute( $name, $val );
198 if ( $reader->isEmptyElement
) {
199 $writer->endElement();
204 if ( $tag == 'revision' ) {
206 } elseif ( $tag == 'page' ) {
209 } elseif ( $type == XMLReader
::SIGNIFICANT_WHITESPACE ||
$type = XMLReader
::TEXT
) {
210 if ( $lastName == 'id' ) {
211 if ( $state == 'revision' ) {
212 $this->thisRev
.= $reader->value
;
213 } elseif ( $state == 'page' ) {
214 $this->thisPage
.= $reader->value
;
217 $writer->text( $reader->value
);
219 $this->sink
->write( $writer->outputMemory() );
223 function getText( $id ) {
225 if ( isset( $this->prefetch
) ) {
226 $text = $this->prefetch
->prefetch( $this->thisPage
, $this->thisRev
);
227 if ( $text !== null ) { // Entry missing from prefetch dump
228 $dbr = wfGetDB( DB_SLAVE
);
229 $revID = intval( $this->thisRev
);
230 $revLength = $dbr->selectField( 'revision', 'rev_len', array( 'rev_id' => $revID ) );
231 // if length of rev text in file doesn't match length in db, we reload
232 // this avoids carrying forward broken data from previous xml dumps
233 if( strlen( $text ) == $revLength ) {
234 $this->prefetchCount++
;
239 return $this->doGetText( $id );
242 private function doGetText( $id ) {
245 $ex = new MWException( "Graceful storage failure" );
247 if ( $this->spawn
) {
248 if ($this->failures
) {
249 // we don't know why it failed, could be the child process
250 // borked, could be db entry busted, could be db server out to lunch,
251 // so cover all bases
255 $text = $this->getTextSpawned( $id );
257 $text = $this->getTextDbSafe( $id );
259 if ( $text === false ) {
261 if ( $this->failures
> $this->maxFailures
) {
262 $this->progress( "Failed to retrieve revision text for text id ".
263 "$id after $this->maxFailures tries, giving up" );
264 // were there so many bad retrievals in a row we want to bail?
265 // at some point we have to declare the dump irretrievably broken
266 $this->failedTextRetrievals++
;
267 if ($this->failedTextRetrievals
> $this->maxConsecutiveFailedTextRetrievals
) {
271 // would be nice to return something better to the caller someday,
272 // log what we know about the failure and about the revision
276 $this->progress( "Error $this->failures " .
277 "of allowed $this->maxFailures retrieving revision text for text id $id! " .
278 "Pausing $this->failureTimeout seconds before retry..." );
279 sleep( $this->failureTimeout
);
282 $this->failedTextRetrievals
= 0;
290 * Fetch a text revision from the database, retrying in case of failure.
291 * This may survive some transitory errors by reconnecting, but
292 * may not survive a long-term server outage.
294 private function getTextDbSafe( $id ) {
297 $text = $this->getTextDb( $id );
298 } catch ( DBQueryError
$ex ) {
306 * May throw a database error if, say, the server dies during query.
308 private function getTextDb( $id ) {
310 $row = $this->db
->selectRow( 'text',
311 array( 'old_text', 'old_flags' ),
312 array( 'old_id' => $id ),
314 $text = Revision
::getRevisionText( $row );
315 if ( $text === false ) {
318 $stripped = str_replace( "\r", "", $text );
319 $normalized = $wgContLang->normalize( $stripped );
323 private function getTextSpawned( $id ) {
324 wfSuppressWarnings();
325 if ( !$this->spawnProc
) {
329 $text = $this->getTextSpawnedOnce( $id );
334 function openSpawn() {
338 array_map( 'wfEscapeShellArg',
341 "$IP/maintenance/fetchText.php",
342 '--wiki', wfWikiID() ) ) );
344 0 => array( "pipe", "r" ),
345 1 => array( "pipe", "w" ),
346 2 => array( "file", "/dev/null", "a" ) );
349 $this->progress( "Spawning database subprocess: $cmd" );
350 $this->spawnProc
= proc_open( $cmd, $spec, $pipes );
351 if ( !$this->spawnProc
) {
353 $this->progress( "Subprocess spawn failed." );
357 $this->spawnWrite
, // -> stdin
358 $this->spawnRead
, // <- stdout
364 private function closeSpawn() {
365 wfSuppressWarnings();
366 if ( $this->spawnRead
)
367 fclose( $this->spawnRead
);
368 $this->spawnRead
= false;
369 if ( $this->spawnWrite
)
370 fclose( $this->spawnWrite
);
371 $this->spawnWrite
= false;
372 if ( $this->spawnErr
)
373 fclose( $this->spawnErr
);
374 $this->spawnErr
= false;
375 if ( $this->spawnProc
)
376 pclose( $this->spawnProc
);
377 $this->spawnProc
= false;
381 private function getTextSpawnedOnce( $id ) {
384 $ok = fwrite( $this->spawnWrite
, "$id\n" );
385 // $this->progress( ">> $id" );
386 if ( !$ok ) return false;
388 $ok = fflush( $this->spawnWrite
);
389 // $this->progress( ">> [flush]" );
390 if ( !$ok ) return false;
392 // check that the text id they are sending is the one we asked for
393 // this avoids out of sync revision text errors we have encountered in the past
394 $newId = fgets( $this->spawnRead
);
395 if ( $newId === false ) {
398 if ( $id != intval( $newId ) ) {
402 $len = fgets( $this->spawnRead
);
403 // $this->progress( "<< " . trim( $len ) );
404 if ( $len === false ) return false;
406 $nbytes = intval( $len );
407 // actual error, not zero-length text
408 if ($nbytes < 0 ) return false;
412 // Subprocess may not send everything at once, we have to loop.
413 while ( $nbytes > strlen( $text ) ) {
414 $buffer = fread( $this->spawnRead
, $nbytes - strlen( $text ) );
415 if ( $buffer === false ) break;
419 $gotbytes = strlen( $text );
420 if ( $gotbytes != $nbytes ) {
421 $this->progress( "Expected $nbytes bytes from database subprocess, got $gotbytes " );
425 // Do normalization in the dump thread...
426 $stripped = str_replace( "\r", "", $text );
427 $normalized = $wgContLang->normalize( $stripped );
433 $dumper = new TextPassDumper( $argv );
435 if ( !isset( $options['help'] ) ) {
436 $dumper->dump( WikiExporter
::FULL
);
438 $dumper->progress( <<<ENDS
439 This script postprocesses XML dumps from dumpBackup.php to add
440 page text which was stubbed out (using --stub).
442 XML input is accepted on stdin.
443 XML output is sent to stdout; progress reports are sent to stderr.
445 Usage: php dumpTextPass.php [<options>]
447 --stub=<type>:<file> To load a compressed stub dump instead of stdin
448 --prefetch=<type>:<file> Use a prior dump file as a text source, to save
449 pressure on the database.
450 --quiet Don't dump status reports to stderr.
451 --report=n Report position and speed after every n pages processed.
453 --server=h Force reading from MySQL server h
454 --output=<type>:<file> Write to a file instead of stdout
455 <type>s: file, gzip, bzip2, 7zip
456 --current Base ETA on number of pages in database instead of all revisions
457 --spawn Spawn a subprocess for loading text records
458 --help Display this help message