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