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