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