Merge "First half of fix for bug #30332 ("API spamblocklist error should provide...
[lhc/web/wiklou.git] / maintenance / backup.inc
1 <?php
2 /**
3 * Base classes for database dumpers
4 *
5 * Copyright © 2005 Brion Vibber <brion@pobox.com>
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 Dump Maintenance
25 */
26
27 /**
28 * @ingroup Dump Maintenance
29 */
30 class DumpDBZip2Output extends DumpPipeOutput {
31 function DumpDBZip2Output( $file ) {
32 parent::__construct( "dbzip2", $file );
33 }
34 }
35
36 /**
37 * @ingroup Dump Maintenance
38 */
39 class BackupDumper {
40 var $reportingInterval = 100;
41 var $reporting = true;
42 var $pageCount = 0;
43 var $revCount = 0;
44 var $server = null; // use default
45 var $pages = null; // all pages
46 var $skipHeader = false; // don't output <mediawiki> and <siteinfo>
47 var $skipFooter = false; // don't output </mediawiki>
48 var $startId = 0;
49 var $endId = 0;
50 var $revStartId = 0;
51 var $revEndId = 0;
52 var $sink = null; // Output filters
53 var $stubText = false; // include rev_text_id instead of text; for 2-pass dump
54 var $dumpUploads = false;
55 var $dumpUploadFileContents = false;
56 var $lastTime = 0;
57 var $pageCountLast = 0;
58 var $revCountLast = 0;
59 var $ID = 0;
60
61 var $outputTypes = array(), $filterTypes = array();
62
63 /**
64 * @var LoadBalancer
65 */
66 protected $lb;
67
68 function __construct( $args ) {
69 $this->stderr = fopen( "php://stderr", "wt" );
70
71 // Built-in output and filter plugins
72 $this->registerOutput( 'file', 'DumpFileOutput' );
73 $this->registerOutput( 'gzip', 'DumpGZipOutput' );
74 $this->registerOutput( 'bzip2', 'DumpBZip2Output' );
75 $this->registerOutput( 'dbzip2', 'DumpDBZip2Output' );
76 $this->registerOutput( '7zip', 'Dump7ZipOutput' );
77
78 $this->registerFilter( 'latest', 'DumpLatestFilter' );
79 $this->registerFilter( 'notalk', 'DumpNotalkFilter' );
80 $this->registerFilter( 'namespace', 'DumpNamespaceFilter' );
81
82 $this->sink = $this->processArgs( $args );
83 }
84
85 /**
86 * @param $name String
87 * @param $class String: name of output filter plugin class
88 */
89 function registerOutput( $name, $class ) {
90 $this->outputTypes[$name] = $class;
91 }
92
93 /**
94 * @param $name String
95 * @param $class String: name of filter plugin class
96 */
97 function registerFilter( $name, $class ) {
98 $this->filterTypes[$name] = $class;
99 }
100
101 /**
102 * Load a plugin and register it
103 *
104 * @param $class String: name of plugin class; must have a static 'register'
105 * method that takes a BackupDumper as a parameter.
106 * @param $file String: full or relative path to the PHP file to load, or empty
107 */
108 function loadPlugin( $class, $file ) {
109 if ( $file != '' ) {
110 require_once( $file );
111 }
112 $register = array( $class, 'register' );
113 call_user_func_array( $register, array( &$this ) );
114 }
115
116 /**
117 * @param $args Array
118 * @return Array
119 */
120 function processArgs( $args ) {
121 $sink = null;
122 $sinks = array();
123 foreach ( $args as $arg ) {
124 $matches = array();
125 if ( preg_match( '/^--(.+?)(?:=(.+?)(?::(.+?))?)?$/', $arg, $matches ) ) {
126 @list( /* $full */ , $opt, $val, $param ) = $matches;
127 switch( $opt ) {
128 case "plugin":
129 $this->loadPlugin( $val, $param );
130 break;
131 case "output":
132 if ( !is_null( $sink ) ) {
133 $sinks[] = $sink;
134 }
135 if ( !isset( $this->outputTypes[$val] ) ) {
136 $this->fatalError( "Unrecognized output sink type '$val'" );
137 }
138 $type = $this->outputTypes[$val];
139 $sink = new $type( $param );
140 break;
141 case "filter":
142 if ( is_null( $sink ) ) {
143 $sink = new DumpOutput();
144 }
145 if ( !isset( $this->filterTypes[$val] ) ) {
146 $this->fatalError( "Unrecognized filter type '$val'" );
147 }
148 $type = $this->filterTypes[$val];
149 $filter = new $type( $sink, $param );
150
151 // references are lame in php...
152 unset( $sink );
153 $sink = $filter;
154
155 break;
156 case "report":
157 $this->reportingInterval = intval( $val );
158 break;
159 case "server":
160 $this->server = $val;
161 break;
162 case "force-normal":
163 if ( !function_exists( 'utf8_normalize' ) ) {
164 wfDl( "php_utfnormal.so" );
165 if ( !function_exists( 'utf8_normalize' ) ) {
166 $this->fatalError( "Failed to load UTF-8 normalization extension. " .
167 "Install or remove --force-normal parameter to use slower code." );
168 }
169 }
170 break;
171 default:
172 $this->processOption( $opt, $val, $param );
173 }
174 }
175 }
176
177 if ( is_null( $sink ) ) {
178 $sink = new DumpOutput();
179 }
180 $sinks[] = $sink;
181
182 if ( count( $sinks ) > 1 ) {
183 return new DumpMultiWriter( $sinks );
184 } else {
185 return $sink;
186 }
187 }
188
189 function processOption( $opt, $val, $param ) {
190 // extension point for subclasses to add options
191 }
192
193 function dump( $history, $text = WikiExporter::TEXT ) {
194 # Notice messages will foul up your XML output even if they're
195 # relatively harmless.
196 if ( ini_get( 'display_errors' ) )
197 ini_set( 'display_errors', 'stderr' );
198
199 $this->initProgress( $history );
200
201 $db = $this->backupDb();
202 $exporter = new WikiExporter( $db, $history, WikiExporter::STREAM, $text );
203 $exporter->dumpUploads = $this->dumpUploads;
204 $exporter->dumpUploadFileContents = $this->dumpUploadFileContents;
205
206 $wrapper = new ExportProgressFilter( $this->sink, $this );
207 $exporter->setOutputSink( $wrapper );
208
209 if ( !$this->skipHeader )
210 $exporter->openStream();
211 # Log item dumps: all or by range
212 if ( $history & WikiExporter::LOGS ) {
213 if ( $this->startId || $this->endId ) {
214 $exporter->logsByRange( $this->startId, $this->endId );
215 } else {
216 $exporter->allLogs();
217 }
218 # Page dumps: all or by page ID range
219 } else if ( is_null( $this->pages ) ) {
220 if ( $this->startId || $this->endId ) {
221 $exporter->pagesByRange( $this->startId, $this->endId );
222 } elseif ( $this->revStartId || $this->revEndId ) {
223 $exporter->revsByRange( $this->revStartId, $this->revEndId );
224 } else {
225 $exporter->allPages();
226 }
227 # Dump of specific pages
228 } else {
229 $exporter->pagesByName( $this->pages );
230 }
231
232 if ( !$this->skipFooter )
233 $exporter->closeStream();
234
235 $this->report( true );
236 }
237
238 /**
239 * Initialise starting time and maximum revision count.
240 * We'll make ETA calculations based an progress, assuming relatively
241 * constant per-revision rate.
242 * @param $history Integer: WikiExporter::CURRENT or WikiExporter::FULL
243 */
244 function initProgress( $history = WikiExporter::FULL ) {
245 $table = ( $history == WikiExporter::CURRENT ) ? 'page' : 'revision';
246 $field = ( $history == WikiExporter::CURRENT ) ? 'page_id' : 'rev_id';
247
248 $dbr = wfGetDB( DB_SLAVE );
249 $this->maxCount = $dbr->selectField( $table, "MAX($field)", '', __METHOD__ );
250 $this->startTime = wfTime();
251 $this->lastTime = $this->startTime;
252 $this->ID = getmypid();
253 }
254
255 /**
256 * @todo Fixme: the --server parameter is currently not respected, as it
257 * doesn't seem terribly easy to ask the load balancer for a particular
258 * connection by name.
259 * @return DatabaseBase
260 */
261 function backupDb() {
262 $this->lb = wfGetLBFactory()->newMainLB();
263 $db = $this->lb->getConnection( DB_SLAVE, 'backup' );
264
265 // Discourage the server from disconnecting us if it takes a long time
266 // to read out the big ol' batch query.
267 $db->setSessionOptions( array( 'connTimeout' => 3600 * 24 ) );
268
269 return $db;
270 }
271
272 function __destruct() {
273 if ( isset( $this->lb ) ) {
274 $this->lb->closeAll();
275 }
276 }
277
278 function backupServer() {
279 global $wgDBserver;
280 return $this->server
281 ? $this->server
282 : $wgDBserver;
283 }
284
285 function reportPage() {
286 $this->pageCount++;
287 }
288
289 function revCount() {
290 $this->revCount++;
291 $this->report();
292 }
293
294 function report( $final = false ) {
295 if ( $final xor ( $this->revCount % $this->reportingInterval == 0 ) ) {
296 $this->showReport();
297 }
298 }
299
300 function showReport() {
301 if ( $this->reporting ) {
302 $now = wfTimestamp( TS_DB );
303 $nowts = wfTime();
304 $deltaAll = wfTime() - $this->startTime;
305 $deltaPart = wfTime() - $this->lastTime;
306 $this->pageCountPart = $this->pageCount - $this->pageCountLast;
307 $this->revCountPart = $this->revCount - $this->revCountLast;
308
309 if ( $deltaAll ) {
310 $portion = $this->revCount / $this->maxCount;
311 $eta = $this->startTime + $deltaAll / $portion;
312 $etats = wfTimestamp( TS_DB, intval( $eta ) );
313 $pageRate = $this->pageCount / $deltaAll;
314 $revRate = $this->revCount / $deltaAll;
315 } else {
316 $pageRate = '-';
317 $revRate = '-';
318 $etats = '-';
319 }
320 if ( $deltaPart ) {
321 $pageRatePart = $this->pageCountPart / $deltaPart;
322 $revRatePart = $this->revCountPart / $deltaPart;
323 } else {
324 $pageRatePart = '-';
325 $revRatePart = '-';
326 }
327 $this->progress( sprintf( "%s: %s (ID %d) %d pages (%0.1f|%0.1f/sec all|curr), %d revs (%0.1f|%0.1f/sec all|curr), ETA %s [max %d]",
328 $now, wfWikiID(), $this->ID, $this->pageCount, $pageRate, $pageRatePart, $this->revCount, $revRate, $revRatePart, $etats, $this->maxCount ) );
329 $this->lastTime = $nowts;
330 $this->revCountLast = $this->revCount;
331 }
332 }
333
334 function progress( $string ) {
335 fwrite( $this->stderr, $string . "\n" );
336 }
337
338 function fatalError( $msg ) {
339 $this->progress( "$msg\n" );
340 die(1);
341 }
342 }
343
344 class ExportProgressFilter extends DumpFilter {
345 function __construct( &$sink, &$progress ) {
346 parent::__construct( $sink );
347 $this->progress = $progress;
348 }
349
350 function writeClosePage( $string ) {
351 parent::writeClosePage( $string );
352 $this->progress->reportPage();
353 }
354
355 function writeRevision( $rev, $string ) {
356 parent::writeRevision( $rev, $string );
357 $this->progress->revCount();
358 }
359 }