* (Bug 25451) Language::time() and ::date() misfunction when given timestamps in...
[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 $ex = new MWException( "Graceful storage failure" );
267 } catch ( DBQueryError $ex ) {
268 $text = false;
269 }
270 return $text;
271 }
272 }
273
274 /**
275 * May throw a database error if, say, the server dies during query.
276 */
277 private function getTextDb( $id ) {
278 global $wgContLang;
279 $row = $this->db->selectRow( 'text',
280 array( 'old_text', 'old_flags' ),
281 array( 'old_id' => $id ),
282 __METHOD__ );
283 $text = Revision::getRevisionText( $row );
284 if ( $text === false ) {
285 return false;
286 }
287 $stripped = str_replace( "\r", "", $text );
288 $normalized = $wgContLang->normalize( $stripped );
289 return $normalized;
290 }
291
292 private function getTextSpawned( $id ) {
293 wfSuppressWarnings();
294 if ( !$this->spawnProc ) {
295 // First time?
296 $this->openSpawn();
297 }
298 $text = $this->getTextSpawnedOnce( $id );
299 wfRestoreWarnings();
300 return $text;
301 }
302
303 function openSpawn() {
304 global $IP, $wgDBname;
305
306 $cmd = implode( " ",
307 array_map( 'wfEscapeShellArg',
308 array(
309 $this->php,
310 "$IP/maintenance/fetchText.php",
311 $wgDBname ) ) );
312 $spec = array(
313 0 => array( "pipe", "r" ),
314 1 => array( "pipe", "w" ),
315 2 => array( "file", "/dev/null", "a" ) );
316 $pipes = array();
317
318 $this->progress( "Spawning database subprocess: $cmd" );
319 $this->spawnProc = proc_open( $cmd, $spec, $pipes );
320 if ( !$this->spawnProc ) {
321 // shit
322 $this->progress( "Subprocess spawn failed." );
323 return false;
324 }
325 list(
326 $this->spawnWrite, // -> stdin
327 $this->spawnRead, // <- stdout
328 ) = $pipes;
329
330 return true;
331 }
332
333 private function closeSpawn() {
334 wfSuppressWarnings();
335 if ( $this->spawnRead )
336 fclose( $this->spawnRead );
337 $this->spawnRead = false;
338 if ( $this->spawnWrite )
339 fclose( $this->spawnWrite );
340 $this->spawnWrite = false;
341 if ( $this->spawnErr )
342 fclose( $this->spawnErr );
343 $this->spawnErr = false;
344 if ( $this->spawnProc )
345 pclose( $this->spawnProc );
346 $this->spawnProc = false;
347 wfRestoreWarnings();
348 }
349
350 private function getTextSpawnedOnce( $id ) {
351 global $wgContLang;
352
353 $ok = fwrite( $this->spawnWrite, "$id\n" );
354 // $this->progress( ">> $id" );
355 if ( !$ok ) return false;
356
357 $ok = fflush( $this->spawnWrite );
358 // $this->progress( ">> [flush]" );
359 if ( !$ok ) return false;
360
361 // check that the text id they are sending is the one we asked for
362 // this avoids out of sync revision text errors we have encountered in the past
363 $newId = fgets( $this->spawnRead );
364 if ( $newId === false ) {
365 return false;
366 }
367 if ( $id != intval( $newId ) ) {
368 return false;
369 }
370
371 $len = fgets( $this->spawnRead );
372 // $this->progress( "<< " . trim( $len ) );
373 if ( $len === false ) return false;
374
375 $nbytes = intval( $len );
376 // actual error, not zero-length text
377 if ($nbytes < 0 ) return false;
378
379 $text = "";
380
381 // Subprocess may not send everything at once, we have to loop.
382 while ( $nbytes > strlen( $text ) ) {
383 $buffer = fread( $this->spawnRead, $nbytes - strlen( $text ) );
384 if ( $buffer === false ) break;
385 $text .= $buffer;
386 }
387
388 $gotbytes = strlen( $text );
389 if ( $gotbytes != $nbytes ) {
390 $this->progress( "Expected $nbytes bytes from database subprocess, got $gotbytes " );
391 return false;
392 }
393
394 // Do normalization in the dump thread...
395 $stripped = str_replace( "\r", "", $text );
396 $normalized = $wgContLang->normalize( $stripped );
397 return $normalized;
398 }
399
400 function startElement( $parser, $name, $attribs ) {
401 $this->clearOpenElement( null );
402 $this->lastName = $name;
403
404 if ( $name == 'revision' ) {
405 $this->state = $name;
406 $this->egress->writeOpenPage( null, $this->buffer );
407 $this->buffer = "";
408 } elseif ( $name == 'page' ) {
409 $this->state = $name;
410 if ( $this->atStart ) {
411 $this->egress->writeOpenStream( $this->buffer );
412 $this->buffer = "";
413 $this->atStart = false;
414 }
415 }
416
417 if ( $name == "text" && isset( $attribs['id'] ) ) {
418 $text = $this->getText( $attribs['id'] );
419 $this->openElement = array( $name, array( 'xml:space' => 'preserve' ) );
420 if ( strlen( $text ) > 0 ) {
421 $this->characterData( $parser, $text );
422 }
423 } else {
424 $this->openElement = array( $name, $attribs );
425 }
426 }
427
428 function endElement( $parser, $name ) {
429 if ( $this->openElement ) {
430 $this->clearOpenElement( "" );
431 } else {
432 $this->buffer .= "</$name>";
433 }
434
435 if ( $name == 'revision' ) {
436 $this->egress->writeRevision( null, $this->buffer );
437 $this->buffer = "";
438 $this->thisRev = "";
439 } elseif ( $name == 'page' ) {
440 $this->egress->writeClosePage( $this->buffer );
441 $this->buffer = "";
442 $this->thisPage = "";
443 } elseif ( $name == 'mediawiki' ) {
444 $this->egress->writeCloseStream( $this->buffer );
445 $this->buffer = "";
446 }
447 }
448
449 function characterData( $parser, $data ) {
450 $this->clearOpenElement( null );
451 if ( $this->lastName == "id" ) {
452 if ( $this->state == "revision" ) {
453 $this->thisRev .= $data;
454 } elseif ( $this->state == "page" ) {
455 $this->thisPage .= $data;
456 }
457 }
458 $this->buffer .= htmlspecialchars( $data );
459 }
460
461 function clearOpenElement( $style ) {
462 if ( $this->openElement ) {
463 $this->buffer .= Xml::element( $this->openElement[0], $this->openElement[1], $style );
464 $this->openElement = false;
465 }
466 }
467 }
468
469
470 $dumper = new TextPassDumper( $argv );
471
472 if ( !isset( $options['help'] ) ) {
473 $dumper->dump( true );
474 } else {
475 $dumper->progress( <<<ENDS
476 This script postprocesses XML dumps from dumpBackup.php to add
477 page text which was stubbed out (using --stub).
478
479 XML input is accepted on stdin.
480 XML output is sent to stdout; progress reports are sent to stderr.
481
482 Usage: php dumpTextPass.php [<options>]
483 Options:
484 --stub=<type>:<file> To load a compressed stub dump instead of stdin
485 --prefetch=<type>:<file> Use a prior dump file as a text source, to save
486 pressure on the database.
487 (Requires the XMLReader extension)
488 --quiet Don't dump status reports to stderr.
489 --report=n Report position and speed after every n pages processed.
490 (Default: 100)
491 --server=h Force reading from MySQL server h
492 --current Base ETA on number of pages in database instead of all revisions
493 --spawn Spawn a subprocess for loading text records
494 --help Display this help message
495 ENDS
496 );
497 }
498
499