3 * Base classes for database dumpers
5 * Copyright © 2005 Brion Vibber <brion@pobox.com>
6 * https://www.mediawiki.org/
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.
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.
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
24 * @ingroup Dump Maintenance
27 require_once __DIR__ . '/Maintenance.php';
28 require_once __DIR__ . '/../includes/export/DumpFilter.php';
31 * @ingroup Dump Maintenance
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>
40 public $revStartId = 0;
42 public $dumpUploads = false;
43 public $dumpUploadFileContents = false;
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;
54 protected $outputTypes = array();
55 protected $filterTypes = array();
60 * The dependency-injected database to use.
62 * @var DatabaseBase|null
66 protected $forcedDb = null;
68 /** @var LoadBalancer */
72 private $stubText = false; // include rev_text_id instead of text; for 2-pass dump
75 * @param array $args For backward compatibility
77 function __construct( $args = null ) {
78 parent::__construct();
79 $this->stderr = fopen( "php://stderr", "wt" );
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' );
88 $this->registerFilter( 'latest', 'DumpLatestFilter' );
89 $this->registerFilter( 'notalk', 'DumpNotalkFilter' );
90 $this->registerFilter( 'namespace', 'DumpNamespaceFilter' );
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 );
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();
112 * @param string $name
113 * @param string $class Name of output filter plugin class
115 function registerOutput( $name, $class ) {
116 $this->outputTypes[$name] = $class;
120 * @param string $name
121 * @param string $class Name of filter plugin class
123 function registerFilter( $name, $class ) {
124 $this->filterTypes[$name] = $class;
128 * Load a plugin and register it
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
134 function loadPlugin( $class, $file ) {
138 $register = array( $class, 'register' );
139 call_user_func_array( $register, array( &$this ) );
143 throw new MWException( 'execute() must be overridden in subclasses' );
147 * Processes arguments and sets $this->$sink accordingly
149 function processOptions() {
153 $options = $this->orderedOptions;
154 foreach ( $options as $arg ) {
160 $val = explode( ':', $param );
162 if ( count( $val ) === 1 ) {
163 $this->loadPlugin( $val[0] );
164 } elseif ( count( $val ) === 2 ) {
165 $this->loadPlugin( $val[0], $val[1] );
167 $this->fatalError( 'Invalid plugin parameter' );
173 $split = explode( ':', $param, 2 );
174 if ( count( $split ) !== 2 ) {
175 $this->fatalError( 'Invalid output parameter' );
177 list( $type, $file ) = $split;
178 if ( !is_null( $sink ) ) {
181 if ( !isset( $this->outputTypes[$type] ) ) {
182 $this->fatalError( "Unrecognized output sink type '$type'" );
184 $class = $this->outputTypes[$type];
185 $sink = new $class( $file );
189 if ( is_null( $sink ) ) {
190 $sink = new DumpOutput();
193 $split = explode( ':', $param );
196 if ( !isset( $this->filterTypes[$key] ) ) {
197 $this->fatalError( "Unrecognized filter type '$key'" );
200 $type = $this->filterTypes[$key];
202 if ( count( $split ) === 1 ) {
203 $filter = new $type( $sink );
204 } elseif ( count( $split ) === 2 ) {
205 $filter = new $type( $sink, $split[1] );
207 $this->fatalError( 'Invalid filter parameter' );
210 // references are lame in php...
218 if ( $this->hasOption( 'report' ) ) {
219 $this->reportingInterval = intval( $this->getOption( 'report' ) );
222 if ( $this->hasOption( 'server' ) ) {
223 $this->server = $this->getOption( 'server' );
226 if ( is_null( $sink ) ) {
227 $sink = new DumpOutput();
231 if ( count( $sinks ) > 1 ) {
232 $this->sink = new DumpMultiWriter( $sinks );
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' );
245 $this->initProgress( $history );
247 $db = $this->backupDb();
248 $exporter = new WikiExporter( $db, $history, WikiExporter::STREAM, $text );
249 $exporter->dumpUploads = $this->dumpUploads;
250 $exporter->dumpUploadFileContents = $this->dumpUploadFileContents;
252 $wrapper = new ExportProgressFilter( $this->sink, $this );
253 $exporter->setOutputSink( $wrapper );
255 if ( !$this->skipHeader ) {
256 $exporter->openStream();
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 );
263 $exporter->allLogs();
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 );
272 $exporter->allPages();
275 # Dump of specific pages
276 $exporter->pagesByName( $this->pages );
279 if ( !$this->skipFooter ) {
280 $exporter->closeStream();
283 $this->report( true );
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
292 function initProgress( $history = WikiExporter::FULL ) {
293 $table = ( $history == WikiExporter::CURRENT ) ? 'page' : 'revision';
294 $field = ( $history == WikiExporter::CURRENT ) ? 'page_id' : 'rev_id';
296 $dbr = $this->forcedDb;
297 if ( $this->forcedDb === null ) {
298 $dbr = wfGetDB( DB_SLAVE );
300 $this->maxCount = $dbr->selectField( $table, "MAX($field)", '', __METHOD__ );
301 $this->startTime = microtime( true );
302 $this->lastTime = $this->startTime;
303 $this->ID = getmypid();
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
312 function backupDb() {
313 if ( $this->forcedDb !== null ) {
314 return $this->forcedDb;
317 $this->lb = wfGetLBFactory()->newMainLB();
318 $db = $this->lb->getConnection( DB_SLAVE, 'dump' );
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 ) );
328 * Force the dump to use the provided database connection for database
329 * operations, wherever possible.
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.
334 function setDB( IDatabase $db = null ) {
335 parent::setDB( $db );
336 $this->forcedDb = $db;
339 function __destruct() {
340 if ( isset( $this->lb ) ) {
341 $this->lb->closeAll();
345 function backupServer() {
353 function reportPage() {
357 function revCount() {
362 function report( $final = false ) {
363 if ( $final xor ( $this->revCount % $this->reportingInterval == 0 ) ) {
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;
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;
389 $pageRatePart = $this->pageCountPart / $deltaPart;
390 $revRatePart = $this->revCountPart / $deltaPart;
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,
402 $this->lastTime = $nowts;
403 $this->revCountLast = $this->revCount;
407 function progress( $string ) {
408 if ( $this->reporting ) {
409 fwrite( $this->stderr, $string . "\n" );
413 function fatalError( $msg ) {
414 $this->error( "$msg\n", 1 );
418 class ExportProgressFilter extends DumpFilter {
419 function __construct( &$sink, &$progress ) {
420 parent::__construct( $sink );
421 $this->progress = $progress;
424 function writeClosePage( $string ) {
425 parent::writeClosePage( $string );
426 $this->progress->reportPage();
429 function writeRevision( $rev, $string ) {
430 parent::writeRevision( $rev, $string );
431 $this->progress->revCount();