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
21 * @addtogroup SpecialPage
24 $originalDir = getcwd();
26 require_once( 'commandLine.inc' );
27 require_once( 'backup.inc' );
30 * Stream wrapper around 7za filter program.
31 * Required since we can't pass an open file resource to XMLReader->open()
32 * which is used for the text prefetch.
34 class SevenZipStream
{
37 private function stripPath( $path ) {
38 $prefix = 'mediawiki.compress.7z://';
39 return substr( $path, strlen( $prefix ) );
42 function stream_open( $path, $mode, $options, &$opened_path ) {
43 if( $mode{0} == 'r' ) {
44 $options = 'e -bd -so';
45 } elseif( $mode{0} == 'w' ) {
46 $options = 'a -bd -si';
50 $arg = wfEscapeShellArg( $this->stripPath( $path ) );
51 $command = "7za $options $arg";
52 if( !wfIsWindows() ) {
53 // Suppress the stupid messages on stderr
54 $command .= ' 2>/dev/null';
56 $this->stream
= popen( $command, $mode );
57 return ($this->stream
!== false);
60 function url_stat( $path, $flags ) {
61 return stat( $this->stripPath( $path ) );
64 // This is all so lame; there should be a default class we can extend
66 function stream_close() {
67 return fclose( $this->stream
);
70 function stream_flush() {
71 return fflush( $this->stream
);
74 function stream_read( $count ) {
75 return fread( $this->stream
, $count );
78 function stream_write( $data ) {
79 return fwrite( $this->stream
, $data );
82 function stream_tell() {
83 return ftell( $this->stream
);
86 function stream_eof() {
87 return feof( $this->stream
);
90 function stream_seek( $offset, $whence ) {
91 return fseek( $this->stream
, $offset, $whence );
94 stream_wrapper_register( 'mediawiki.compress.7z', 'SevenZipStream' );
97 class TextPassDumper
extends BackupDumper
{
99 var $input = "php://stdin";
100 var $history = WikiExporter
::FULL
;
102 var $prefetchCount = 0;
105 var $maxFailures = 200;
106 var $failureTimeout = 5; // Seconds to sleep after db failure
110 var $spawnProc = false;
111 var $spawnWrite = false;
112 var $spawnRead = false;
113 var $spawnErr = false;
116 # This shouldn't happen if on console... ;)
117 header( 'Content-type: text/html; charset=UTF-8' );
119 # Notice messages will foul up your XML output even if they're
120 # relatively harmless.
121 // ini_set( 'display_errors', false );
123 $this->initProgress( $this->history
);
125 $this->db
= $this->backupDb();
127 $this->egress
= new ExportProgressFilter( $this->sink
, $this );
129 $input = fopen( $this->input
, "rt" );
130 $result = $this->readDump( $input );
132 if( WikiError
::isError( $result ) ) {
133 wfDie( $result->getMessage() );
136 if( $this->spawnProc
) {
140 $this->report( true );
143 function processOption( $opt, $val, $param ) {
144 $url = $this->processFileOpt( $val, $param );
148 require_once 'maintenance/backupPrefetch.inc';
149 $this->prefetch
= new BaseDump( $url );
155 $this->history
= WikiExporter
::CURRENT
;
158 $this->history
= WikiExporter
::FULL
;
169 function processFileOpt( $val, $param ) {
174 return "compress.zlib://$param";
176 return "compress.bzip2://$param";
178 return "mediawiki.compress.7z://$param";
185 * Overridden to include prefetch ratio if enabled.
187 function showReport() {
188 if( !$this->prefetch
) {
189 return parent
::showReport();
192 if( $this->reporting
) {
193 $delta = wfTime() - $this->startTime
;
194 $now = wfTimestamp( TS_DB
);
196 $rate = $this->pageCount
/ $delta;
197 $revrate = $this->revCount
/ $delta;
198 $portion = $this->revCount
/ $this->maxCount
;
199 $eta = $this->startTime +
$delta / $portion;
200 $etats = wfTimestamp( TS_DB
, intval( $eta ) );
201 $fetchrate = 100.0 * $this->prefetchCount
/ $this->fetchCount
;
208 $this->progress( sprintf( "%s: %s %d pages (%0.3f/sec), %d revs (%0.3f/sec), %0.1f%% prefetched, ETA %s [max %d]",
209 $now, wfWikiID(), $this->pageCount
, $rate, $this->revCount
, $revrate, $fetchrate, $etats, $this->maxCount
) );
213 function readDump( $input ) {
215 $this->openElement
= false;
216 $this->atStart
= true;
218 $this->lastName
= "";
222 $parser = xml_parser_create( "UTF-8" );
223 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING
, false );
225 xml_set_element_handler( $parser, array( &$this, 'startElement' ), array( &$this, 'endElement' ) );
226 xml_set_character_data_handler( $parser, array( &$this, 'characterData' ) );
228 $offset = 0; // for context extraction on error reporting
229 $bufferSize = 512 * 1024;
231 $chunk = fread( $input, $bufferSize );
232 if( !xml_parse( $parser, $chunk, feof( $input ) ) ) {
233 wfDebug( "TextDumpPass::readDump encountered XML parsing error\n" );
234 return new WikiXmlError( $parser, 'XML import parse failure', $chunk, $offset );
236 $offset +
= strlen( $chunk );
237 } while( $chunk !== false && !feof( $input ) );
238 xml_parser_free( $parser );
243 function getText( $id ) {
245 if( isset( $this->prefetch
) ) {
246 $text = $this->prefetch
->prefetch( $this->thisPage
, $this->thisRev
);
247 if( $text === null ) {
248 // Entry missing from prefetch dump
249 } elseif( $text === "" ) {
250 // Blank entries may indicate that the prior dump was broken.
251 // To be safe, reload it.
253 $this->prefetchCount++
;
257 return $this->doGetText( $id );
260 private function doGetText( $id ) {
262 return $this->getTextSpawned( $id );
264 return $this->getTextDbSafe( $id );
269 * Fetch a text revision from the database, retrying in case of failure.
270 * This may survive some transitory errors by reconnecting, but
271 * may not survive a long-term server outage.
273 private function getTextDbSafe( $id ) {
276 $text = $this->getTextDb( $id );
277 $ex = new MWException("Graceful storage failure");
278 } catch (DBQueryError
$ex) {
281 if( $text === false ) {
283 if( $this->failures
> $this->maxFailures
) {
286 $this->progress( "Database failure $this->failures " .
287 "of allowed $this->maxFailures for revision $id! " .
288 "Pausing $this->failureTimeout seconds..." );
289 sleep( $this->failureTimeout
);
298 * May throw a database error if, say, the server dies during query.
300 private function getTextDb( $id ) {
302 $row = $this->db
->selectRow( 'text',
303 array( 'old_text', 'old_flags' ),
304 array( 'old_id' => $id ),
305 'TextPassDumper::getText' );
306 $text = Revision
::getRevisionText( $row );
307 if( $text === false ) {
310 $stripped = str_replace( "\r", "", $text );
311 $normalized = UtfNormal
::cleanUp( $stripped );
315 private function getTextSpawned( $id ) {
316 wfSuppressWarnings();
317 if( !$this->spawnProc
) {
323 $text = $this->getTextSpawnedOnce( $id );
324 if( !is_string( $text ) ) {
325 $this->progress("Database subprocess failed. Respawning...");
328 sleep( $this->failureTimeout
);
338 function openSpawn() {
339 global $IP, $wgDBname;
342 array_map( 'wfEscapeShellArg',
345 "$IP/maintenance/fetchText.php",
348 0 => array( "pipe", "r" ),
349 1 => array( "pipe", "w" ),
350 2 => array( "file", "/dev/null", "a" ) );
353 $this->progress( "Spawning database subprocess: $cmd" );
354 $this->spawnProc
= proc_open( $cmd, $spec, $pipes );
355 if( !$this->spawnProc
) {
357 $this->progress( "Subprocess spawn failed." );
361 $this->spawnWrite
, // -> stdin
362 $this->spawnRead
, // <- stdout
368 private function closeSpawn() {
369 wfSuppressWarnings();
370 if( $this->spawnRead
)
371 fclose( $this->spawnRead
);
372 $this->spawnRead
= false;
373 if( $this->spawnWrite
)
374 fclose( $this->spawnWrite
);
375 $this->spawnWrite
= false;
376 if( $this->spawnErr
)
377 fclose( $this->spawnErr
);
378 $this->spawnErr
= false;
379 if( $this->spawnProc
)
380 pclose( $this->spawnProc
);
381 $this->spawnProc
= false;
385 private function getTextSpawnedOnce( $id ) {
386 $ok = fwrite( $this->spawnWrite
, "$id\n" );
387 //$this->progress( ">> $id" );
388 if( !$ok ) return false;
390 $ok = fflush( $this->spawnWrite
);
391 //$this->progress( ">> [flush]" );
392 if( !$ok ) return false;
394 $len = fgets( $this->spawnRead
);
395 //$this->progress( "<< " . trim( $len ) );
396 if( $len === false ) return false;
398 $nbytes = intval( $len );
401 // Subprocess may not send everything at once, we have to loop.
402 while( $nbytes > strlen( $text ) ) {
403 $buffer = fread( $this->spawnRead
, $nbytes - strlen( $text ) );
404 if( $text === false ) break;
408 $gotbytes = strlen( $text );
409 if( $gotbytes != $nbytes ) {
410 $this->progress( "Expected $nbytes bytes from database subprocess, got $gotbytes ");
414 // Do normalization in the dump thread...
415 $stripped = str_replace( "\r", "", $text );
416 $normalized = UtfNormal
::cleanUp( $stripped );
420 function startElement( $parser, $name, $attribs ) {
421 $this->clearOpenElement( null );
422 $this->lastName
= $name;
424 if( $name == 'revision' ) {
425 $this->state
= $name;
426 $this->egress
->writeOpenPage( null, $this->buffer
);
428 } elseif( $name == 'page' ) {
429 $this->state
= $name;
430 if( $this->atStart
) {
431 $this->egress
->writeOpenStream( $this->buffer
);
433 $this->atStart
= false;
437 if( $name == "text" && isset( $attribs['id'] ) ) {
438 $text = $this->getText( $attribs['id'] );
439 $this->openElement
= array( $name, array( 'xml:space' => 'preserve' ) );
440 if( strlen( $text ) > 0 ) {
441 $this->characterData( $parser, $text );
444 $this->openElement
= array( $name, $attribs );
448 function endElement( $parser, $name ) {
449 if( $this->openElement
) {
450 $this->clearOpenElement( "" );
452 $this->buffer
.= "</$name>";
455 if( $name == 'revision' ) {
456 $this->egress
->writeRevision( null, $this->buffer
);
459 } elseif( $name == 'page' ) {
460 $this->egress
->writeClosePage( $this->buffer
);
462 $this->thisPage
= "";
463 } elseif( $name == 'mediawiki' ) {
464 $this->egress
->writeCloseStream( $this->buffer
);
469 function characterData( $parser, $data ) {
470 $this->clearOpenElement( null );
471 if( $this->lastName
== "id" ) {
472 if( $this->state
== "revision" ) {
473 $this->thisRev
.= $data;
474 } elseif( $this->state
== "page" ) {
475 $this->thisPage
.= $data;
478 $this->buffer
.= htmlspecialchars( $data );
481 function clearOpenElement( $style ) {
482 if( $this->openElement
) {
483 $this->buffer
.= wfElement( $this->openElement
[0], $this->openElement
[1], $style );
484 $this->openElement
= false;
490 $dumper = new TextPassDumper( $argv );
495 $dumper->progress( <<<END
496 This script postprocesses XML dumps from dumpBackup.php to add
497 page text which was stubbed out (using --stub).
499 XML input is accepted on stdin.
500 XML output is sent to stdout; progress reports are sent to stderr.
502 Usage: php dumpTextPass.php [<options>]
504 --stub=<type>:<file> To load a compressed stub dump instead of stdin
505 --prefetch=<type>:<file> Use a prior dump file as a text source, to save
506 pressure on the database.
507 (Requires PHP 5.0+ and the XMLReader PECL extension)
508 --quiet Don't dump status reports to stderr.
509 --report=n Report position and speed after every n pages processed.
511 --server=h Force reading from MySQL server h
512 --current Base ETA on number of pages in database instead of all revisions
513 --spawn Spawn a subprocess for loading text records