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