More reversion of r77297, 2 of 2 commits to keep it readable in CR (hopefully)
[lhc/web/wiklou.git] / maintenance / dumpTextPass.php
1 <?php
2 /**
3 * Script that postprocesses XML dumps from dumpBackup.php to add page text
4 *
5 * Copyright (C) 2005 Brion Vibber <brion@pobox.com>
6 * http://www.mediawiki.org/
7 *
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.
12 *
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.
17 *
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
22 *
23 * @file
24 * @ingroup Maintenance
25 */
26
27 $originalDir = getcwd();
28
29 require_once( dirname( __FILE__ ) . '/commandLine.inc' );
30 require_once( 'backup.inc' );
31
32 /**
33 * @ingroup Maintenance
34 */
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;
41
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
47
48 var $php = "php";
49 var $spawn = false;
50 var $spawnProc = false;
51 var $spawnWrite = false;
52 var $spawnRead = false;
53 var $spawnErr = false;
54
55 function dump( $history, $text = WikiExporter::TEXT ) {
56 # This shouldn't happen if on console... ;)
57 header( 'Content-type: text/html; charset=UTF-8' );
58
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' );
63
64 $this->initProgress( $this->history );
65
66 $this->db = $this->backupDb();
67
68 $this->egress = new ExportProgressFilter( $this->sink, $this );
69
70 $input = fopen( $this->input, "rt" );
71 $result = $this->readDump( $input );
72
73 if ( WikiError::isError( $result ) ) {
74 wfDie( $result->getMessage() );
75 }
76
77 if ( $this->spawnProc ) {
78 $this->closeSpawn();
79 }
80
81 $this->report( true );
82 }
83
84 function processOption( $opt, $val, $param ) {
85 global $IP;
86 $url = $this->processFileOpt( $val, $param );
87
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;
106 }
107 break;
108 }
109 }
110
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;
123 }
124 }
125
126 /**
127 * Overridden to include prefetch ratio if enabled.
128 */
129 function showReport() {
130 if ( !$this->prefetch ) {
131 return parent::showReport();
132 }
133
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 = '-';
149 }
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 ) );
152 }
153 }
154
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;
163
164 $parser = xml_parser_create( "UTF-8" );
165 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
166
167 xml_set_element_handler( $parser, array( &$this, 'startElement' ), array( &$this, 'endElement' ) );
168 xml_set_character_data_handler( $parser, array( &$this, 'characterData' ) );
169
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 );
177 }
178 $offset += strlen( $chunk );
179 } while ( $chunk !== false && !feof( $input ) );
180 xml_parser_free( $parser );
181
182 return true;
183 }
184
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;
203 }
204 }
205 }
206 return $this->doGetText( $id );
207 }
208
209 private function doGetText( $id ) {
210
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();
222 }
223 $text = $this->getTextSpawned( $id );
224 } else {
225 $text = $this->getTextDbSafe( $id );
226 }
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;
237 }
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("");
242 }
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 );
248 }
249 } else {
250 $this->failedTextRetrievals= 0;
251 return( $text );
252 }
253 }
254
255 }
256
257 /**
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.
261 */
262 private function getTextDbSafe( $id ) {
263 while ( true ) {
264 try {
265 $text = $this->getTextDb( $id );
266 } catch ( DBQueryError $ex ) {
267 $text = false;
268 }
269 return $text;
270 }
271 }
272
273 /**
274 * May throw a database error if, say, the server dies during query.
275 */
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;
285 }
286 $stripped = str_replace( "\r", "", $text );
287 $normalized = $wgContLang->normalize( $stripped );
288 return $normalized;
289 }
290
291 private function getTextSpawned( $id ) {
292 wfSuppressWarnings();
293 if ( !$this->spawnProc ) {
294 // First time?
295 $this->openSpawn();
296 }
297 $text = $this->getTextSpawnedOnce( $id );
298 wfRestoreWarnings();
299 return $text;
300 }
301
302 function openSpawn() {
303 global $IP, $wgDBname;
304
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();
316
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;
323 }
324 list(
325 $this->spawnWrite, // -> stdin
326 $this->spawnRead, // <- stdout
327 ) = $pipes;
328
329 return true;
330 }
331
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();
347 }
348
349 private function getTextSpawnedOnce( $id ) {
350 global $wgContLang;
351
352 $ok = fwrite( $this->spawnWrite, "$id\n" );
353 // $this->progress( ">> $id" );
354 if ( !$ok ) return false;
355
356 $ok = fflush( $this->spawnWrite );
357 // $this->progress( ">> [flush]" );
358 if ( !$ok ) return false;
359
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;
365 }
366 if ( $id != intval( $newId ) ) {
367 return false;
368 }
369
370 $len = fgets( $this->spawnRead );
371 // $this->progress( "<< " . trim( $len ) );
372 if ( $len === false ) return false;
373
374 $nbytes = intval( $len );
375 // actual error, not zero-length text
376 if ($nbytes < 0 ) return false;
377
378 $text = "";
379
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;
385 }
386
387 $gotbytes = strlen( $text );
388 if ( $gotbytes != $nbytes ) {
389 $this->progress( "Expected $nbytes bytes from database subprocess, got $gotbytes " );
390 return false;
391 }
392
393 // Do normalization in the dump thread...
394 $stripped = str_replace( "\r", "", $text );
395 $normalized = $wgContLang->normalize( $stripped );
396 return $normalized;
397 }
398
399 function startElement( $parser, $name, $attribs ) {
400 $this->clearOpenElement( null );
401 $this->lastName = $name;
402
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;
413 }
414 }
415
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 );
421 }
422 } else {
423 $this->openElement = array( $name, $attribs );
424 }
425 }
426
427 function endElement( $parser, $name ) {
428 if ( $this->openElement ) {
429 $this->clearOpenElement( "" );
430 } else {
431 $this->buffer .= "</$name>";
432 }
433
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 = "";
445 }
446 }
447
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;
455 }
456 }
457 $this->buffer .= htmlspecialchars( $data );
458 }
459
460 function clearOpenElement( $style ) {
461 if ( $this->openElement ) {
462 $this->buffer .= Xml::element( $this->openElement[0], $this->openElement[1], $style );
463 $this->openElement = false;
464 }
465 }
466 }
467
468
469 $dumper = new TextPassDumper( $argv );
470
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).
477
478 XML input is accepted on stdin.
479 XML output is sent to stdout; progress reports are sent to stderr.
480
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
495 );
496 }
497
498