]> scripts.mit.edu Git - autoinstalls/mediawiki.git/blob - maintenance/dumpTextPass.php
MediaWiki 1.16.4
[autoinstalls/mediawiki.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                                 $this->prefetchCount++;
192                                 return $text;
193                         }
194                 }
195                 return $this->doGetText( $id );
196         }
197         
198         private function doGetText( $id ) {
199                 if( $this->spawn ) {
200                         return $this->getTextSpawned( $id );
201                 } else {
202                         return $this->getTextDbSafe( $id );
203                 }
204         }
205         
206         /**
207          * Fetch a text revision from the database, retrying in case of failure.
208          * This may survive some transitory errors by reconnecting, but
209          * may not survive a long-term server outage.
210          */
211         private function getTextDbSafe( $id ) {
212                 while( true ) {
213                         try {
214                                 $text = $this->getTextDb( $id );
215                                 $ex = new MWException("Graceful storage failure");
216                         } catch (DBQueryError $ex) {
217                                 $text = false;
218                         }
219                         if( $text === false ) {
220                                 $this->failures++;
221                                 if( $this->failures > $this->maxFailures ) {
222                                         throw $ex;
223                                 } else {
224                                         $this->progress( "Database failure $this->failures " .
225                                                 "of allowed $this->maxFailures for revision $id! " .
226                                                 "Pausing $this->failureTimeout seconds..." );
227                                         sleep( $this->failureTimeout );
228                                 }
229                         } else {
230                                 return $text;
231                         }
232                 }
233         }
234         
235         /**
236          * May throw a database error if, say, the server dies during query.
237          */
238         private function getTextDb( $id ) {
239                 global $wgContLang;
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 = $wgContLang->normalize( $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                 global $wgContLang;
326
327                 $ok = fwrite( $this->spawnWrite, "$id\n" );
328                 //$this->progress( ">> $id" );
329                 if( !$ok ) return false;
330                 
331                 $ok = fflush( $this->spawnWrite );
332                 //$this->progress( ">> [flush]" );
333                 if( !$ok ) return false;
334                 
335                 $len = fgets( $this->spawnRead );
336                 //$this->progress( "<< " . trim( $len ) );
337                 if( $len === false ) return false;
338                 
339                 $nbytes = intval( $len );
340                 $text = "";
341                 
342                 // Subprocess may not send everything at once, we have to loop.
343                 while( $nbytes > strlen( $text ) ) {
344                         $buffer = fread( $this->spawnRead, $nbytes - strlen( $text ) );
345                         if( $buffer === false ) break;
346                         $text .= $buffer;
347                 }
348                 
349                 $gotbytes = strlen( $text );
350                 if( $gotbytes != $nbytes ) {
351                         $this->progress( "Expected $nbytes bytes from database subprocess, got $gotbytes ");
352                         return false;
353                 }
354                 
355                 // Do normalization in the dump thread...
356                 $stripped = str_replace( "\r", "", $text );
357                 $normalized = $wgContLang->normalize( $stripped );
358                 return $normalized;
359         }
360
361         function startElement( $parser, $name, $attribs ) {
362                 $this->clearOpenElement( null );
363                 $this->lastName = $name;
364
365                 if( $name == 'revision' ) {
366                         $this->state = $name;
367                         $this->egress->writeOpenPage( null, $this->buffer );
368                         $this->buffer = "";
369                 } elseif( $name == 'page' ) {
370                         $this->state = $name;
371                         if( $this->atStart ) {
372                                 $this->egress->writeOpenStream( $this->buffer );
373                                 $this->buffer = "";
374                                 $this->atStart = false;
375                         }
376                 }
377
378                 if( $name == "text" && isset( $attribs['id'] ) ) {
379                         $text = $this->getText( $attribs['id'] );
380                         $this->openElement = array( $name, array( 'xml:space' => 'preserve' ) );
381                         if( strlen( $text ) > 0 ) {
382                                 $this->characterData( $parser, $text );
383                         }
384                 } else {
385                         $this->openElement = array( $name, $attribs );
386                 }
387         }
388
389         function endElement( $parser, $name ) {
390                 if( $this->openElement ) {
391                         $this->clearOpenElement( "" );
392                 } else {
393                         $this->buffer .= "</$name>";
394                 }
395
396                 if( $name == 'revision' ) {
397                         $this->egress->writeRevision( null, $this->buffer );
398                         $this->buffer = "";
399                         $this->thisRev = "";
400                 } elseif( $name == 'page' ) {
401                         $this->egress->writeClosePage( $this->buffer );
402                         $this->buffer = "";
403                         $this->thisPage = "";
404                 } elseif( $name == 'mediawiki' ) {
405                         $this->egress->writeCloseStream( $this->buffer );
406                         $this->buffer = "";
407                 }
408         }
409
410         function characterData( $parser, $data ) {
411                 $this->clearOpenElement( null );
412                 if( $this->lastName == "id" ) {
413                         if( $this->state == "revision" ) {
414                                 $this->thisRev .= $data;
415                         } elseif( $this->state == "page" ) {
416                                 $this->thisPage .= $data;
417                         }
418                 }
419                 $this->buffer .= htmlspecialchars( $data );
420         }
421
422         function clearOpenElement( $style ) {
423                 if( $this->openElement ) {
424                         $this->buffer .= Xml::element( $this->openElement[0], $this->openElement[1], $style );
425                         $this->openElement = false;
426                 }
427         }
428 }
429
430
431 $dumper = new TextPassDumper( $argv );
432
433 if( true ) {
434         $dumper->dump();
435 } else {
436         $dumper->progress( <<<ENDS
437 This script postprocesses XML dumps from dumpBackup.php to add
438 page text which was stubbed out (using --stub).
439
440 XML input is accepted on stdin.
441 XML output is sent to stdout; progress reports are sent to stderr.
442
443 Usage: php dumpTextPass.php [<options>]
444 Options:
445   --stub=<type>:<file> To load a compressed stub dump instead of stdin
446   --prefetch=<type>:<file> Use a prior dump file as a text source, to save
447               pressure on the database.
448               (Requires PHP 5.0+ and the XMLReader PECL extension)
449   --quiet     Don't dump status reports to stderr.
450   --report=n  Report position and speed after every n pages processed.
451               (Default: 100)
452   --server=h  Force reading from MySQL server h
453   --current   Base ETA on number of pages in database instead of all revisions
454   --spawn     Spawn a subprocess for loading text records
455 ENDS
456 );
457 }
458
459