Follow up r72799.
[lhc/web/wiklou.git] / maintenance / dumpTextPass.php
1 <?php
2 /**
3 * Copyright (C) 2005 Brion Vibber <brion@pobox.com>
4 * http://www.mediawiki.org/
5 *
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.
10 *
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.
15 *
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
20 *
21 * @file
22 * @ingroup Maintenance
23 */
24
25 $originalDir = getcwd();
26
27 require_once( dirname( __FILE__ ) . '/commandLine.inc' );
28 require_once( 'backup.inc' );
29
30 /**
31 * @ingroup Maintenance
32 */
33 class TextPassDumper extends BackupDumper {
34 var $prefetch = null;
35 var $input = "php://stdin";
36 var $history = WikiExporter::FULL;
37 var $fetchCount = 0;
38 var $prefetchCount = 0;
39
40 var $failures = 0;
41 var $maxFailures = 5;
42 var $failedTextRetrievals = 0;
43 var $maxConsecutiveFailedTextRetrievals = 200;
44 var $failureTimeout = 5; // Seconds to sleep after db failure
45
46 var $php = "php";
47 var $spawn = false;
48 var $spawnProc = false;
49 var $spawnWrite = false;
50 var $spawnRead = false;
51 var $spawnErr = false;
52
53 function dump() {
54 # This shouldn't happen if on console... ;)
55 header( 'Content-type: text/html; charset=UTF-8' );
56
57 # Notice messages will foul up your XML output even if they're
58 # relatively harmless.
59 if ( ini_get( 'display_errors' ) )
60 ini_set( 'display_errors', 'stderr' );
61
62 $this->initProgress( $this->history );
63
64 $this->db = $this->backupDb();
65
66 $this->egress = new ExportProgressFilter( $this->sink, $this );
67
68 $input = fopen( $this->input, "rt" );
69 $result = $this->readDump( $input );
70
71 if ( WikiError::isError( $result ) ) {
72 wfDie( $result->getMessage() );
73 }
74
75 if ( $this->spawnProc ) {
76 $this->closeSpawn();
77 }
78
79 $this->report( true );
80 }
81
82 function processOption( $opt, $val, $param ) {
83 global $IP;
84 $url = $this->processFileOpt( $val, $param );
85
86 switch( $opt ) {
87 case 'prefetch':
88 require_once "$IP/maintenance/backupPrefetch.inc";
89 $this->prefetch = new BaseDump( $url );
90 break;
91 case 'stub':
92 $this->input = $url;
93 break;
94 case 'current':
95 $this->history = WikiExporter::CURRENT;
96 break;
97 case 'full':
98 $this->history = WikiExporter::FULL;
99 break;
100 case 'spawn':
101 $this->spawn = true;
102 if ( $val ) {
103 $this->php = $val;
104 }
105 break;
106 }
107 }
108
109 function processFileOpt( $val, $param ) {
110 switch( $val ) {
111 case "file":
112 return $param;
113 case "gzip":
114 return "compress.zlib://$param";
115 case "bzip2":
116 return "compress.bzip2://$param";
117 case "7zip":
118 return "mediawiki.compress.7z://$param";
119 default:
120 return $val;
121 }
122 }
123
124 /**
125 * Overridden to include prefetch ratio if enabled.
126 */
127 function showReport() {
128 if ( !$this->prefetch ) {
129 return parent::showReport();
130 }
131
132 if ( $this->reporting ) {
133 $delta = wfTime() - $this->startTime;
134 $now = wfTimestamp( TS_DB );
135 if ( $delta ) {
136 $rate = $this->pageCount / $delta;
137 $revrate = $this->revCount / $delta;
138 $portion = $this->revCount / $this->maxCount;
139 $eta = $this->startTime + $delta / $portion;
140 $etats = wfTimestamp( TS_DB, intval( $eta ) );
141 $fetchrate = 100.0 * $this->prefetchCount / $this->fetchCount;
142 } else {
143 $rate = '-';
144 $revrate = '-';
145 $etats = '-';
146 $fetchrate = '-';
147 }
148 $this->progress( sprintf( "%s: %s %d pages (%0.3f/sec), %d revs (%0.3f/sec), %0.1f%% prefetched, ETA %s [max %d]",
149 $now, wfWikiID(), $this->pageCount, $rate, $this->revCount, $revrate, $fetchrate, $etats, $this->maxCount ) );
150 }
151 }
152
153 function readDump( $input ) {
154 $this->buffer = "";
155 $this->openElement = false;
156 $this->atStart = true;
157 $this->state = "";
158 $this->lastName = "";
159 $this->thisPage = 0;
160 $this->thisRev = 0;
161
162 $parser = xml_parser_create( "UTF-8" );
163 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
164
165 xml_set_element_handler( $parser, array( &$this, 'startElement' ), array( &$this, 'endElement' ) );
166 xml_set_character_data_handler( $parser, array( &$this, 'characterData' ) );
167
168 $offset = 0; // for context extraction on error reporting
169 $bufferSize = 512 * 1024;
170 do {
171 $chunk = fread( $input, $bufferSize );
172 if ( !xml_parse( $parser, $chunk, feof( $input ) ) ) {
173 wfDebug( "TextDumpPass::readDump encountered XML parsing error\n" );
174 return new WikiXmlError( $parser, 'XML import parse failure', $chunk, $offset );
175 }
176 $offset += strlen( $chunk );
177 } while ( $chunk !== false && !feof( $input ) );
178 xml_parser_free( $parser );
179
180 return true;
181 }
182
183 function getText( $id ) {
184 $this->fetchCount++;
185 if ( isset( $this->prefetch ) ) {
186 $text = $this->prefetch->prefetch( $this->thisPage, $this->thisRev );
187 if ( $text === null ) {
188 // Entry missing from prefetch dump
189 } elseif ( $text === "" ) {
190 // Blank entries may indicate that the prior dump was broken.
191 // To be safe, reload it.
192 } else {
193 $dbr = wfGetDB( DB_SLAVE );
194 $revID = intval($this->thisRev);
195 $revLength = $dbr->selectField( 'revision', 'rev_len', array('rev_id' => $revID ) );
196 // if length of rev text in file doesn't match length in db, we reload
197 // this avoids carrying forward broken data from previous xml dumps
198 if( strlen($text) == $revLength ) {
199 $this->prefetchCount++;
200 return $text;
201 }
202 }
203 }
204 return $this->doGetText( $id );
205 }
206
207 private function doGetText( $id ) {
208
209 $id = intval( $id );
210 $this->failures = 0;
211 $ex = new MWException( "Graceful storage failure" );
212 while (true) {
213 if ( $this->spawn ) {
214 if ($this->failures) {
215 // we don't know why it failed, could be the child process
216 // borked, could be db entry busted, could be db server out to lunch,
217 // so cover all bases
218 $this->closeSpawn();
219 $this->openSpawn();
220 }
221 $text = $this->getTextSpawned( $id );
222 } else {
223 $text = $this->getTextDbSafe( $id );
224 }
225 if ( $text === false ) {
226 $this->failures++;
227 if ( $this->failures > $this->maxFailures) {
228 $this->progress( "Failed to retrieve revision text for text id ".
229 "$id after $this->maxFailures tries, giving up" );
230 // were there so many bad retrievals in a row we want to bail?
231 // at some point we have to declare the dump irretrievably broken
232 $this->failedTextRetrievals++;
233 if ($this->failedTextRetrievals > $this->maxConsecutiveFailedTextRetrievals) {
234 throw $ex;
235 }
236 else {
237 // would be nice to return something better to the caller someday,
238 // log what we know about the failure and about the revision
239 return("");
240 }
241 } else {
242 $this->progress( "Error $this->failures " .
243 "of allowed $this->maxFailures retrieving revision text for text id $id! " .
244 "Pausing $this->failureTimeout seconds before retry..." );
245 sleep( $this->failureTimeout );
246 }
247 } else {
248 $this->failedTextRetrievals= 0;
249 return( $text );
250 }
251 }
252
253 }
254
255 /**
256 * Fetch a text revision from the database, retrying in case of failure.
257 * This may survive some transitory errors by reconnecting, but
258 * may not survive a long-term server outage.
259 */
260 private function getTextDbSafe( $id ) {
261 while ( true ) {
262 try {
263 $text = $this->getTextDb( $id );
264 $ex = new MWException( "Graceful storage failure" );
265 } catch ( DBQueryError $ex ) {
266 $text = false;
267 }
268 return $text;
269 }
270 }
271
272 /**
273 * May throw a database error if, say, the server dies during query.
274 */
275 private function getTextDb( $id ) {
276 global $wgContLang;
277 $row = $this->db->selectRow( 'text',
278 array( 'old_text', 'old_flags' ),
279 array( 'old_id' => $id ),
280 'TextPassDumper::getText' );
281 $text = Revision::getRevisionText( $row );
282 if ( $text === false ) {
283 return false;
284 }
285 $stripped = str_replace( "\r", "", $text );
286 $normalized = $wgContLang->normalize( $stripped );
287 return $normalized;
288 }
289
290 private function getTextSpawned( $id ) {
291 wfSuppressWarnings();
292 if ( !$this->spawnProc ) {
293 // First time?
294 $this->openSpawn();
295 }
296 $text = $this->getTextSpawnedOnce( $id );
297 wfRestoreWarnings();
298 return $text;
299 }
300
301 function openSpawn() {
302 global $IP, $wgDBname;
303
304 $cmd = implode( " ",
305 array_map( 'wfEscapeShellArg',
306 array(
307 $this->php,
308 "$IP/maintenance/fetchText.php",
309 $wgDBname ) ) );
310 $spec = array(
311 0 => array( "pipe", "r" ),
312 1 => array( "pipe", "w" ),
313 2 => array( "file", "/dev/null", "a" ) );
314 $pipes = array();
315
316 $this->progress( "Spawning database subprocess: $cmd" );
317 $this->spawnProc = proc_open( $cmd, $spec, $pipes );
318 if ( !$this->spawnProc ) {
319 // shit
320 $this->progress( "Subprocess spawn failed." );
321 return false;
322 }
323 list(
324 $this->spawnWrite, // -> stdin
325 $this->spawnRead, // <- stdout
326 ) = $pipes;
327
328 return true;
329 }
330
331 private function closeSpawn() {
332 wfSuppressWarnings();
333 if ( $this->spawnRead )
334 fclose( $this->spawnRead );
335 $this->spawnRead = false;
336 if ( $this->spawnWrite )
337 fclose( $this->spawnWrite );
338 $this->spawnWrite = false;
339 if ( $this->spawnErr )
340 fclose( $this->spawnErr );
341 $this->spawnErr = false;
342 if ( $this->spawnProc )
343 pclose( $this->spawnProc );
344 $this->spawnProc = false;
345 wfRestoreWarnings();
346 }
347
348 private function getTextSpawnedOnce( $id ) {
349 global $wgContLang;
350
351 $ok = fwrite( $this->spawnWrite, "$id\n" );
352 // $this->progress( ">> $id" );
353 if ( !$ok ) return false;
354
355 $ok = fflush( $this->spawnWrite );
356 // $this->progress( ">> [flush]" );
357 if ( !$ok ) return false;
358
359 // check that the text id they are sending is the one we asked for
360 // this avoids out of sync revision text errors we have encountered in the past
361 $newId = fgets( $this->spawnRead );
362 if ( $newId === false ) {
363 return false;
364 }
365 if ( $id != intval( $newId ) ) {
366 return false;
367 }
368
369 $len = fgets( $this->spawnRead );
370 // $this->progress( "<< " . trim( $len ) );
371 if ( $len === false ) return false;
372
373 $nbytes = intval( $len );
374 // actual error, not zero-length text
375 if ($nbytes < 0 ) return false;
376
377 $text = "";
378
379 // Subprocess may not send everything at once, we have to loop.
380 while ( $nbytes > strlen( $text ) ) {
381 $buffer = fread( $this->spawnRead, $nbytes - strlen( $text ) );
382 if ( $buffer === false ) break;
383 $text .= $buffer;
384 }
385
386 $gotbytes = strlen( $text );
387 if ( $gotbytes != $nbytes ) {
388 $this->progress( "Expected $nbytes bytes from database subprocess, got $gotbytes " );
389 return false;
390 }
391
392 // Do normalization in the dump thread...
393 $stripped = str_replace( "\r", "", $text );
394 $normalized = $wgContLang->normalize( $stripped );
395 return $normalized;
396 }
397
398 function startElement( $parser, $name, $attribs ) {
399 $this->clearOpenElement( null );
400 $this->lastName = $name;
401
402 if ( $name == 'revision' ) {
403 $this->state = $name;
404 $this->egress->writeOpenPage( null, $this->buffer );
405 $this->buffer = "";
406 } elseif ( $name == 'page' ) {
407 $this->state = $name;
408 if ( $this->atStart ) {
409 $this->egress->writeOpenStream( $this->buffer );
410 $this->buffer = "";
411 $this->atStart = false;
412 }
413 }
414
415 if ( $name == "text" && isset( $attribs['id'] ) ) {
416 $text = $this->getText( $attribs['id'] );
417 $this->openElement = array( $name, array( 'xml:space' => 'preserve' ) );
418 if ( strlen( $text ) > 0 ) {
419 $this->characterData( $parser, $text );
420 }
421 } else {
422 $this->openElement = array( $name, $attribs );
423 }
424 }
425
426 function endElement( $parser, $name ) {
427 if ( $this->openElement ) {
428 $this->clearOpenElement( "" );
429 } else {
430 $this->buffer .= "</$name>";
431 }
432
433 if ( $name == 'revision' ) {
434 $this->egress->writeRevision( null, $this->buffer );
435 $this->buffer = "";
436 $this->thisRev = "";
437 } elseif ( $name == 'page' ) {
438 $this->egress->writeClosePage( $this->buffer );
439 $this->buffer = "";
440 $this->thisPage = "";
441 } elseif ( $name == 'mediawiki' ) {
442 $this->egress->writeCloseStream( $this->buffer );
443 $this->buffer = "";
444 }
445 }
446
447 function characterData( $parser, $data ) {
448 $this->clearOpenElement( null );
449 if ( $this->lastName == "id" ) {
450 if ( $this->state == "revision" ) {
451 $this->thisRev .= $data;
452 } elseif ( $this->state == "page" ) {
453 $this->thisPage .= $data;
454 }
455 }
456 $this->buffer .= htmlspecialchars( $data );
457 }
458
459 function clearOpenElement( $style ) {
460 if ( $this->openElement ) {
461 $this->buffer .= Xml::element( $this->openElement[0], $this->openElement[1], $style );
462 $this->openElement = false;
463 }
464 }
465 }
466
467
468 $dumper = new TextPassDumper( $argv );
469
470 if ( true ) {
471 $dumper->dump();
472 } else {
473 $dumper->progress( <<<ENDS
474 This script postprocesses XML dumps from dumpBackup.php to add
475 page text which was stubbed out (using --stub).
476
477 XML input is accepted on stdin.
478 XML output is sent to stdout; progress reports are sent to stderr.
479
480 Usage: php dumpTextPass.php [<options>]
481 Options:
482 --stub=<type>:<file> To load a compressed stub dump instead of stdin
483 --prefetch=<type>:<file> Use a prior dump file as a text source, to save
484 pressure on the database.
485 (Requires PHP 5.0+ and the XMLReader PECL extension)
486 --quiet Don't dump status reports to stderr.
487 --report=n Report position and speed after every n pages processed.
488 (Default: 100)
489 --server=h Force reading from MySQL server h
490 --current Base ETA on number of pages in database instead of all revisions
491 --spawn Spawn a subprocess for loading text records
492 ENDS
493 );
494 }
495
496