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' );
29 require_once( '7zip.inc' );
32 * @ingroup Maintenance
34 class TextPassDumper
extends BackupDumper
{
36 var $input = "php://stdin";
37 var $history = WikiExporter
::FULL
;
39 var $prefetchCount = 0;
42 var $maxFailures = 200;
43 var $failureTimeout = 5; // Seconds to sleep after db failure
47 var $spawnProc = false;
48 var $spawnWrite = false;
49 var $spawnRead = false;
50 var $spawnErr = false;
53 # This shouldn't happen if on console... ;)
54 header( 'Content-type: text/html; charset=UTF-8' );
56 # Notice messages will foul up your XML output even if they're
57 # relatively harmless.
58 if( ini_get( 'display_errors' ) )
59 ini_set( 'display_errors', 'stderr' );
61 $this->initProgress( $this->history
);
63 $this->db
= $this->backupDb();
65 $this->egress
= new ExportProgressFilter( $this->sink
, $this );
67 $input = fopen( $this->input
, "rt" );
68 $result = $this->readDump( $input );
70 if( WikiError
::isError( $result ) ) {
71 wfDie( $result->getMessage() );
74 if( $this->spawnProc
) {
78 $this->report( true );
81 function processOption( $opt, $val, $param ) {
82 $url = $this->processFileOpt( $val, $param );
87 require_once "$IP/maintenance/backupPrefetch.inc";
88 $this->prefetch
= new BaseDump( $url );
94 $this->history
= WikiExporter
::CURRENT
;
97 $this->history
= WikiExporter
::FULL
;
108 function processFileOpt( $val, $param ) {
113 return "compress.zlib://$param";
115 return "compress.bzip2://$param";
117 return "mediawiki.compress.7z://$param";
124 * Overridden to include prefetch ratio if enabled.
126 function showReport() {
127 if( !$this->prefetch
) {
128 return parent
::showReport();
131 if( $this->reporting
) {
132 $delta = wfTime() - $this->startTime
;
133 $now = wfTimestamp( TS_DB
);
135 $rate = $this->pageCount
/ $delta;
136 $revrate = $this->revCount
/ $delta;
137 $portion = $this->revCount
/ $this->maxCount
;
138 $eta = $this->startTime +
$delta / $portion;
139 $etats = wfTimestamp( TS_DB
, intval( $eta ) );
140 $fetchrate = 100.0 * $this->prefetchCount
/ $this->fetchCount
;
147 $this->progress( sprintf( "%s: %s %d pages (%0.3f/sec), %d revs (%0.3f/sec), %0.1f%% prefetched, ETA %s [max %d]",
148 $now, wfWikiID(), $this->pageCount
, $rate, $this->revCount
, $revrate, $fetchrate, $etats, $this->maxCount
) );
152 function readDump( $input ) {
154 $this->openElement
= false;
155 $this->atStart
= true;
157 $this->lastName
= "";
161 $parser = xml_parser_create( "UTF-8" );
162 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING
, false );
164 xml_set_element_handler( $parser, array( &$this, 'startElement' ), array( &$this, 'endElement' ) );
165 xml_set_character_data_handler( $parser, array( &$this, 'characterData' ) );
167 $offset = 0; // for context extraction on error reporting
168 $bufferSize = 512 * 1024;
170 $chunk = fread( $input, $bufferSize );
171 if( !xml_parse( $parser, $chunk, feof( $input ) ) ) {
172 wfDebug( "TextDumpPass::readDump encountered XML parsing error\n" );
173 return new WikiXmlError( $parser, 'XML import parse failure', $chunk, $offset );
175 $offset +
= strlen( $chunk );
176 } while( $chunk !== false && !feof( $input ) );
177 xml_parser_free( $parser );
182 function getText( $id ) {
184 if( isset( $this->prefetch
) ) {
185 $text = $this->prefetch
->prefetch( $this->thisPage
, $this->thisRev
);
186 if( $text === null ) {
187 // Entry missing from prefetch dump
188 } elseif( $text === "" ) {
189 // Blank entries may indicate that the prior dump was broken.
190 // To be safe, reload it.
192 $this->prefetchCount++
;
196 return $this->doGetText( $id );
199 private function doGetText( $id ) {
201 return $this->getTextSpawned( $id );
203 return $this->getTextDbSafe( $id );
208 * Fetch a text revision from the database, retrying in case of failure.
209 * This may survive some transitory errors by reconnecting, but
210 * may not survive a long-term server outage.
212 private function getTextDbSafe( $id ) {
215 $text = $this->getTextDb( $id );
216 $ex = new MWException("Graceful storage failure");
217 } catch (DBQueryError
$ex) {
220 if( $text === false ) {
222 if( $this->failures
> $this->maxFailures
) {
225 $this->progress( "Database failure $this->failures " .
226 "of allowed $this->maxFailures for revision $id! " .
227 "Pausing $this->failureTimeout seconds..." );
228 sleep( $this->failureTimeout
);
237 * May throw a database error if, say, the server dies during query.
239 private function getTextDb( $id ) {
241 $row = $this->db
->selectRow( 'text',
242 array( 'old_text', 'old_flags' ),
243 array( 'old_id' => $id ),
244 'TextPassDumper::getText' );
245 $text = Revision
::getRevisionText( $row );
246 if( $text === false ) {
249 $stripped = str_replace( "\r", "", $text );
250 $normalized = UtfNormal
::cleanUp( $stripped );
254 private function getTextSpawned( $id ) {
255 wfSuppressWarnings();
256 if( !$this->spawnProc
) {
262 $text = $this->getTextSpawnedOnce( $id );
263 if( !is_string( $text ) ) {
264 $this->progress("Database subprocess failed. Respawning...");
267 sleep( $this->failureTimeout
);
277 function openSpawn() {
278 global $IP, $wgDBname;
281 array_map( 'wfEscapeShellArg',
284 "$IP/maintenance/fetchText.php",
287 0 => array( "pipe", "r" ),
288 1 => array( "pipe", "w" ),
289 2 => array( "file", "/dev/null", "a" ) );
292 $this->progress( "Spawning database subprocess: $cmd" );
293 $this->spawnProc
= proc_open( $cmd, $spec, $pipes );
294 if( !$this->spawnProc
) {
296 $this->progress( "Subprocess spawn failed." );
300 $this->spawnWrite
, // -> stdin
301 $this->spawnRead
, // <- stdout
307 private function closeSpawn() {
308 wfSuppressWarnings();
309 if( $this->spawnRead
)
310 fclose( $this->spawnRead
);
311 $this->spawnRead
= false;
312 if( $this->spawnWrite
)
313 fclose( $this->spawnWrite
);
314 $this->spawnWrite
= false;
315 if( $this->spawnErr
)
316 fclose( $this->spawnErr
);
317 $this->spawnErr
= false;
318 if( $this->spawnProc
)
319 pclose( $this->spawnProc
);
320 $this->spawnProc
= false;
324 private function getTextSpawnedOnce( $id ) {
325 $ok = fwrite( $this->spawnWrite
, "$id\n" );
326 //$this->progress( ">> $id" );
327 if( !$ok ) return false;
329 $ok = fflush( $this->spawnWrite
);
330 //$this->progress( ">> [flush]" );
331 if( !$ok ) return false;
333 $len = fgets( $this->spawnRead
);
334 //$this->progress( "<< " . trim( $len ) );
335 if( $len === false ) return false;
337 $nbytes = intval( $len );
340 // Subprocess may not send everything at once, we have to loop.
341 while( $nbytes > strlen( $text ) ) {
342 $buffer = fread( $this->spawnRead
, $nbytes - strlen( $text ) );
343 if( $buffer === false ) break;
347 $gotbytes = strlen( $text );
348 if( $gotbytes != $nbytes ) {
349 $this->progress( "Expected $nbytes bytes from database subprocess, got $gotbytes ");
353 // Do normalization in the dump thread...
354 $stripped = str_replace( "\r", "", $text );
355 $normalized = UtfNormal
::cleanUp( $stripped );
359 function startElement( $parser, $name, $attribs ) {
360 $this->clearOpenElement( null );
361 $this->lastName
= $name;
363 if( $name == 'revision' ) {
364 $this->state
= $name;
365 $this->egress
->writeOpenPage( null, $this->buffer
);
367 } elseif( $name == 'page' ) {
368 $this->state
= $name;
369 if( $this->atStart
) {
370 $this->egress
->writeOpenStream( $this->buffer
);
372 $this->atStart
= false;
376 if( $name == "text" && isset( $attribs['id'] ) ) {
377 $text = $this->getText( $attribs['id'] );
378 $this->openElement
= array( $name, array( 'xml:space' => 'preserve' ) );
379 if( strlen( $text ) > 0 ) {
380 $this->characterData( $parser, $text );
383 $this->openElement
= array( $name, $attribs );
387 function endElement( $parser, $name ) {
388 if( $this->openElement
) {
389 $this->clearOpenElement( "" );
391 $this->buffer
.= "</$name>";
394 if( $name == 'revision' ) {
395 $this->egress
->writeRevision( null, $this->buffer
);
398 } elseif( $name == 'page' ) {
399 $this->egress
->writeClosePage( $this->buffer
);
401 $this->thisPage
= "";
402 } elseif( $name == 'mediawiki' ) {
403 $this->egress
->writeCloseStream( $this->buffer
);
408 function characterData( $parser, $data ) {
409 $this->clearOpenElement( null );
410 if( $this->lastName
== "id" ) {
411 if( $this->state
== "revision" ) {
412 $this->thisRev
.= $data;
413 } elseif( $this->state
== "page" ) {
414 $this->thisPage
.= $data;
417 $this->buffer
.= htmlspecialchars( $data );
420 function clearOpenElement( $style ) {
421 if( $this->openElement
) {
422 $this->buffer
.= Xml
::element( $this->openElement
[0], $this->openElement
[1], $style );
423 $this->openElement
= false;
429 $dumper = new TextPassDumper( $argv );
434 $dumper->progress( <<<ENDS
435 This script postprocesses XML dumps from dumpBackup.php to add
436 page text which was stubbed out (using --stub).
438 XML input is accepted on stdin.
439 XML output is sent to stdout; progress reports are sent to stderr.
441 Usage: php dumpTextPass.php [<options>]
443 --stub=<type>:<file> To load a compressed stub dump instead of stdin
444 --prefetch=<type>:<file> Use a prior dump file as a text source, to save
445 pressure on the database.
446 (Requires PHP 5.0+ and the XMLReader PECL extension)
447 --quiet Don't dump status reports to stderr.
448 --report=n Report position and speed after every n pages processed.
450 --server=h Force reading from MySQL server h
451 --current Base ETA on number of pages in database instead of all revisions
452 --spawn Spawn a subprocess for loading text records