Refactor dumpBackup.php and dumpTextPass.php to be Maintenance subclasses
[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 * https://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 require_once __DIR__ . '/Maintenance.php';
28 require_once __DIR__ . '/../includes/export/DumpFilter.php';
29
30 /**
31 * @ingroup Dump Maintenance
32 */
33 class BackupDumper extends Maintenance {
34 public $reporting = true;
35 public $pages = null; // all pages
36 public $skipHeader = false; // don't output <mediawiki> and <siteinfo>
37 public $skipFooter = false; // don't output </mediawiki>
38 public $startId = 0;
39 public $endId = 0;
40 public $revStartId = 0;
41 public $revEndId = 0;
42 public $dumpUploads = false;
43 public $dumpUploadFileContents = false;
44
45 protected $reportingInterval = 100;
46 protected $pageCount = 0;
47 protected $revCount = 0;
48 protected $server = null; // use default
49 protected $sink = null; // Output filters
50 protected $lastTime = 0;
51 protected $pageCountLast = 0;
52 protected $revCountLast = 0;
53
54 protected $outputTypes = array();
55 protected $filterTypes = array();
56
57 protected $ID = 0;
58
59 /**
60 * The dependency-injected database to use.
61 *
62 * @var DatabaseBase|null
63 *
64 * @see self::setDB
65 */
66 protected $forcedDb = null;
67
68 /** @var LoadBalancer */
69 protected $lb;
70
71 // @todo Unused?
72 private $stubText = false; // include rev_text_id instead of text; for 2-pass dump
73
74 /**
75 * @param array $args For backward compatibility
76 */
77 function __construct( $args = null ) {
78 parent::__construct();
79 $this->stderr = fopen( "php://stderr", "wt" );
80
81 // Built-in output and filter plugins
82 $this->registerOutput( 'file', 'DumpFileOutput' );
83 $this->registerOutput( 'gzip', 'DumpGZipOutput' );
84 $this->registerOutput( 'bzip2', 'DumpBZip2Output' );
85 $this->registerOutput( 'dbzip2', 'DumpDBZip2Output' );
86 $this->registerOutput( '7zip', 'Dump7ZipOutput' );
87
88 $this->registerFilter( 'latest', 'DumpLatestFilter' );
89 $this->registerFilter( 'notalk', 'DumpNotalkFilter' );
90 $this->registerFilter( 'namespace', 'DumpNamespaceFilter' );
91
92 // These three can be specified multiple times
93 $this->addOption( 'plugin', 'Load a dump plugin class. Specify as <class>[:<file>].',
94 false, true, false, true );
95 $this->addOption( 'output', 'Begin a filtered output stream; Specify as <type>:<file>. ' .
96 '<type>s: file, gzip, bzip2, 7zip, dbzip2', false, true, false, true );
97 $this->addOption( 'filter', 'Add a filter on an output branch. Specify as ' .
98 '<type>[:<options>]. <types>s: latest, notalk, namespace', false, true, false, true );
99 $this->addOption( 'report', 'Report position and speed after every n pages processed. ' .
100 'Default: 100.', false, true );
101 $this->addOption( 'server', 'Force reading from MySQL server', false, true );
102
103 if ( $args ) {
104 // Args should be loaded and processed so that dump() can be called directly
105 // instead of execute()
106 $this->loadWithArgv( $args );
107 $this->processOptions();
108 }
109 }
110
111 /**
112 * @param string $name
113 * @param string $class Name of output filter plugin class
114 */
115 function registerOutput( $name, $class ) {
116 $this->outputTypes[$name] = $class;
117 }
118
119 /**
120 * @param string $name
121 * @param string $class Name of filter plugin class
122 */
123 function registerFilter( $name, $class ) {
124 $this->filterTypes[$name] = $class;
125 }
126
127 /**
128 * Load a plugin and register it
129 *
130 * @param string $class Name of plugin class; must have a static 'register'
131 * method that takes a BackupDumper as a parameter.
132 * @param string $file Full or relative path to the PHP file to load, or empty
133 */
134 function loadPlugin( $class, $file ) {
135 if ( $file != '' ) {
136 require_once $file;
137 }
138 $register = array( $class, 'register' );
139 call_user_func_array( $register, array( &$this ) );
140 }
141
142 function execute() {
143 throw new MWException( 'execute() must be overridden in subclasses' );
144 }
145
146 /**
147 * Processes arguments and sets $this->$sink accordingly
148 */
149 function processOptions() {
150 $sink = null;
151 $sinks = array();
152
153 $options = $this->orderedOptions;
154 foreach ( $options as $arg ) {
155 $opt = $arg[0];
156 $param = $arg[1];
157
158 switch ( $opt ) {
159 case 'plugin':
160 $val = explode( ':', $param );
161
162 if ( count( $val ) === 1 ) {
163 $this->loadPlugin( $val[0] );
164 } elseif ( count( $val ) === 2 ) {
165 $this->loadPlugin( $val[0], $val[1] );
166 } else {
167 $this->fatalError( 'Invalid plugin parameter' );
168 return;
169 }
170
171 break;
172 case 'output':
173 $split = explode( ':', $param, 2 );
174 if ( count( $split ) !== 2 ) {
175 $this->fatalError( 'Invalid output parameter' );
176 }
177 list( $type, $file ) = $split;
178 if ( !is_null( $sink ) ) {
179 $sinks[] = $sink;
180 }
181 if ( !isset( $this->outputTypes[$type] ) ) {
182 $this->fatalError( "Unrecognized output sink type '$type'" );
183 }
184 $class = $this->outputTypes[$type];
185 $sink = new $class( $file );
186
187 break;
188 case 'filter':
189 if ( is_null( $sink ) ) {
190 $sink = new DumpOutput();
191 }
192
193 $split = explode( ':', $param );
194 $key = $split[0];
195
196 if ( !isset( $this->filterTypes[$key] ) ) {
197 $this->fatalError( "Unrecognized filter type '$key'" );
198 }
199
200 $type = $this->filterTypes[$key];
201
202 if ( count( $split ) === 1 ) {
203 $filter = new $type( $sink );
204 } elseif ( count( $split ) === 2 ) {
205 $filter = new $type( $sink, $split[1] );
206 } else {
207 $this->fatalError( 'Invalid filter parameter' );
208 }
209
210 // references are lame in php...
211 unset( $sink );
212 $sink = $filter;
213
214 break;
215 }
216 }
217
218 if ( $this->hasOption( 'report' ) ) {
219 $this->reportingInterval = intval( $this->getOption( 'report' ) );
220 }
221
222 if ( $this->hasOption( 'server' ) ) {
223 $this->server = $this->getOption( 'server' );
224 }
225
226 if ( is_null( $sink ) ) {
227 $sink = new DumpOutput();
228 }
229 $sinks[] = $sink;
230
231 if ( count( $sinks ) > 1 ) {
232 $this->sink = new DumpMultiWriter( $sinks );
233 } else {
234 $this->sink = $sink;
235 }
236 }
237
238 function dump( $history, $text = WikiExporter::TEXT ) {
239 # Notice messages will foul up your XML output even if they're
240 # relatively harmless.
241 if ( ini_get( 'display_errors' ) ) {
242 ini_set( 'display_errors', 'stderr' );
243 }
244
245 $this->initProgress( $history );
246
247 $db = $this->backupDb();
248 $exporter = new WikiExporter( $db, $history, WikiExporter::STREAM, $text );
249 $exporter->dumpUploads = $this->dumpUploads;
250 $exporter->dumpUploadFileContents = $this->dumpUploadFileContents;
251
252 $wrapper = new ExportProgressFilter( $this->sink, $this );
253 $exporter->setOutputSink( $wrapper );
254
255 if ( !$this->skipHeader ) {
256 $exporter->openStream();
257 }
258 # Log item dumps: all or by range
259 if ( $history & WikiExporter::LOGS ) {
260 if ( $this->startId || $this->endId ) {
261 $exporter->logsByRange( $this->startId, $this->endId );
262 } else {
263 $exporter->allLogs();
264 }
265 } elseif ( is_null( $this->pages ) ) {
266 # Page dumps: all or by page ID range
267 if ( $this->startId || $this->endId ) {
268 $exporter->pagesByRange( $this->startId, $this->endId );
269 } elseif ( $this->revStartId || $this->revEndId ) {
270 $exporter->revsByRange( $this->revStartId, $this->revEndId );
271 } else {
272 $exporter->allPages();
273 }
274 } else {
275 # Dump of specific pages
276 $exporter->pagesByName( $this->pages );
277 }
278
279 if ( !$this->skipFooter ) {
280 $exporter->closeStream();
281 }
282
283 $this->report( true );
284 }
285
286 /**
287 * Initialise starting time and maximum revision count.
288 * We'll make ETA calculations based an progress, assuming relatively
289 * constant per-revision rate.
290 * @param int $history WikiExporter::CURRENT or WikiExporter::FULL
291 */
292 function initProgress( $history = WikiExporter::FULL ) {
293 $table = ( $history == WikiExporter::CURRENT ) ? 'page' : 'revision';
294 $field = ( $history == WikiExporter::CURRENT ) ? 'page_id' : 'rev_id';
295
296 $dbr = $this->forcedDb;
297 if ( $this->forcedDb === null ) {
298 $dbr = wfGetDB( DB_SLAVE );
299 }
300 $this->maxCount = $dbr->selectField( $table, "MAX($field)", '', __METHOD__ );
301 $this->startTime = microtime( true );
302 $this->lastTime = $this->startTime;
303 $this->ID = getmypid();
304 }
305
306 /**
307 * @todo Fixme: the --server parameter is currently not respected, as it
308 * doesn't seem terribly easy to ask the load balancer for a particular
309 * connection by name.
310 * @return DatabaseBase
311 */
312 function backupDb() {
313 if ( $this->forcedDb !== null ) {
314 return $this->forcedDb;
315 }
316
317 $this->lb = wfGetLBFactory()->newMainLB();
318 $db = $this->lb->getConnection( DB_SLAVE, 'dump' );
319
320 // Discourage the server from disconnecting us if it takes a long time
321 // to read out the big ol' batch query.
322 $db->setSessionOptions( array( 'connTimeout' => 3600 * 24 ) );
323
324 return $db;
325 }
326
327 /**
328 * Force the dump to use the provided database connection for database
329 * operations, wherever possible.
330 *
331 * @param DatabaseBase|null $db (Optional) the database connection to use. If null, resort to
332 * use the globally provided ways to get database connections.
333 */
334 function setDB( IDatabase $db = null ) {
335 parent::setDB( $db );
336 $this->forcedDb = $db;
337 }
338
339 function __destruct() {
340 if ( isset( $this->lb ) ) {
341 $this->lb->closeAll();
342 }
343 }
344
345 function backupServer() {
346 global $wgDBserver;
347
348 return $this->server
349 ? $this->server
350 : $wgDBserver;
351 }
352
353 function reportPage() {
354 $this->pageCount++;
355 }
356
357 function revCount() {
358 $this->revCount++;
359 $this->report();
360 }
361
362 function report( $final = false ) {
363 if ( $final xor ( $this->revCount % $this->reportingInterval == 0 ) ) {
364 $this->showReport();
365 }
366 }
367
368 function showReport() {
369 if ( $this->reporting ) {
370 $now = wfTimestamp( TS_DB );
371 $nowts = microtime( true );
372 $deltaAll = $nowts - $this->startTime;
373 $deltaPart = $nowts - $this->lastTime;
374 $this->pageCountPart = $this->pageCount - $this->pageCountLast;
375 $this->revCountPart = $this->revCount - $this->revCountLast;
376
377 if ( $deltaAll ) {
378 $portion = $this->revCount / $this->maxCount;
379 $eta = $this->startTime + $deltaAll / $portion;
380 $etats = wfTimestamp( TS_DB, intval( $eta ) );
381 $pageRate = $this->pageCount / $deltaAll;
382 $revRate = $this->revCount / $deltaAll;
383 } else {
384 $pageRate = '-';
385 $revRate = '-';
386 $etats = '-';
387 }
388 if ( $deltaPart ) {
389 $pageRatePart = $this->pageCountPart / $deltaPart;
390 $revRatePart = $this->revCountPart / $deltaPart;
391 } else {
392 $pageRatePart = '-';
393 $revRatePart = '-';
394 }
395 $this->progress( sprintf(
396 "%s: %s (ID %d) %d pages (%0.1f|%0.1f/sec all|curr), "
397 . "%d revs (%0.1f|%0.1f/sec all|curr), ETA %s [max %d]",
398 $now, wfWikiID(), $this->ID, $this->pageCount, $pageRate,
399 $pageRatePart, $this->revCount, $revRate, $revRatePart, $etats,
400 $this->maxCount
401 ) );
402 $this->lastTime = $nowts;
403 $this->revCountLast = $this->revCount;
404 }
405 }
406
407 function progress( $string ) {
408 if ( $this->reporting ) {
409 fwrite( $this->stderr, $string . "\n" );
410 }
411 }
412
413 function fatalError( $msg ) {
414 $this->error( "$msg\n", 1 );
415 }
416 }
417
418 class ExportProgressFilter extends DumpFilter {
419 function __construct( &$sink, &$progress ) {
420 parent::__construct( $sink );
421 $this->progress = $progress;
422 }
423
424 function writeClosePage( $string ) {
425 parent::writeClosePage( $string );
426 $this->progress->reportPage();
427 }
428
429 function writeRevision( $rev, $string ) {
430 parent::writeRevision( $rev, $string );
431 $this->progress->revCount();
432 }
433 }