testRegisteringNullModuleThrowsAnException - $this->markTestIncomplete( "Broken by...
[mediawiki.git] / maintenance / dumpTextPass.php
blob3a06cce56befde9b50602ce79ab67ab813b3c999
1 <?php
2 /**
3 * Script that postprocesses XML dumps from dumpBackup.php to add page text
5 * Copyright (C) 2005 Brion Vibber <brion@pobox.com>
6 * http://www.mediawiki.org/
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
23 * @file
24 * @ingroup Maintenance
27 $originalDir = getcwd();
29 require_once( dirname( __FILE__ ) . '/commandLine.inc' );
30 require_once( 'backup.inc' );
32 /**
33 * @ingroup Maintenance
35 class TextPassDumper extends BackupDumper {
36 var $prefetch = null;
37 var $input = "php://stdin";
38 var $history = WikiExporter::FULL;
39 var $fetchCount = 0;
40 var $prefetchCount = 0;
42 var $failures = 0;
43 var $maxFailures = 5;
44 var $failedTextRetrievals = 0;
45 var $maxConsecutiveFailedTextRetrievals = 200;
46 var $failureTimeout = 5; // Seconds to sleep after db failure
48 var $php = "php";
49 var $spawn = false;
50 var $spawnProc = false;
51 var $spawnWrite = false;
52 var $spawnRead = false;
53 var $spawnErr = false;
55 function dump( $history, $text = WikiExporter::TEXT ) {
56 # This shouldn't happen if on console... ;)
57 header( 'Content-type: text/html; charset=UTF-8' );
59 # Notice messages will foul up your XML output even if they're
60 # relatively harmless.
61 if ( ini_get( 'display_errors' ) )
62 ini_set( 'display_errors', 'stderr' );
64 $this->initProgress( $this->history );
66 $this->db = $this->backupDb();
68 $this->egress = new ExportProgressFilter( $this->sink, $this );
70 $input = fopen( $this->input, "rt" );
71 $result = $this->readDump( $input );
73 if ( WikiError::isError( $result ) ) {
74 wfDie( $result->getMessage() );
77 if ( $this->spawnProc ) {
78 $this->closeSpawn();
81 $this->report( true );
84 function processOption( $opt, $val, $param ) {
85 global $IP;
86 $url = $this->processFileOpt( $val, $param );
88 switch( $opt ) {
89 case 'prefetch':
90 require_once "$IP/maintenance/backupPrefetch.inc";
91 $this->prefetch = new BaseDump( $url );
92 break;
93 case 'stub':
94 $this->input = $url;
95 break;
96 case 'current':
97 $this->history = WikiExporter::CURRENT;
98 break;
99 case 'full':
100 $this->history = WikiExporter::FULL;
101 break;
102 case 'spawn':
103 $this->spawn = true;
104 if ( $val ) {
105 $this->php = $val;
107 break;
111 function processFileOpt( $val, $param ) {
112 switch( $val ) {
113 case "file":
114 return $param;
115 case "gzip":
116 return "compress.zlib://$param";
117 case "bzip2":
118 return "compress.bzip2://$param";
119 case "7zip":
120 return "mediawiki.compress.7z://$param";
121 default:
122 return $val;
127 * Overridden to include prefetch ratio if enabled.
129 function showReport() {
130 if ( !$this->prefetch ) {
131 return parent::showReport();
134 if ( $this->reporting ) {
135 $delta = wfTime() - $this->startTime;
136 $now = wfTimestamp( TS_DB );
137 if ( $delta ) {
138 $rate = $this->pageCount / $delta;
139 $revrate = $this->revCount / $delta;
140 $portion = $this->revCount / $this->maxCount;
141 $eta = $this->startTime + $delta / $portion;
142 $etats = wfTimestamp( TS_DB, intval( $eta ) );
143 $fetchrate = 100.0 * $this->prefetchCount / $this->fetchCount;
144 } else {
145 $rate = '-';
146 $revrate = '-';
147 $etats = '-';
148 $fetchrate = '-';
150 $this->progress( sprintf( "%s: %s %d pages (%0.3f/sec), %d revs (%0.3f/sec), %0.1f%% prefetched, ETA %s [max %d]",
151 $now, wfWikiID(), $this->pageCount, $rate, $this->revCount, $revrate, $fetchrate, $etats, $this->maxCount ) );
155 function readDump( $input ) {
156 $this->buffer = "";
157 $this->openElement = false;
158 $this->atStart = true;
159 $this->state = "";
160 $this->lastName = "";
161 $this->thisPage = 0;
162 $this->thisRev = 0;
164 $parser = xml_parser_create( "UTF-8" );
165 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
167 xml_set_element_handler( $parser, array( &$this, 'startElement' ), array( &$this, 'endElement' ) );
168 xml_set_character_data_handler( $parser, array( &$this, 'characterData' ) );
170 $offset = 0; // for context extraction on error reporting
171 $bufferSize = 512 * 1024;
172 do {
173 $chunk = fread( $input, $bufferSize );
174 if ( !xml_parse( $parser, $chunk, feof( $input ) ) ) {
175 wfDebug( "TextDumpPass::readDump encountered XML parsing error\n" );
176 return new WikiXmlError( $parser, 'XML import parse failure', $chunk, $offset );
178 $offset += strlen( $chunk );
179 } while ( $chunk !== false && !feof( $input ) );
180 xml_parser_free( $parser );
182 return true;
185 function getText( $id ) {
186 $this->fetchCount++;
187 if ( isset( $this->prefetch ) ) {
188 $text = $this->prefetch->prefetch( $this->thisPage, $this->thisRev );
189 if ( $text === null ) {
190 // Entry missing from prefetch dump
191 } elseif ( $text === "" ) {
192 // Blank entries may indicate that the prior dump was broken.
193 // To be safe, reload it.
194 } else {
195 $dbr = wfGetDB( DB_SLAVE );
196 $revID = intval($this->thisRev);
197 $revLength = $dbr->selectField( 'revision', 'rev_len', array('rev_id' => $revID ) );
198 // if length of rev text in file doesn't match length in db, we reload
199 // this avoids carrying forward broken data from previous xml dumps
200 if( strlen($text) == $revLength ) {
201 $this->prefetchCount++;
202 return $text;
206 return $this->doGetText( $id );
209 private function doGetText( $id ) {
211 $id = intval( $id );
212 $this->failures = 0;
213 $ex = new MWException( "Graceful storage failure" );
214 while (true) {
215 if ( $this->spawn ) {
216 if ($this->failures) {
217 // we don't know why it failed, could be the child process
218 // borked, could be db entry busted, could be db server out to lunch,
219 // so cover all bases
220 $this->closeSpawn();
221 $this->openSpawn();
223 $text = $this->getTextSpawned( $id );
224 } else {
225 $text = $this->getTextDbSafe( $id );
227 if ( $text === false ) {
228 $this->failures++;
229 if ( $this->failures > $this->maxFailures) {
230 $this->progress( "Failed to retrieve revision text for text id ".
231 "$id after $this->maxFailures tries, giving up" );
232 // were there so many bad retrievals in a row we want to bail?
233 // at some point we have to declare the dump irretrievably broken
234 $this->failedTextRetrievals++;
235 if ($this->failedTextRetrievals > $this->maxConsecutiveFailedTextRetrievals) {
236 throw $ex;
238 else {
239 // would be nice to return something better to the caller someday,
240 // log what we know about the failure and about the revision
241 return("");
243 } else {
244 $this->progress( "Error $this->failures " .
245 "of allowed $this->maxFailures retrieving revision text for text id $id! " .
246 "Pausing $this->failureTimeout seconds before retry..." );
247 sleep( $this->failureTimeout );
249 } else {
250 $this->failedTextRetrievals= 0;
251 return( $text );
258 * Fetch a text revision from the database, retrying in case of failure.
259 * This may survive some transitory errors by reconnecting, but
260 * may not survive a long-term server outage.
262 private function getTextDbSafe( $id ) {
263 while ( true ) {
264 try {
265 $text = $this->getTextDb( $id );
266 } catch ( DBQueryError $ex ) {
267 $text = false;
269 return $text;
274 * May throw a database error if, say, the server dies during query.
276 private function getTextDb( $id ) {
277 global $wgContLang;
278 $row = $this->db->selectRow( 'text',
279 array( 'old_text', 'old_flags' ),
280 array( 'old_id' => $id ),
281 __METHOD__ );
282 $text = Revision::getRevisionText( $row );
283 if ( $text === false ) {
284 return false;
286 $stripped = str_replace( "\r", "", $text );
287 $normalized = $wgContLang->normalize( $stripped );
288 return $normalized;
291 private function getTextSpawned( $id ) {
292 wfSuppressWarnings();
293 if ( !$this->spawnProc ) {
294 // First time?
295 $this->openSpawn();
297 $text = $this->getTextSpawnedOnce( $id );
298 wfRestoreWarnings();
299 return $text;
302 function openSpawn() {
303 global $IP, $wgDBname;
305 $cmd = implode( " ",
306 array_map( 'wfEscapeShellArg',
307 array(
308 $this->php,
309 "$IP/maintenance/fetchText.php",
310 $wgDBname ) ) );
311 $spec = array(
312 0 => array( "pipe", "r" ),
313 1 => array( "pipe", "w" ),
314 2 => array( "file", "/dev/null", "a" ) );
315 $pipes = array();
317 $this->progress( "Spawning database subprocess: $cmd" );
318 $this->spawnProc = proc_open( $cmd, $spec, $pipes );
319 if ( !$this->spawnProc ) {
320 // shit
321 $this->progress( "Subprocess spawn failed." );
322 return false;
324 list(
325 $this->spawnWrite, // -> stdin
326 $this->spawnRead, // <- stdout
327 ) = $pipes;
329 return true;
332 private function closeSpawn() {
333 wfSuppressWarnings();
334 if ( $this->spawnRead )
335 fclose( $this->spawnRead );
336 $this->spawnRead = false;
337 if ( $this->spawnWrite )
338 fclose( $this->spawnWrite );
339 $this->spawnWrite = false;
340 if ( $this->spawnErr )
341 fclose( $this->spawnErr );
342 $this->spawnErr = false;
343 if ( $this->spawnProc )
344 pclose( $this->spawnProc );
345 $this->spawnProc = false;
346 wfRestoreWarnings();
349 private function getTextSpawnedOnce( $id ) {
350 global $wgContLang;
352 $ok = fwrite( $this->spawnWrite, "$id\n" );
353 // $this->progress( ">> $id" );
354 if ( !$ok ) return false;
356 $ok = fflush( $this->spawnWrite );
357 // $this->progress( ">> [flush]" );
358 if ( !$ok ) return false;
360 // check that the text id they are sending is the one we asked for
361 // this avoids out of sync revision text errors we have encountered in the past
362 $newId = fgets( $this->spawnRead );
363 if ( $newId === false ) {
364 return false;
366 if ( $id != intval( $newId ) ) {
367 return false;
370 $len = fgets( $this->spawnRead );
371 // $this->progress( "<< " . trim( $len ) );
372 if ( $len === false ) return false;
374 $nbytes = intval( $len );
375 // actual error, not zero-length text
376 if ($nbytes < 0 ) return false;
378 $text = "";
380 // Subprocess may not send everything at once, we have to loop.
381 while ( $nbytes > strlen( $text ) ) {
382 $buffer = fread( $this->spawnRead, $nbytes - strlen( $text ) );
383 if ( $buffer === false ) break;
384 $text .= $buffer;
387 $gotbytes = strlen( $text );
388 if ( $gotbytes != $nbytes ) {
389 $this->progress( "Expected $nbytes bytes from database subprocess, got $gotbytes " );
390 return false;
393 // Do normalization in the dump thread...
394 $stripped = str_replace( "\r", "", $text );
395 $normalized = $wgContLang->normalize( $stripped );
396 return $normalized;
399 function startElement( $parser, $name, $attribs ) {
400 $this->clearOpenElement( null );
401 $this->lastName = $name;
403 if ( $name == 'revision' ) {
404 $this->state = $name;
405 $this->egress->writeOpenPage( null, $this->buffer );
406 $this->buffer = "";
407 } elseif ( $name == 'page' ) {
408 $this->state = $name;
409 if ( $this->atStart ) {
410 $this->egress->writeOpenStream( $this->buffer );
411 $this->buffer = "";
412 $this->atStart = false;
416 if ( $name == "text" && isset( $attribs['id'] ) ) {
417 $text = $this->getText( $attribs['id'] );
418 $this->openElement = array( $name, array( 'xml:space' => 'preserve' ) );
419 if ( strlen( $text ) > 0 ) {
420 $this->characterData( $parser, $text );
422 } else {
423 $this->openElement = array( $name, $attribs );
427 function endElement( $parser, $name ) {
428 if ( $this->openElement ) {
429 $this->clearOpenElement( "" );
430 } else {
431 $this->buffer .= "</$name>";
434 if ( $name == 'revision' ) {
435 $this->egress->writeRevision( null, $this->buffer );
436 $this->buffer = "";
437 $this->thisRev = "";
438 } elseif ( $name == 'page' ) {
439 $this->egress->writeClosePage( $this->buffer );
440 $this->buffer = "";
441 $this->thisPage = "";
442 } elseif ( $name == 'mediawiki' ) {
443 $this->egress->writeCloseStream( $this->buffer );
444 $this->buffer = "";
448 function characterData( $parser, $data ) {
449 $this->clearOpenElement( null );
450 if ( $this->lastName == "id" ) {
451 if ( $this->state == "revision" ) {
452 $this->thisRev .= $data;
453 } elseif ( $this->state == "page" ) {
454 $this->thisPage .= $data;
457 $this->buffer .= htmlspecialchars( $data );
460 function clearOpenElement( $style ) {
461 if ( $this->openElement ) {
462 $this->buffer .= Xml::element( $this->openElement[0], $this->openElement[1], $style );
463 $this->openElement = false;
469 $dumper = new TextPassDumper( $argv );
471 if ( !isset( $options['help'] ) ) {
472 $dumper->dump( true );
473 } else {
474 $dumper->progress( <<<ENDS
475 This script postprocesses XML dumps from dumpBackup.php to add
476 page text which was stubbed out (using --stub).
478 XML input is accepted on stdin.
479 XML output is sent to stdout; progress reports are sent to stderr.
481 Usage: php dumpTextPass.php [<options>]
482 Options:
483 --stub=<type>:<file> To load a compressed stub dump instead of stdin
484 --prefetch=<type>:<file> Use a prior dump file as a text source, to save
485 pressure on the database.
486 (Requires the XMLReader extension)
487 --quiet Don't dump status reports to stderr.
488 --report=n Report position and speed after every n pages processed.
489 (Default: 100)
490 --server=h Force reading from MySQL server h
491 --current Base ETA on number of pages in database instead of all revisions
492 --spawn Spawn a subprocess for loading text records
493 --help Display this help message
494 ENDS