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' );
31 * @ingroup Maintenance
33 class TextPassDumper
extends BackupDumper
{
35 var $input = "php://stdin";
36 var $history = WikiExporter
::FULL
;
38 var $prefetchCount = 0;
41 var $maxFailures = 200;
42 var $failureTimeout = 5; // Seconds to sleep after db failure
46 var $spawnProc = false;
47 var $spawnWrite = false;
48 var $spawnRead = false;
49 var $spawnErr = false;
52 # This shouldn't happen if on console... ;)
53 header( 'Content-type: text/html; charset=UTF-8' );
55 # Notice messages will foul up your XML output even if they're
56 # relatively harmless.
57 if( ini_get( 'display_errors' ) )
58 ini_set( 'display_errors', 'stderr' );
60 $this->initProgress( $this->history
);
62 $this->db
= $this->backupDb();
64 $this->egress
= new ExportProgressFilter( $this->sink
, $this );
66 $input = fopen( $this->input
, "rt" );
67 $result = $this->readDump( $input );
69 if( WikiError
::isError( $result ) ) {
70 wfDie( $result->getMessage() );
73 if( $this->spawnProc
) {
77 $this->report( true );
80 function processOption( $opt, $val, $param ) {
81 $url = $this->processFileOpt( $val, $param );
86 require_once "$IP/maintenance/backupPrefetch.inc";
87 $this->prefetch
= new BaseDump( $url );
93 $this->history
= WikiExporter
::CURRENT
;
96 $this->history
= WikiExporter
::FULL
;
107 function processFileOpt( $val, $param ) {
112 return "compress.zlib://$param";
114 return "compress.bzip2://$param";
116 return "mediawiki.compress.7z://$param";
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( $input ) {
153 $this->openElement
= false;
154 $this->atStart
= true;
156 $this->lastName
= "";
160 $parser = xml_parser_create( "UTF-8" );
161 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING
, false );
163 xml_set_element_handler( $parser, array( &$this, 'startElement' ), array( &$this, 'endElement' ) );
164 xml_set_character_data_handler( $parser, array( &$this, 'characterData' ) );
166 $offset = 0; // for context extraction on error reporting
167 $bufferSize = 512 * 1024;
169 $chunk = fread( $input, $bufferSize );
170 if( !xml_parse( $parser, $chunk, feof( $input ) ) ) {
171 wfDebug( "TextDumpPass::readDump encountered XML parsing error\n" );
172 return new WikiXmlError( $parser, 'XML import parse failure', $chunk, $offset );
174 $offset +
= strlen( $chunk );
175 } while( $chunk !== false && !feof( $input ) );
176 xml_parser_free( $parser );
181 function getText( $id ) {
183 if( isset( $this->prefetch
) ) {
184 $text = $this->prefetch
->prefetch( $this->thisPage
, $this->thisRev
);
185 if( $text === null ) {
186 // Entry missing from prefetch dump
187 } elseif( $text === "" ) {
188 // Blank entries may indicate that the prior dump was broken.
189 // To be safe, reload it.
191 $this->prefetchCount++
;
195 return $this->doGetText( $id );
198 private function doGetText( $id ) {
200 return $this->getTextSpawned( $id );
202 return $this->getTextDbSafe( $id );
207 * Fetch a text revision from the database, retrying in case of failure.
208 * This may survive some transitory errors by reconnecting, but
209 * may not survive a long-term server outage.
211 private function getTextDbSafe( $id ) {
214 $text = $this->getTextDb( $id );
215 $ex = new MWException("Graceful storage failure");
216 } catch (DBQueryError
$ex) {
219 if( $text === false ) {
221 if( $this->failures
> $this->maxFailures
) {
224 $this->progress( "Database failure $this->failures " .
225 "of allowed $this->maxFailures for revision $id! " .
226 "Pausing $this->failureTimeout seconds..." );
227 sleep( $this->failureTimeout
);
236 * May throw a database error if, say, the server dies during query.
238 private function getTextDb( $id ) {
240 $row = $this->db
->selectRow( 'text',
241 array( 'old_text', 'old_flags' ),
242 array( 'old_id' => $id ),
243 'TextPassDumper::getText' );
244 $text = Revision
::getRevisionText( $row );
245 if( $text === false ) {
248 $stripped = str_replace( "\r", "", $text );
249 $normalized = UtfNormal
::cleanUp( $stripped );
253 private function getTextSpawned( $id ) {
254 wfSuppressWarnings();
255 if( !$this->spawnProc
) {
261 $text = $this->getTextSpawnedOnce( $id );
262 if( !is_string( $text ) ) {
263 $this->progress("Database subprocess failed. Respawning...");
266 sleep( $this->failureTimeout
);
276 function openSpawn() {
277 global $IP, $wgDBname;
280 array_map( 'wfEscapeShellArg',
283 "$IP/maintenance/fetchText.php",
286 0 => array( "pipe", "r" ),
287 1 => array( "pipe", "w" ),
288 2 => array( "file", "/dev/null", "a" ) );
291 $this->progress( "Spawning database subprocess: $cmd" );
292 $this->spawnProc
= proc_open( $cmd, $spec, $pipes );
293 if( !$this->spawnProc
) {
295 $this->progress( "Subprocess spawn failed." );
299 $this->spawnWrite
, // -> stdin
300 $this->spawnRead
, // <- stdout
306 private function closeSpawn() {
307 wfSuppressWarnings();
308 if( $this->spawnRead
)
309 fclose( $this->spawnRead
);
310 $this->spawnRead
= false;
311 if( $this->spawnWrite
)
312 fclose( $this->spawnWrite
);
313 $this->spawnWrite
= false;
314 if( $this->spawnErr
)
315 fclose( $this->spawnErr
);
316 $this->spawnErr
= false;
317 if( $this->spawnProc
)
318 pclose( $this->spawnProc
);
319 $this->spawnProc
= false;
323 private function getTextSpawnedOnce( $id ) {
324 $ok = fwrite( $this->spawnWrite
, "$id\n" );
325 //$this->progress( ">> $id" );
326 if( !$ok ) return false;
328 $ok = fflush( $this->spawnWrite
);
329 //$this->progress( ">> [flush]" );
330 if( !$ok ) return false;
332 $len = fgets( $this->spawnRead
);
333 //$this->progress( "<< " . trim( $len ) );
334 if( $len === false ) return false;
336 $nbytes = intval( $len );
339 // Subprocess may not send everything at once, we have to loop.
340 while( $nbytes > strlen( $text ) ) {
341 $buffer = fread( $this->spawnRead
, $nbytes - strlen( $text ) );
342 if( $buffer === false ) break;
346 $gotbytes = strlen( $text );
347 if( $gotbytes != $nbytes ) {
348 $this->progress( "Expected $nbytes bytes from database subprocess, got $gotbytes ");
352 // Do normalization in the dump thread...
353 $stripped = str_replace( "\r", "", $text );
354 $normalized = UtfNormal
::cleanUp( $stripped );
358 function startElement( $parser, $name, $attribs ) {
359 $this->clearOpenElement( null );
360 $this->lastName
= $name;
362 if( $name == 'revision' ) {
363 $this->state
= $name;
364 $this->egress
->writeOpenPage( null, $this->buffer
);
366 } elseif( $name == 'page' ) {
367 $this->state
= $name;
368 if( $this->atStart
) {
369 $this->egress
->writeOpenStream( $this->buffer
);
371 $this->atStart
= false;
375 if( $name == "text" && isset( $attribs['id'] ) ) {
376 $text = $this->getText( $attribs['id'] );
377 $this->openElement
= array( $name, array( 'xml:space' => 'preserve' ) );
378 if( strlen( $text ) > 0 ) {
379 $this->characterData( $parser, $text );
382 $this->openElement
= array( $name, $attribs );
386 function endElement( $parser, $name ) {
387 if( $this->openElement
) {
388 $this->clearOpenElement( "" );
390 $this->buffer
.= "</$name>";
393 if( $name == 'revision' ) {
394 $this->egress
->writeRevision( null, $this->buffer
);
397 } elseif( $name == 'page' ) {
398 $this->egress
->writeClosePage( $this->buffer
);
400 $this->thisPage
= "";
401 } elseif( $name == 'mediawiki' ) {
402 $this->egress
->writeCloseStream( $this->buffer
);
407 function characterData( $parser, $data ) {
408 $this->clearOpenElement( null );
409 if( $this->lastName
== "id" ) {
410 if( $this->state
== "revision" ) {
411 $this->thisRev
.= $data;
412 } elseif( $this->state
== "page" ) {
413 $this->thisPage
.= $data;
416 $this->buffer
.= htmlspecialchars( $data );
419 function clearOpenElement( $style ) {
420 if( $this->openElement
) {
421 $this->buffer
.= Xml
::element( $this->openElement
[0], $this->openElement
[1], $style );
422 $this->openElement
= false;
428 $dumper = new TextPassDumper( $argv );
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 (Requires PHP 5.0+ and the XMLReader PECL extension)
446 --quiet Don't dump status reports to stderr.
447 --report=n Report position and speed after every n pages processed.
449 --server=h Force reading from MySQL server h
450 --current Base ETA on number of pages in database instead of all revisions
451 --spawn Spawn a subprocess for loading text records