3 * Base classes for database-dumping maintenance scripts.
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
25 * @ingroup Maintenance
28 require_once __DIR__
. '/../Maintenance.php';
30 use MediaWiki\MediaWikiServices
;
31 use Wikimedia\Rdbms\LoadBalancer
;
32 use Wikimedia\Rdbms\IDatabase
;
36 * @ingroup Maintenance
38 abstract class BackupDumper
extends Maintenance
{
39 public $reporting = true;
40 public $pages = null; // all pages
41 public $skipHeader = false; // don't output <mediawiki> and <siteinfo>
42 public $skipFooter = false; // don't output </mediawiki>
45 public $revStartId = 0;
47 public $dumpUploads = false;
48 public $dumpUploadFileContents = false;
49 public $orderRevs = false;
51 protected $reportingInterval = 100;
52 protected $pageCount = 0;
53 protected $revCount = 0;
54 protected $schemaVersion = null; // use default
55 protected $server = null; // use default
56 protected $sink = null; // Output filters
57 protected $lastTime = 0;
58 protected $pageCountLast = 0;
59 protected $revCountLast = 0;
61 protected $outputTypes = [];
62 protected $filterTypes = [];
67 * The dependency-injected database to use.
73 protected $forcedDb = null;
75 /** @var LoadBalancer */
79 * @param array|null $args For backward compatibility
81 function __construct( $args = null ) {
82 parent
::__construct();
83 $this->stderr
= fopen( "php://stderr", "wt" );
85 // Built-in output and filter plugins
86 $this->registerOutput( 'file', DumpFileOutput
::class );
87 $this->registerOutput( 'gzip', DumpGZipOutput
::class );
88 $this->registerOutput( 'bzip2', DumpBZip2Output
::class );
89 $this->registerOutput( 'dbzip2', DumpDBZip2Output
::class );
90 $this->registerOutput( '7zip', Dump7ZipOutput
::class );
92 $this->registerFilter( 'latest', DumpLatestFilter
::class );
93 $this->registerFilter( 'notalk', DumpNotalkFilter
::class );
94 $this->registerFilter( 'namespace', DumpNamespaceFilter
::class );
96 // These three can be specified multiple times
97 $this->addOption( 'plugin', 'Load a dump plugin class. Specify as <class>[:<file>].',
98 false, true, false, true );
99 $this->addOption( 'output', 'Begin a filtered output stream; Specify as <type>:<file>. ' .
100 '<type>s: file, gzip, bzip2, 7zip, dbzip2', false, true, false, true );
101 $this->addOption( 'filter', 'Add a filter on an output branch. Specify as ' .
102 '<type>[:<options>]. <types>s: latest, notalk, namespace', false, true, false, true );
103 $this->addOption( 'report', 'Report position and speed after every n pages processed. ' .
104 'Default: 100.', false, true );
105 $this->addOption( 'schema-version', 'Schema version to use for output. ' .
106 'Default: ' . WikiExporter
::schemaVersion(), false, true );
107 $this->addOption( 'server', 'Force reading from MySQL server', false, true );
108 $this->addOption( '7ziplevel', '7zip compression level for all 7zip outputs. Used for ' .
109 '-mx option to 7za command.', false, true );
112 // Args should be loaded and processed so that dump() can be called directly
113 // instead of execute()
114 $this->loadWithArgv( $args );
115 $this->processOptions();
120 * @param string $name
121 * @param string $class Name of output filter plugin class
123 function registerOutput( $name, $class ) {
124 $this->outputTypes
[$name] = $class;
128 * @param string $name
129 * @param string $class Name of filter plugin class
131 function registerFilter( $name, $class ) {
132 $this->filterTypes
[$name] = $class;
136 * Load a plugin and register it
138 * @param string $class Name of plugin class; must have a static 'register'
139 * method that takes a BackupDumper as a parameter.
140 * @param string $file Full or relative path to the PHP file to load, or empty
142 function loadPlugin( $class, $file ) {
146 $register = [ $class, 'register' ];
151 throw new MWException( 'execute() must be overridden in subclasses' );
155 * Processes arguments and sets $this->$sink accordingly
157 function processOptions() {
161 $this->schemaVersion
= WikiExporter
::schemaVersion();
163 $options = $this->orderedOptions
;
164 foreach ( $options as $arg ) {
170 $val = explode( ':', $param, 2 );
172 if ( count( $val ) === 1 ) {
173 $this->loadPlugin( $val[0], '' );
174 } elseif ( count( $val ) === 2 ) {
175 $this->loadPlugin( $val[0], $val[1] );
180 $split = explode( ':', $param, 2 );
181 if ( count( $split ) !== 2 ) {
182 $this->fatalError( 'Invalid output parameter' );
184 list( $type, $file ) = $split;
185 if ( !is_null( $sink ) ) {
188 if ( !isset( $this->outputTypes
[$type] ) ) {
189 $this->fatalError( "Unrecognized output sink type '$type'" );
191 $class = $this->outputTypes
[$type];
192 if ( $type === "7zip" ) {
193 $sink = new $class( $file, intval( $this->getOption( '7ziplevel' ) ) );
195 $sink = new $class( $file );
200 if ( is_null( $sink ) ) {
201 $sink = new DumpOutput();
204 $split = explode( ':', $param, 2 );
207 if ( !isset( $this->filterTypes
[$key] ) ) {
208 $this->fatalError( "Unrecognized filter type '$key'" );
211 $type = $this->filterTypes
[$key];
213 if ( count( $split ) === 1 ) {
214 $filter = new $type( $sink );
215 } elseif ( count( $split ) === 2 ) {
216 $filter = new $type( $sink, $split[1] );
219 // references are lame in php...
224 case 'schema-version':
225 if ( !in_array( $param, XmlDumpWriter
::$supportedSchemas ) ) {
227 "Unsupported schema version $param. Supported versions: " .
228 implode( ', ', XmlDumpWriter
::$supportedSchemas )
231 $this->schemaVersion
= $param;
236 if ( $this->hasOption( 'report' ) ) {
237 $this->reportingInterval
= intval( $this->getOption( 'report' ) );
240 if ( $this->hasOption( 'server' ) ) {
241 $this->server
= $this->getOption( 'server' );
244 if ( is_null( $sink ) ) {
245 $sink = new DumpOutput();
249 if ( count( $sinks ) > 1 ) {
250 $this->sink
= new DumpMultiWriter( $sinks );
256 function dump( $history, $text = WikiExporter
::TEXT
) {
257 # Notice messages will foul up your XML output even if they're
258 # relatively harmless.
259 if ( ini_get( 'display_errors' ) ) {
260 ini_set( 'display_errors', 'stderr' );
263 $this->initProgress( $history );
265 $db = $this->backupDb();
266 $exporter = new WikiExporter( $db, $history, $text );
267 $exporter->setSchemaVersion( $this->schemaVersion
);
268 $exporter->dumpUploads
= $this->dumpUploads
;
269 $exporter->dumpUploadFileContents
= $this->dumpUploadFileContents
;
271 $wrapper = new ExportProgressFilter( $this->sink
, $this );
272 $exporter->setOutputSink( $wrapper );
274 if ( !$this->skipHeader
) {
275 $exporter->openStream();
277 # Log item dumps: all or by range
278 if ( $history & WikiExporter
::LOGS
) {
279 if ( $this->startId ||
$this->endId
) {
280 $exporter->logsByRange( $this->startId
, $this->endId
);
282 $exporter->allLogs();
284 } elseif ( is_null( $this->pages
) ) {
285 # Page dumps: all or by page ID range
286 if ( $this->startId ||
$this->endId
) {
287 $exporter->pagesByRange( $this->startId
, $this->endId
, $this->orderRevs
);
288 } elseif ( $this->revStartId ||
$this->revEndId
) {
289 $exporter->revsByRange( $this->revStartId
, $this->revEndId
);
291 $exporter->allPages();
294 # Dump of specific pages
295 $exporter->pagesByName( $this->pages
);
298 if ( !$this->skipFooter
) {
299 $exporter->closeStream();
302 $this->report( true );
306 * Initialise starting time and maximum revision count.
307 * We'll make ETA calculations based an progress, assuming relatively
308 * constant per-revision rate.
309 * @param int $history WikiExporter::CURRENT or WikiExporter::FULL
311 function initProgress( $history = WikiExporter
::FULL
) {
312 $table = ( $history == WikiExporter
::CURRENT
) ?
'page' : 'revision';
313 $field = ( $history == WikiExporter
::CURRENT
) ?
'page_id' : 'rev_id';
315 $dbr = $this->forcedDb
;
316 if ( $this->forcedDb
=== null ) {
317 $dbr = wfGetDB( DB_REPLICA
);
319 $this->maxCount
= $dbr->selectField( $table, "MAX($field)", '', __METHOD__
);
320 $this->startTime
= microtime( true );
321 $this->lastTime
= $this->startTime
;
322 $this->ID
= getmypid();
326 * @todo Fixme: the --server parameter is currently not respected, as it
327 * doesn't seem terribly easy to ask the load balancer for a particular
328 * connection by name.
331 function backupDb() {
332 if ( $this->forcedDb
!== null ) {
333 return $this->forcedDb
;
336 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
337 $this->lb
= $lbFactory->newMainLB();
338 $db = $this->lb
->getConnection( DB_REPLICA
, 'dump' );
340 // Discourage the server from disconnecting us if it takes a long time
341 // to read out the big ol' batch query.
342 $db->setSessionOptions( [ 'connTimeout' => 3600 * 24 ] );
348 * Force the dump to use the provided database connection for database
349 * operations, wherever possible.
351 * @param IDatabase|null $db (Optional) the database connection to use. If null, resort to
352 * use the globally provided ways to get database connections.
354 function setDB( IDatabase
$db = null ) {
355 parent
::setDB( $db );
356 $this->forcedDb
= $db;
359 function __destruct() {
360 if ( isset( $this->lb
) ) {
361 $this->lb
->closeAll();
365 function backupServer() {
368 return $this->server ?
: $wgDBserver;
371 function reportPage() {
375 function revCount() {
380 function report( $final = false ) {
381 if ( $final xor ( $this->revCount %
$this->reportingInterval
== 0 ) ) {
386 function showReport() {
387 if ( $this->reporting
) {
388 $now = wfTimestamp( TS_DB
);
389 $nowts = microtime( true );
390 $deltaAll = $nowts - $this->startTime
;
391 $deltaPart = $nowts - $this->lastTime
;
392 $this->pageCountPart
= $this->pageCount
- $this->pageCountLast
;
393 $this->revCountPart
= $this->revCount
- $this->revCountLast
;
396 $portion = $this->revCount
/ $this->maxCount
;
397 $eta = $this->startTime +
$deltaAll / $portion;
398 $etats = wfTimestamp( TS_DB
, intval( $eta ) );
399 $pageRate = $this->pageCount
/ $deltaAll;
400 $revRate = $this->revCount
/ $deltaAll;
407 $pageRatePart = $this->pageCountPart
/ $deltaPart;
408 $revRatePart = $this->revCountPart
/ $deltaPart;
413 $this->progress( sprintf(
414 "%s: %s (ID %d) %d pages (%0.1f|%0.1f/sec all|curr), "
415 . "%d revs (%0.1f|%0.1f/sec all|curr), ETA %s [max %d]",
416 $now, wfWikiID(), $this->ID
, $this->pageCount
, $pageRate,
417 $pageRatePart, $this->revCount
, $revRate, $revRatePart, $etats,
420 $this->lastTime
= $nowts;
421 $this->revCountLast
= $this->revCount
;
425 function progress( $string ) {
426 if ( $this->reporting
) {
427 fwrite( $this->stderr
, $string . "\n" );