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( 'commandLine.inc' );
28 require_once( 'backup.inc' );
31 * Stream wrapper around 7za filter program.
32 * Required since we can't pass an open file resource to XMLReader->open()
33 * which is used for the text prefetch.
35 * @ingroup Maintenance
37 class SevenZipStream
{
40 private function stripPath( $path ) {
41 $prefix = 'mediawiki.compress.7z://';
42 return substr( $path, strlen( $prefix ) );
45 function stream_open( $path, $mode, $options, &$opened_path ) {
46 if( $mode{0} == 'r' ) {
47 $options = 'e -bd -so';
48 } elseif( $mode{0} == 'w' ) {
49 $options = 'a -bd -si';
53 $arg = wfEscapeShellArg( $this->stripPath( $path ) );
54 $command = "7za $options $arg";
55 if( !wfIsWindows() ) {
56 // Suppress the stupid messages on stderr
57 $command .= ' 2>/dev/null';
59 $this->stream
= popen( $command, $mode );
60 return ($this->stream
!== false);
63 function url_stat( $path, $flags ) {
64 return stat( $this->stripPath( $path ) );
67 // This is all so lame; there should be a default class we can extend
69 function stream_close() {
70 return fclose( $this->stream
);
73 function stream_flush() {
74 return fflush( $this->stream
);
77 function stream_read( $count ) {
78 return fread( $this->stream
, $count );
81 function stream_write( $data ) {
82 return fwrite( $this->stream
, $data );
85 function stream_tell() {
86 return ftell( $this->stream
);
89 function stream_eof() {
90 return feof( $this->stream
);
93 function stream_seek( $offset, $whence ) {
94 return fseek( $this->stream
, $offset, $whence );
97 stream_wrapper_register( 'mediawiki.compress.7z', 'SevenZipStream' );
100 * @ingroup Maintenance
102 class TextPassDumper
extends BackupDumper
{
103 var $prefetch = null;
104 var $input = "php://stdin";
105 var $history = WikiExporter
::FULL
;
107 var $prefetchCount = 0;
110 var $maxFailures = 200;
111 var $failureTimeout = 5; // Seconds to sleep after db failure
115 var $spawnProc = false;
116 var $spawnWrite = false;
117 var $spawnRead = false;
118 var $spawnErr = false;
121 # This shouldn't happen if on console... ;)
122 header( 'Content-type: text/html; charset=UTF-8' );
124 # Notice messages will foul up your XML output even if they're
125 # relatively harmless.
126 if( ini_get( 'display_errors' ) )
127 ini_set( 'display_errors', 'stderr' );
129 $this->initProgress( $this->history
);
131 $this->db
= $this->backupDb();
133 $this->egress
= new ExportProgressFilter( $this->sink
, $this );
135 $input = fopen( $this->input
, "rt" );
136 $result = $this->readDump( $input );
138 if( WikiError
::isError( $result ) ) {
139 wfDie( $result->getMessage() );
142 if( $this->spawnProc
) {
146 $this->report( true );
149 function processOption( $opt, $val, $param ) {
150 $url = $this->processFileOpt( $val, $param );
155 require_once "$IP/maintenance/backupPrefetch.inc";
156 $this->prefetch
= new BaseDump( $url );
162 $this->history
= WikiExporter
::CURRENT
;
165 $this->history
= WikiExporter
::FULL
;
176 function processFileOpt( $val, $param ) {
181 return "compress.zlib://$param";
183 return "compress.bzip2://$param";
185 return "mediawiki.compress.7z://$param";
192 * Overridden to include prefetch ratio if enabled.
194 function showReport() {
195 if( !$this->prefetch
) {
196 return parent
::showReport();
199 if( $this->reporting
) {
200 $delta = wfTime() - $this->startTime
;
201 $now = wfTimestamp( TS_DB
);
203 $rate = $this->pageCount
/ $delta;
204 $revrate = $this->revCount
/ $delta;
205 $portion = $this->revCount
/ $this->maxCount
;
206 $eta = $this->startTime +
$delta / $portion;
207 $etats = wfTimestamp( TS_DB
, intval( $eta ) );
208 $fetchrate = 100.0 * $this->prefetchCount
/ $this->fetchCount
;
215 $this->progress( sprintf( "%s: %s %d pages (%0.3f/sec), %d revs (%0.3f/sec), %0.1f%% prefetched, ETA %s [max %d]",
216 $now, wfWikiID(), $this->pageCount
, $rate, $this->revCount
, $revrate, $fetchrate, $etats, $this->maxCount
) );
220 function readDump( $input ) {
222 $this->openElement
= false;
223 $this->atStart
= true;
225 $this->lastName
= "";
229 $parser = xml_parser_create( "UTF-8" );
230 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING
, false );
232 xml_set_element_handler( $parser, array( &$this, 'startElement' ), array( &$this, 'endElement' ) );
233 xml_set_character_data_handler( $parser, array( &$this, 'characterData' ) );
235 $offset = 0; // for context extraction on error reporting
236 $bufferSize = 512 * 1024;
238 $chunk = fread( $input, $bufferSize );
239 if( !xml_parse( $parser, $chunk, feof( $input ) ) ) {
240 wfDebug( "TextDumpPass::readDump encountered XML parsing error\n" );
241 return new WikiXmlError( $parser, 'XML import parse failure', $chunk, $offset );
243 $offset +
= strlen( $chunk );
244 } while( $chunk !== false && !feof( $input ) );
245 xml_parser_free( $parser );
250 function getText( $id ) {
252 if( isset( $this->prefetch
) ) {
253 $text = $this->prefetch
->prefetch( $this->thisPage
, $this->thisRev
);
254 if( $text === null ) {
255 // Entry missing from prefetch dump
256 } elseif( $text === "" ) {
257 // Blank entries may indicate that the prior dump was broken.
258 // To be safe, reload it.
260 $this->prefetchCount++
;
264 return $this->doGetText( $id );
267 private function doGetText( $id ) {
269 return $this->getTextSpawned( $id );
271 return $this->getTextDbSafe( $id );
276 * Fetch a text revision from the database, retrying in case of failure.
277 * This may survive some transitory errors by reconnecting, but
278 * may not survive a long-term server outage.
280 private function getTextDbSafe( $id ) {
283 $text = $this->getTextDb( $id );
284 $ex = new MWException("Graceful storage failure");
285 } catch (DBQueryError
$ex) {
288 if( $text === false ) {
290 if( $this->failures
> $this->maxFailures
) {
293 $this->progress( "Database failure $this->failures " .
294 "of allowed $this->maxFailures for revision $id! " .
295 "Pausing $this->failureTimeout seconds..." );
296 sleep( $this->failureTimeout
);
305 * May throw a database error if, say, the server dies during query.
307 private function getTextDb( $id ) {
309 $row = $this->db
->selectRow( 'text',
310 array( 'old_text', 'old_flags' ),
311 array( 'old_id' => $id ),
312 'TextPassDumper::getText' );
313 $text = Revision
::getRevisionText( $row );
314 if( $text === false ) {
317 $stripped = str_replace( "\r", "", $text );
318 $normalized = UtfNormal
::cleanUp( $stripped );
322 private function getTextSpawned( $id ) {
323 wfSuppressWarnings();
324 if( !$this->spawnProc
) {
330 $text = $this->getTextSpawnedOnce( $id );
331 if( !is_string( $text ) ) {
332 $this->progress("Database subprocess failed. Respawning...");
335 sleep( $this->failureTimeout
);
345 function openSpawn() {
346 global $IP, $wgDBname;
349 array_map( 'wfEscapeShellArg',
352 "$IP/maintenance/fetchText.php",
355 0 => array( "pipe", "r" ),
356 1 => array( "pipe", "w" ),
357 2 => array( "file", "/dev/null", "a" ) );
360 $this->progress( "Spawning database subprocess: $cmd" );
361 $this->spawnProc
= proc_open( $cmd, $spec, $pipes );
362 if( !$this->spawnProc
) {
364 $this->progress( "Subprocess spawn failed." );
368 $this->spawnWrite
, // -> stdin
369 $this->spawnRead
, // <- stdout
375 private function closeSpawn() {
376 wfSuppressWarnings();
377 if( $this->spawnRead
)
378 fclose( $this->spawnRead
);
379 $this->spawnRead
= false;
380 if( $this->spawnWrite
)
381 fclose( $this->spawnWrite
);
382 $this->spawnWrite
= false;
383 if( $this->spawnErr
)
384 fclose( $this->spawnErr
);
385 $this->spawnErr
= false;
386 if( $this->spawnProc
)
387 pclose( $this->spawnProc
);
388 $this->spawnProc
= false;
392 private function getTextSpawnedOnce( $id ) {
393 $ok = fwrite( $this->spawnWrite
, "$id\n" );
394 //$this->progress( ">> $id" );
395 if( !$ok ) return false;
397 $ok = fflush( $this->spawnWrite
);
398 //$this->progress( ">> [flush]" );
399 if( !$ok ) return false;
401 $len = fgets( $this->spawnRead
);
402 //$this->progress( "<< " . trim( $len ) );
403 if( $len === false ) return false;
405 $nbytes = intval( $len );
408 // Subprocess may not send everything at once, we have to loop.
409 while( $nbytes > strlen( $text ) ) {
410 $buffer = fread( $this->spawnRead
, $nbytes - strlen( $text ) );
411 if( $text === false ) break;
415 $gotbytes = strlen( $text );
416 if( $gotbytes != $nbytes ) {
417 $this->progress( "Expected $nbytes bytes from database subprocess, got $gotbytes ");
421 // Do normalization in the dump thread...
422 $stripped = str_replace( "\r", "", $text );
423 $normalized = UtfNormal
::cleanUp( $stripped );
427 function startElement( $parser, $name, $attribs ) {
428 $this->clearOpenElement( null );
429 $this->lastName
= $name;
431 if( $name == 'revision' ) {
432 $this->state
= $name;
433 $this->egress
->writeOpenPage( null, $this->buffer
);
435 } elseif( $name == 'page' ) {
436 $this->state
= $name;
437 if( $this->atStart
) {
438 $this->egress
->writeOpenStream( $this->buffer
);
440 $this->atStart
= false;
444 if( $name == "text" && isset( $attribs['id'] ) ) {
445 $text = $this->getText( $attribs['id'] );
446 $this->openElement
= array( $name, array( 'xml:space' => 'preserve' ) );
447 if( strlen( $text ) > 0 ) {
448 $this->characterData( $parser, $text );
451 $this->openElement
= array( $name, $attribs );
455 function endElement( $parser, $name ) {
456 if( $this->openElement
) {
457 $this->clearOpenElement( "" );
459 $this->buffer
.= "</$name>";
462 if( $name == 'revision' ) {
463 $this->egress
->writeRevision( null, $this->buffer
);
466 } elseif( $name == 'page' ) {
467 $this->egress
->writeClosePage( $this->buffer
);
469 $this->thisPage
= "";
470 } elseif( $name == 'mediawiki' ) {
471 $this->egress
->writeCloseStream( $this->buffer
);
476 function characterData( $parser, $data ) {
477 $this->clearOpenElement( null );
478 if( $this->lastName
== "id" ) {
479 if( $this->state
== "revision" ) {
480 $this->thisRev
.= $data;
481 } elseif( $this->state
== "page" ) {
482 $this->thisPage
.= $data;
485 $this->buffer
.= htmlspecialchars( $data );
488 function clearOpenElement( $style ) {
489 if( $this->openElement
) {
490 $this->buffer
.= wfElement( $this->openElement
[0], $this->openElement
[1], $style );
491 $this->openElement
= false;
497 $dumper = new TextPassDumper( $argv );
502 $dumper->progress( <<<END
503 This script postprocesses XML dumps from dumpBackup.php to add
504 page text which was stubbed out (using --stub).
506 XML input is accepted on stdin.
507 XML output is sent to stdout; progress reports are sent to stderr.
509 Usage: php dumpTextPass.php [<options>]
511 --stub=<type>:<file> To load a compressed stub dump instead of stdin
512 --prefetch=<type>:<file> Use a prior dump file as a text source, to save
513 pressure on the database.
514 (Requires PHP 5.0+ and the XMLReader PECL extension)
515 --quiet Don't dump status reports to stderr.
516 --report=n Report position and speed after every n pages processed.
518 --server=h Force reading from MySQL server h
519 --current Base ETA on number of pages in database instead of all revisions
520 --spawn Spawn a subprocess for loading text records