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 ) {
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 = $wgContLang->normalize( $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 ) {
327 $ok = fwrite( $this->spawnWrite, "$id\n" );
328 //$this->progress( ">> $id" );
329 if( !$ok ) return false;
331 $ok = fflush( $this->spawnWrite );
332 //$this->progress( ">> [flush]" );
333 if( !$ok ) return false;
335 $len = fgets( $this->spawnRead );
336 //$this->progress( "<< " . trim( $len ) );
337 if( $len === false ) return false;
339 $nbytes = intval( $len );
342 // Subprocess may not send everything at once, we have to loop.
343 while( $nbytes > strlen( $text ) ) {
344 $buffer = fread( $this->spawnRead, $nbytes - strlen( $text ) );
345 if( $buffer === false ) break;
349 $gotbytes = strlen( $text );
350 if( $gotbytes != $nbytes ) {
351 $this->progress( "Expected $nbytes bytes from database subprocess, got $gotbytes ");
355 // Do normalization in the dump thread...
356 $stripped = str_replace( "\r", "", $text );
357 $normalized = $wgContLang->normalize( $stripped );
361 function startElement( $parser, $name, $attribs ) {
362 $this->clearOpenElement( null );
363 $this->lastName = $name;
365 if( $name == 'revision' ) {
366 $this->state = $name;
367 $this->egress->writeOpenPage( null, $this->buffer );
369 } elseif( $name == 'page' ) {
370 $this->state = $name;
371 if( $this->atStart ) {
372 $this->egress->writeOpenStream( $this->buffer );
374 $this->atStart = false;
378 if( $name == "text" && isset( $attribs['id'] ) ) {
379 $text = $this->getText( $attribs['id'] );
380 $this->openElement = array( $name, array( 'xml:space' => 'preserve' ) );
381 if( strlen( $text ) > 0 ) {
382 $this->characterData( $parser, $text );
385 $this->openElement = array( $name, $attribs );
389 function endElement( $parser, $name ) {
390 if( $this->openElement ) {
391 $this->clearOpenElement( "" );
393 $this->buffer .= "</$name>";
396 if( $name == 'revision' ) {
397 $this->egress->writeRevision( null, $this->buffer );
400 } elseif( $name == 'page' ) {
401 $this->egress->writeClosePage( $this->buffer );
403 $this->thisPage = "";
404 } elseif( $name == 'mediawiki' ) {
405 $this->egress->writeCloseStream( $this->buffer );
410 function characterData( $parser, $data ) {
411 $this->clearOpenElement( null );
412 if( $this->lastName == "id" ) {
413 if( $this->state == "revision" ) {
414 $this->thisRev .= $data;
415 } elseif( $this->state == "page" ) {
416 $this->thisPage .= $data;
419 $this->buffer .= htmlspecialchars( $data );
422 function clearOpenElement( $style ) {
423 if( $this->openElement ) {
424 $this->buffer .= Xml::element( $this->openElement[0], $this->openElement[1], $style );
425 $this->openElement = false;
431 $dumper = new TextPassDumper( $argv );
436 $dumper->progress( <<<ENDS
437 This script postprocesses XML dumps from dumpBackup.php to add
438 page text which was stubbed out (using --stub).
440 XML input is accepted on stdin.
441 XML output is sent to stdout; progress reports are sent to stderr.
443 Usage: php dumpTextPass.php [<options>]
445 --stub=<type>:<file> To load a compressed stub dump instead of stdin
446 --prefetch=<type>:<file> Use a prior dump file as a text source, to save
447 pressure on the database.
448 (Requires PHP 5.0+ and the XMLReader PECL extension)
449 --quiet Don't dump status reports to stderr.
450 --report=n Report position and speed after every n pages processed.
452 --server=h Force reading from MySQL server h
453 --current Base ETA on number of pages in database instead of all revisions
454 --spawn Spawn a subprocess for loading text records