Partial revert r78593 (adding --upgrade option to install.php). Rather than supportin...
[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 $fileURIs = explode(';',$param);
99 foreach ( $fileURIs as $URI ) {
100 switch( $val ) {
101 case "file":
102 $newURI = $URI;
103 break;
104 case "gzip":
105 $newURI = "compress.zlib://$URI";
106 break;
107 case "bzip2":
108 $newURI = "compress.bzip2://$URI";
109 break;
110 case "7zip":
111 $newURI = "mediawiki.compress.7z://$URI";
112 break;
113 default:
114 $newURI = $URI;
115 }
116 $newFileURIs[] = $newURI;
117 }
118 $val = implode( ';', $newFileURIs );
119 return $val;
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() {
152 $state = '';
153 $lastName = '';
154 $this->thisPage = 0;
155 $this->thisRev = 0;
156
157 $reader = new XMLReader();
158 $reader->open( $this->input );
159 $writer = new XMLWriter();
160 $writer->openMemory();
161
162
163 while ( $reader->read() ) {
164 $tag = $reader->name;
165 $type = $reader->nodeType;
166
167 if ( $type == XmlReader::END_ELEMENT ) {
168 $writer->endElement();
169
170 if ( $tag == 'revision' ) {
171 $this->revCount();
172 $this->thisRev = '';
173 } elseif ( $tag == 'page' ) {
174 $this->reportPage();
175 $this->thisPage = '';
176 }
177 } elseif ( $type == XmlReader::ELEMENT ) {
178 $attribs = array();
179 if ( $reader->hasAttributes ) {
180 for ( $i = 0; $reader->moveToAttributeNo( $i ); $i++ ) {
181 $attribs[$reader->name] = $reader->value;
182 }
183 }
184
185 if ( $reader->isEmptyElement && $tag == 'text' && isset( $attribs['id'] ) ) {
186 $writer->startElement( 'text' );
187 $writer->writeAttribute( 'xml:space', 'preserve' );
188 $text = $this->getText( $attribs['id'] );
189 if ( strlen( $text ) ) {
190 $writer->text( $text );
191 }
192 $writer->endElement();
193 } else {
194 $writer->startElement( $tag );
195 foreach( $attribs as $name => $val ) {
196 $writer->writeAttribute( $name, $val );
197 }
198 if ( $reader->isEmptyElement ) {
199 $writer->endElement();
200 }
201 }
202
203 $lastName = $tag;
204 if ( $tag == 'revision' ) {
205 $state = 'revision';
206 } elseif ( $tag == 'page' ) {
207 $state = 'page';
208 }
209 } elseif ( $type == XMLReader::SIGNIFICANT_WHITESPACE || $type = XMLReader::TEXT ) {
210 if ( $lastName == 'id' ) {
211 if ( $state == 'revision' ) {
212 $this->thisRev .= $reader->value;
213 } elseif ( $state == 'page' ) {
214 $this->thisPage .= $reader->value;
215 }
216 }
217 $writer->text( $reader->value );
218 }
219 $this->sink->write( $writer->outputMemory() );
220 }
221 }
222
223 function getText( $id ) {
224 $this->fetchCount++;
225 if ( isset( $this->prefetch ) ) {
226 $text = $this->prefetch->prefetch( $this->thisPage, $this->thisRev );
227 if ( $text !== null ) { // Entry missing from prefetch dump
228 $dbr = wfGetDB( DB_SLAVE );
229 $revID = intval( $this->thisRev );
230 $revLength = $dbr->selectField( 'revision', 'rev_len', array( 'rev_id' => $revID ) );
231 // if length of rev text in file doesn't match length in db, we reload
232 // this avoids carrying forward broken data from previous xml dumps
233 if( strlen( $text ) == $revLength ) {
234 $this->prefetchCount++;
235 return $text;
236 }
237 }
238 }
239 return $this->doGetText( $id );
240 }
241
242 private function doGetText( $id ) {
243 $id = intval( $id );
244 $this->failures = 0;
245 $ex = new MWException( "Graceful storage failure" );
246 while (true) {
247 if ( $this->spawn ) {
248 if ($this->failures) {
249 // we don't know why it failed, could be the child process
250 // borked, could be db entry busted, could be db server out to lunch,
251 // so cover all bases
252 $this->closeSpawn();
253 $this->openSpawn();
254 }
255 $text = $this->getTextSpawned( $id );
256 } else {
257 $text = $this->getTextDbSafe( $id );
258 }
259 if ( $text === false ) {
260 $this->failures++;
261 if ( $this->failures > $this->maxFailures) {
262 $this->progress( "Failed to retrieve revision text for text id ".
263 "$id after $this->maxFailures tries, giving up" );
264 // were there so many bad retrievals in a row we want to bail?
265 // at some point we have to declare the dump irretrievably broken
266 $this->failedTextRetrievals++;
267 if ($this->failedTextRetrievals > $this->maxConsecutiveFailedTextRetrievals) {
268 throw $ex;
269 }
270 else {
271 // would be nice to return something better to the caller someday,
272 // log what we know about the failure and about the revision
273 return("");
274 }
275 } else {
276 $this->progress( "Error $this->failures " .
277 "of allowed $this->maxFailures retrieving revision text for text id $id! " .
278 "Pausing $this->failureTimeout seconds before retry..." );
279 sleep( $this->failureTimeout );
280 }
281 } else {
282 $this->failedTextRetrievals= 0;
283 return( $text );
284 }
285 }
286
287 }
288
289 /**
290 * Fetch a text revision from the database, retrying in case of failure.
291 * This may survive some transitory errors by reconnecting, but
292 * may not survive a long-term server outage.
293 */
294 private function getTextDbSafe( $id ) {
295 while ( true ) {
296 try {
297 $text = $this->getTextDb( $id );
298 } catch ( DBQueryError $ex ) {
299 $text = false;
300 }
301 return $text;
302 }
303 }
304
305 /**
306 * May throw a database error if, say, the server dies during query.
307 */
308 private function getTextDb( $id ) {
309 global $wgContLang;
310 $row = $this->db->selectRow( 'text',
311 array( 'old_text', 'old_flags' ),
312 array( 'old_id' => $id ),
313 __METHOD__ );
314 $text = Revision::getRevisionText( $row );
315 if ( $text === false ) {
316 return false;
317 }
318 $stripped = str_replace( "\r", "", $text );
319 $normalized = $wgContLang->normalize( $stripped );
320 return $normalized;
321 }
322
323 private function getTextSpawned( $id ) {
324 wfSuppressWarnings();
325 if ( !$this->spawnProc ) {
326 // First time?
327 $this->openSpawn();
328 }
329 $text = $this->getTextSpawnedOnce( $id );
330 wfRestoreWarnings();
331 return $text;
332 }
333
334 function openSpawn() {
335 global $IP;
336
337 $cmd = implode( " ",
338 array_map( 'wfEscapeShellArg',
339 array(
340 $this->php,
341 "$IP/maintenance/fetchText.php",
342 '--wiki', wfWikiID() ) ) );
343 $spec = array(
344 0 => array( "pipe", "r" ),
345 1 => array( "pipe", "w" ),
346 2 => array( "file", "/dev/null", "a" ) );
347 $pipes = array();
348
349 $this->progress( "Spawning database subprocess: $cmd" );
350 $this->spawnProc = proc_open( $cmd, $spec, $pipes );
351 if ( !$this->spawnProc ) {
352 // shit
353 $this->progress( "Subprocess spawn failed." );
354 return false;
355 }
356 list(
357 $this->spawnWrite, // -> stdin
358 $this->spawnRead, // <- stdout
359 ) = $pipes;
360
361 return true;
362 }
363
364 private function closeSpawn() {
365 wfSuppressWarnings();
366 if ( $this->spawnRead )
367 fclose( $this->spawnRead );
368 $this->spawnRead = false;
369 if ( $this->spawnWrite )
370 fclose( $this->spawnWrite );
371 $this->spawnWrite = false;
372 if ( $this->spawnErr )
373 fclose( $this->spawnErr );
374 $this->spawnErr = false;
375 if ( $this->spawnProc )
376 pclose( $this->spawnProc );
377 $this->spawnProc = false;
378 wfRestoreWarnings();
379 }
380
381 private function getTextSpawnedOnce( $id ) {
382 global $wgContLang;
383
384 $ok = fwrite( $this->spawnWrite, "$id\n" );
385 // $this->progress( ">> $id" );
386 if ( !$ok ) return false;
387
388 $ok = fflush( $this->spawnWrite );
389 // $this->progress( ">> [flush]" );
390 if ( !$ok ) return false;
391
392 // check that the text id they are sending is the one we asked for
393 // this avoids out of sync revision text errors we have encountered in the past
394 $newId = fgets( $this->spawnRead );
395 if ( $newId === false ) {
396 return false;
397 }
398 if ( $id != intval( $newId ) ) {
399 return false;
400 }
401
402 $len = fgets( $this->spawnRead );
403 // $this->progress( "<< " . trim( $len ) );
404 if ( $len === false ) return false;
405
406 $nbytes = intval( $len );
407 // actual error, not zero-length text
408 if ($nbytes < 0 ) return false;
409
410 $text = "";
411
412 // Subprocess may not send everything at once, we have to loop.
413 while ( $nbytes > strlen( $text ) ) {
414 $buffer = fread( $this->spawnRead, $nbytes - strlen( $text ) );
415 if ( $buffer === false ) break;
416 $text .= $buffer;
417 }
418
419 $gotbytes = strlen( $text );
420 if ( $gotbytes != $nbytes ) {
421 $this->progress( "Expected $nbytes bytes from database subprocess, got $gotbytes " );
422 return false;
423 }
424
425 // Do normalization in the dump thread...
426 $stripped = str_replace( "\r", "", $text );
427 $normalized = $wgContLang->normalize( $stripped );
428 return $normalized;
429 }
430 }
431
432
433 $dumper = new TextPassDumper( $argv );
434
435 if ( !isset( $options['help'] ) ) {
436 $dumper->dump( WikiExporter::FULL );
437 } else {
438 $dumper->progress( <<<ENDS
439 This script postprocesses XML dumps from dumpBackup.php to add
440 page text which was stubbed out (using --stub).
441
442 XML input is accepted on stdin.
443 XML output is sent to stdout; progress reports are sent to stderr.
444
445 Usage: php dumpTextPass.php [<options>]
446 Options:
447 --stub=<type>:<file> To load a compressed stub dump instead of stdin
448 --prefetch=<type>:<file> Use a prior dump file as a text source, to save
449 pressure on the database.
450 --quiet Don't dump status reports to stderr.
451 --report=n Report position and speed after every n pages processed.
452 (Default: 100)
453 --server=h Force reading from MySQL server h
454 --output=<type>:<file> Write to a file instead of stdout
455 <type>s: file, gzip, bzip2, 7zip
456 --current Base ETA on number of pages in database instead of all revisions
457 --spawn Spawn a subprocess for loading text records
458 --help Display this help message
459 ENDS
460 );
461 }
462
463