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