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 = [];
55 protected $filterTypes = [];
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 );
102 $this->addOption( '7ziplevel', '7zip compression level for all 7zip outputs. Used for ' .
103 '-mx option to 7za command.', false, true );
106 // Args should be loaded and processed so that dump() can be called directly
107 // instead of execute()
108 $this->loadWithArgv( $args );
109 $this->processOptions();
114 * @param string $name
115 * @param string $class Name of output filter plugin class
117 function registerOutput( $name, $class ) {
118 $this->outputTypes[$name] = $class;
122 * @param string $name
123 * @param string $class Name of filter plugin class
125 function registerFilter( $name, $class ) {
126 $this->filterTypes[$name] = $class;
130 * Load a plugin and register it
132 * @param string $class Name of plugin class; must have a static 'register'
133 * method that takes a BackupDumper as a parameter.
134 * @param string $file Full or relative path to the PHP file to load, or empty
136 function loadPlugin( $class, $file ) {
140 $register = [ $class, 'register' ];
141 call_user_func_array( $register, [ $this ] );
145 throw new MWException( 'execute() must be overridden in subclasses' );
149 * Processes arguments and sets $this->$sink accordingly
151 function processOptions() {
155 $options = $this->orderedOptions;
156 foreach ( $options as $arg ) {
162 $val = explode( ':', $param );
164 if ( count( $val ) === 1 ) {
165 $this->loadPlugin( $val[0] );
166 } elseif ( count( $val ) === 2 ) {
167 $this->loadPlugin( $val[0], $val[1] );
169 $this->fatalError( 'Invalid plugin parameter' );
175 $split = explode( ':', $param, 2 );
176 if ( count( $split ) !== 2 ) {
177 $this->fatalError( 'Invalid output parameter' );
179 list( $type, $file ) = $split;
180 if ( !is_null( $sink ) ) {
183 if ( !isset( $this->outputTypes[$type] ) ) {
184 $this->fatalError( "Unrecognized output sink type '$type'" );
186 $class = $this->outputTypes[$type];
187 if ( $type === "7zip" ) {
188 $sink = new $class( $file, intval( $this->getOption( '7ziplevel' ) ) );
190 $sink = new $class( $file );
195 if ( is_null( $sink ) ) {
196 $sink = new DumpOutput();
199 $split = explode( ':', $param );
202 if ( !isset( $this->filterTypes[$key] ) ) {
203 $this->fatalError( "Unrecognized filter type '$key'" );
206 $type = $this->filterTypes[$key];
208 if ( count( $split ) === 1 ) {
209 $filter = new $type( $sink );
210 } elseif ( count( $split ) === 2 ) {
211 $filter = new $type( $sink, $split[1] );
213 $this->fatalError( 'Invalid filter parameter' );
216 // references are lame in php...
224 if ( $this->hasOption( 'report' ) ) {
225 $this->reportingInterval = intval( $this->getOption( 'report' ) );
228 if ( $this->hasOption( 'server' ) ) {
229 $this->server = $this->getOption( 'server' );
232 if ( is_null( $sink ) ) {
233 $sink = new DumpOutput();
237 if ( count( $sinks ) > 1 ) {
238 $this->sink = new DumpMultiWriter( $sinks );
244 function dump( $history, $text = WikiExporter::TEXT ) {
245 # Notice messages will foul up your XML output even if they're
246 # relatively harmless.
247 if ( ini_get( 'display_errors' ) ) {
248 ini_set( 'display_errors', 'stderr' );
251 $this->initProgress( $history );
253 $db = $this->backupDb();
254 $exporter = new WikiExporter( $db, $history, WikiExporter::STREAM, $text );
255 $exporter->dumpUploads = $this->dumpUploads;
256 $exporter->dumpUploadFileContents = $this->dumpUploadFileContents;
258 $wrapper = new ExportProgressFilter( $this->sink, $this );
259 $exporter->setOutputSink( $wrapper );
261 if ( !$this->skipHeader ) {
262 $exporter->openStream();
264 # Log item dumps: all or by range
265 if ( $history & WikiExporter::LOGS ) {
266 if ( $this->startId || $this->endId ) {
267 $exporter->logsByRange( $this->startId, $this->endId );
269 $exporter->allLogs();
271 } elseif ( is_null( $this->pages ) ) {
272 # Page dumps: all or by page ID range
273 if ( $this->startId || $this->endId ) {
274 $exporter->pagesByRange( $this->startId, $this->endId );
275 } elseif ( $this->revStartId || $this->revEndId ) {
276 $exporter->revsByRange( $this->revStartId, $this->revEndId );
278 $exporter->allPages();
281 # Dump of specific pages
282 $exporter->pagesByName( $this->pages );
285 if ( !$this->skipFooter ) {
286 $exporter->closeStream();
289 $this->report( true );
293 * Initialise starting time and maximum revision count.
294 * We'll make ETA calculations based an progress, assuming relatively
295 * constant per-revision rate.
296 * @param int $history WikiExporter::CURRENT or WikiExporter::FULL
298 function initProgress( $history = WikiExporter::FULL ) {
299 $table = ( $history == WikiExporter::CURRENT ) ? 'page' : 'revision';
300 $field = ( $history == WikiExporter::CURRENT ) ? 'page_id' : 'rev_id';
302 $dbr = $this->forcedDb;
303 if ( $this->forcedDb === null ) {
304 $dbr = wfGetDB( DB_SLAVE );
306 $this->maxCount = $dbr->selectField( $table, "MAX($field)", '', __METHOD__ );
307 $this->startTime = microtime( true );
308 $this->lastTime = $this->startTime;
309 $this->ID = getmypid();
313 * @todo Fixme: the --server parameter is currently not respected, as it
314 * doesn't seem terribly easy to ask the load balancer for a particular
315 * connection by name.
316 * @return DatabaseBase
318 function backupDb() {
319 if ( $this->forcedDb !== null ) {
320 return $this->forcedDb;
323 $this->lb = wfGetLBFactory()->newMainLB();
324 $db = $this->lb->getConnection( DB_SLAVE, 'dump' );
326 // Discourage the server from disconnecting us if it takes a long time
327 // to read out the big ol' batch query.
328 $db->setSessionOptions( [ 'connTimeout' => 3600 * 24 ] );
334 * Force the dump to use the provided database connection for database
335 * operations, wherever possible.
337 * @param DatabaseBase|null $db (Optional) the database connection to use. If null, resort to
338 * use the globally provided ways to get database connections.
340 function setDB( IDatabase $db = null ) {
341 parent::setDB( $db );
342 $this->forcedDb = $db;
345 function __destruct() {
346 if ( isset( $this->lb ) ) {
347 $this->lb->closeAll();
351 function backupServer() {
359 function reportPage() {
363 function revCount() {
368 function report( $final = false ) {
369 if ( $final xor ( $this->revCount % $this->reportingInterval == 0 ) ) {
374 function showReport() {
375 if ( $this->reporting ) {
376 $now = wfTimestamp( TS_DB );
377 $nowts = microtime( true );
378 $deltaAll = $nowts - $this->startTime;
379 $deltaPart = $nowts - $this->lastTime;
380 $this->pageCountPart = $this->pageCount - $this->pageCountLast;
381 $this->revCountPart = $this->revCount - $this->revCountLast;
384 $portion = $this->revCount / $this->maxCount;
385 $eta = $this->startTime + $deltaAll / $portion;
386 $etats = wfTimestamp( TS_DB, intval( $eta ) );
387 $pageRate = $this->pageCount / $deltaAll;
388 $revRate = $this->revCount / $deltaAll;
395 $pageRatePart = $this->pageCountPart / $deltaPart;
396 $revRatePart = $this->revCountPart / $deltaPart;
401 $this->progress( sprintf(
402 "%s: %s (ID %d) %d pages (%0.1f|%0.1f/sec all|curr), "
403 . "%d revs (%0.1f|%0.1f/sec all|curr), ETA %s [max %d]",
404 $now, wfWikiID(), $this->ID, $this->pageCount, $pageRate,
405 $pageRatePart, $this->revCount, $revRate, $revRatePart, $etats,
408 $this->lastTime = $nowts;
409 $this->revCountLast = $this->revCount;
413 function progress( $string ) {
414 if ( $this->reporting ) {
415 fwrite( $this->stderr, $string . "\n" );
419 function fatalError( $msg ) {
420 $this->error( "$msg\n", 1 );
424 class ExportProgressFilter extends DumpFilter {
425 function __construct( &$sink, &$progress ) {
426 parent::__construct( $sink );
427 $this->progress = $progress;
430 function writeClosePage( $string ) {
431 parent::writeClosePage( $string );
432 $this->progress->reportPage();
435 function writeRevision( $rev, $string ) {
436 parent::writeRevision( $rev, $string );
437 $this->progress->revCount();