using .append() instead of innerHTML+=. The latter replaces the html and causes all...
[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 ) { // Entry missing from prefetch dump
218 $dbr = wfGetDB( DB_SLAVE );
219 $revID = intval( $this->thisRev );
220 $revLength = $dbr->selectField( 'revision', 'rev_len', array( 'rev_id' => $revID ) );
221 // if length of rev text in file doesn't match length in db, we reload
222 // this avoids carrying forward broken data from previous xml dumps
223 if( strlen( $text ) == $revLength ) {
224 $this->prefetchCount++;
225 return $text;
226 }
227 }
228 }
229 return $this->doGetText( $id );
230 }
231
232 private function doGetText( $id ) {
233 $id = intval( $id );
234 $this->failures = 0;
235 $ex = new MWException( "Graceful storage failure" );
236 while (true) {
237 if ( $this->spawn ) {
238 if ($this->failures) {
239 // we don't know why it failed, could be the child process
240 // borked, could be db entry busted, could be db server out to lunch,
241 // so cover all bases
242 $this->closeSpawn();
243 $this->openSpawn();
244 }
245 $text = $this->getTextSpawned( $id );
246 } else {
247 $text = $this->getTextDbSafe( $id );
248 }
249 if ( $text === false ) {
250 $this->failures++;
251 if ( $this->failures > $this->maxFailures) {
252 $this->progress( "Failed to retrieve revision text for text id ".
253 "$id after $this->maxFailures tries, giving up" );
254 // were there so many bad retrievals in a row we want to bail?
255 // at some point we have to declare the dump irretrievably broken
256 $this->failedTextRetrievals++;
257 if ($this->failedTextRetrievals > $this->maxConsecutiveFailedTextRetrievals) {
258 throw $ex;
259 }
260 else {
261 // would be nice to return something better to the caller someday,
262 // log what we know about the failure and about the revision
263 return("");
264 }
265 } else {
266 $this->progress( "Error $this->failures " .
267 "of allowed $this->maxFailures retrieving revision text for text id $id! " .
268 "Pausing $this->failureTimeout seconds before retry..." );
269 sleep( $this->failureTimeout );
270 }
271 } else {
272 $this->failedTextRetrievals= 0;
273 return( $text );
274 }
275 }
276
277 }
278
279 /**
280 * Fetch a text revision from the database, retrying in case of failure.
281 * This may survive some transitory errors by reconnecting, but
282 * may not survive a long-term server outage.
283 */
284 private function getTextDbSafe( $id ) {
285 while ( true ) {
286 try {
287 $text = $this->getTextDb( $id );
288 } catch ( DBQueryError $ex ) {
289 $text = false;
290 }
291 return $text;
292 }
293 }
294
295 /**
296 * May throw a database error if, say, the server dies during query.
297 */
298 private function getTextDb( $id ) {
299 global $wgContLang;
300 $row = $this->db->selectRow( 'text',
301 array( 'old_text', 'old_flags' ),
302 array( 'old_id' => $id ),
303 __METHOD__ );
304 $text = Revision::getRevisionText( $row );
305 if ( $text === false ) {
306 return false;
307 }
308 $stripped = str_replace( "\r", "", $text );
309 $normalized = $wgContLang->normalize( $stripped );
310 return $normalized;
311 }
312
313 private function getTextSpawned( $id ) {
314 wfSuppressWarnings();
315 if ( !$this->spawnProc ) {
316 // First time?
317 $this->openSpawn();
318 }
319 $text = $this->getTextSpawnedOnce( $id );
320 wfRestoreWarnings();
321 return $text;
322 }
323
324 function openSpawn() {
325 global $IP;
326
327 $cmd = implode( " ",
328 array_map( 'wfEscapeShellArg',
329 array(
330 $this->php,
331 "$IP/maintenance/fetchText.php",
332 '--wiki', wfWikiID() ) ) );
333 $spec = array(
334 0 => array( "pipe", "r" ),
335 1 => array( "pipe", "w" ),
336 2 => array( "file", "/dev/null", "a" ) );
337 $pipes = array();
338
339 $this->progress( "Spawning database subprocess: $cmd" );
340 $this->spawnProc = proc_open( $cmd, $spec, $pipes );
341 if ( !$this->spawnProc ) {
342 // shit
343 $this->progress( "Subprocess spawn failed." );
344 return false;
345 }
346 list(
347 $this->spawnWrite, // -> stdin
348 $this->spawnRead, // <- stdout
349 ) = $pipes;
350
351 return true;
352 }
353
354 private function closeSpawn() {
355 wfSuppressWarnings();
356 if ( $this->spawnRead )
357 fclose( $this->spawnRead );
358 $this->spawnRead = false;
359 if ( $this->spawnWrite )
360 fclose( $this->spawnWrite );
361 $this->spawnWrite = false;
362 if ( $this->spawnErr )
363 fclose( $this->spawnErr );
364 $this->spawnErr = false;
365 if ( $this->spawnProc )
366 pclose( $this->spawnProc );
367 $this->spawnProc = false;
368 wfRestoreWarnings();
369 }
370
371 private function getTextSpawnedOnce( $id ) {
372 global $wgContLang;
373
374 $ok = fwrite( $this->spawnWrite, "$id\n" );
375 // $this->progress( ">> $id" );
376 if ( !$ok ) return false;
377
378 $ok = fflush( $this->spawnWrite );
379 // $this->progress( ">> [flush]" );
380 if ( !$ok ) return false;
381
382 // check that the text id they are sending is the one we asked for
383 // this avoids out of sync revision text errors we have encountered in the past
384 $newId = fgets( $this->spawnRead );
385 if ( $newId === false ) {
386 return false;
387 }
388 if ( $id != intval( $newId ) ) {
389 return false;
390 }
391
392 $len = fgets( $this->spawnRead );
393 // $this->progress( "<< " . trim( $len ) );
394 if ( $len === false ) return false;
395
396 $nbytes = intval( $len );
397 // actual error, not zero-length text
398 if ($nbytes < 0 ) return false;
399
400 $text = "";
401
402 // Subprocess may not send everything at once, we have to loop.
403 while ( $nbytes > strlen( $text ) ) {
404 $buffer = fread( $this->spawnRead, $nbytes - strlen( $text ) );
405 if ( $buffer === false ) break;
406 $text .= $buffer;
407 }
408
409 $gotbytes = strlen( $text );
410 if ( $gotbytes != $nbytes ) {
411 $this->progress( "Expected $nbytes bytes from database subprocess, got $gotbytes " );
412 return false;
413 }
414
415 // Do normalization in the dump thread...
416 $stripped = str_replace( "\r", "", $text );
417 $normalized = $wgContLang->normalize( $stripped );
418 return $normalized;
419 }
420 }
421
422
423 $dumper = new TextPassDumper( $argv );
424
425 if ( !isset( $options['help'] ) ) {
426 $dumper->dump( WikiExporter::FULL );
427 } else {
428 $dumper->progress( <<<ENDS
429 This script postprocesses XML dumps from dumpBackup.php to add
430 page text which was stubbed out (using --stub).
431
432 XML input is accepted on stdin.
433 XML output is sent to stdout; progress reports are sent to stderr.
434
435 Usage: php dumpTextPass.php [<options>]
436 Options:
437 --stub=<type>:<file> To load a compressed stub dump instead of stdin
438 --prefetch=<type>:<file> Use a prior dump file as a text source, to save
439 pressure on the database.
440 --quiet Don't dump status reports to stderr.
441 --report=n Report position and speed after every n pages processed.
442 (Default: 100)
443 --server=h Force reading from MySQL server h
444 --current Base ETA on number of pages in database instead of all revisions
445 --spawn Spawn a subprocess for loading text records
446 --help Display this help message
447 ENDS
448 );
449 }
450
451