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 $server = null; // use default
55 protected $sink = null; // Output filters
56 protected $lastTime = 0;
57 protected $pageCountLast = 0;
58 protected $revCountLast = 0;
60 protected $outputTypes = [];
61 protected $filterTypes = [];
66 * The dependency-injected database to use.
72 protected $forcedDb = null;
74 /** @var LoadBalancer */
78 private $stubText = false; // include rev_text_id instead of text; for 2-pass dump
81 * @param array|null $args For backward compatibility
83 function __construct( $args = null ) {
84 parent
::__construct();
85 $this->stderr
= fopen( "php://stderr", "wt" );
87 // Built-in output and filter plugins
88 $this->registerOutput( 'file', DumpFileOutput
::class );
89 $this->registerOutput( 'gzip', DumpGZipOutput
::class );
90 $this->registerOutput( 'bzip2', DumpBZip2Output
::class );
91 $this->registerOutput( 'dbzip2', DumpDBZip2Output
::class );
92 $this->registerOutput( '7zip', Dump7ZipOutput
::class );
94 $this->registerFilter( 'latest', DumpLatestFilter
::class );
95 $this->registerFilter( 'notalk', DumpNotalkFilter
::class );
96 $this->registerFilter( 'namespace', DumpNamespaceFilter
::class );
98 // These three can be specified multiple times
99 $this->addOption( 'plugin', 'Load a dump plugin class. Specify as <class>[:<file>].',
100 false, true, false, true );
101 $this->addOption( 'output', 'Begin a filtered output stream; Specify as <type>:<file>. ' .
102 '<type>s: file, gzip, bzip2, 7zip, dbzip2', false, true, false, true );
103 $this->addOption( 'filter', 'Add a filter on an output branch. Specify as ' .
104 '<type>[:<options>]. <types>s: latest, notalk, namespace', false, true, false, true );
105 $this->addOption( 'report', 'Report position and speed after every n pages processed. ' .
106 'Default: 100.', 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 $options = $this->orderedOptions
;
162 foreach ( $options as $arg ) {
168 $val = explode( ':', $param, 2 );
170 if ( count( $val ) === 1 ) {
171 $this->loadPlugin( $val[0], '' );
172 } elseif ( count( $val ) === 2 ) {
173 $this->loadPlugin( $val[0], $val[1] );
178 $split = explode( ':', $param, 2 );
179 if ( count( $split ) !== 2 ) {
180 $this->fatalError( 'Invalid output parameter' );
182 list( $type, $file ) = $split;
183 if ( !is_null( $sink ) ) {
186 if ( !isset( $this->outputTypes
[$type] ) ) {
187 $this->fatalError( "Unrecognized output sink type '$type'" );
189 $class = $this->outputTypes
[$type];
190 if ( $type === "7zip" ) {
191 $sink = new $class( $file, intval( $this->getOption( '7ziplevel' ) ) );
193 $sink = new $class( $file );
198 if ( is_null( $sink ) ) {
199 $sink = new DumpOutput();
202 $split = explode( ':', $param, 2 );
205 if ( !isset( $this->filterTypes
[$key] ) ) {
206 $this->fatalError( "Unrecognized filter type '$key'" );
209 $type = $this->filterTypes
[$key];
211 if ( count( $split ) === 1 ) {
212 $filter = new $type( $sink );
213 } elseif ( count( $split ) === 2 ) {
214 $filter = new $type( $sink, $split[1] );
217 // references are lame in php...
225 if ( $this->hasOption( 'report' ) ) {
226 $this->reportingInterval
= intval( $this->getOption( 'report' ) );
229 if ( $this->hasOption( 'server' ) ) {
230 $this->server
= $this->getOption( 'server' );
233 if ( is_null( $sink ) ) {
234 $sink = new DumpOutput();
238 if ( count( $sinks ) > 1 ) {
239 $this->sink
= new DumpMultiWriter( $sinks );
245 function dump( $history, $text = WikiExporter
::TEXT
) {
246 # Notice messages will foul up your XML output even if they're
247 # relatively harmless.
248 if ( ini_get( 'display_errors' ) ) {
249 ini_set( 'display_errors', 'stderr' );
252 $this->initProgress( $history );
254 $db = $this->backupDb();
255 $exporter = new WikiExporter( $db, $history, $text );
256 $exporter->dumpUploads
= $this->dumpUploads
;
257 $exporter->dumpUploadFileContents
= $this->dumpUploadFileContents
;
259 $wrapper = new ExportProgressFilter( $this->sink
, $this );
260 $exporter->setOutputSink( $wrapper );
262 if ( !$this->skipHeader
) {
263 $exporter->openStream();
265 # Log item dumps: all or by range
266 if ( $history & WikiExporter
::LOGS
) {
267 if ( $this->startId ||
$this->endId
) {
268 $exporter->logsByRange( $this->startId
, $this->endId
);
270 $exporter->allLogs();
272 } elseif ( is_null( $this->pages
) ) {
273 # Page dumps: all or by page ID range
274 if ( $this->startId ||
$this->endId
) {
275 $exporter->pagesByRange( $this->startId
, $this->endId
, $this->orderRevs
);
276 } elseif ( $this->revStartId ||
$this->revEndId
) {
277 $exporter->revsByRange( $this->revStartId
, $this->revEndId
);
279 $exporter->allPages();
282 # Dump of specific pages
283 $exporter->pagesByName( $this->pages
);
286 if ( !$this->skipFooter
) {
287 $exporter->closeStream();
290 $this->report( true );
294 * Initialise starting time and maximum revision count.
295 * We'll make ETA calculations based an progress, assuming relatively
296 * constant per-revision rate.
297 * @param int $history WikiExporter::CURRENT or WikiExporter::FULL
299 function initProgress( $history = WikiExporter
::FULL
) {
300 $table = ( $history == WikiExporter
::CURRENT
) ?
'page' : 'revision';
301 $field = ( $history == WikiExporter
::CURRENT
) ?
'page_id' : 'rev_id';
303 $dbr = $this->forcedDb
;
304 if ( $this->forcedDb
=== null ) {
305 $dbr = wfGetDB( DB_REPLICA
);
307 $this->maxCount
= $dbr->selectField( $table, "MAX($field)", '', __METHOD__
);
308 $this->startTime
= microtime( true );
309 $this->lastTime
= $this->startTime
;
310 $this->ID
= getmypid();
314 * @todo Fixme: the --server parameter is currently not respected, as it
315 * doesn't seem terribly easy to ask the load balancer for a particular
316 * connection by name.
319 function backupDb() {
320 if ( $this->forcedDb
!== null ) {
321 return $this->forcedDb
;
324 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
325 $this->lb
= $lbFactory->newMainLB();
326 $db = $this->lb
->getConnection( DB_REPLICA
, 'dump' );
328 // Discourage the server from disconnecting us if it takes a long time
329 // to read out the big ol' batch query.
330 $db->setSessionOptions( [ 'connTimeout' => 3600 * 24 ] );
336 * Force the dump to use the provided database connection for database
337 * operations, wherever possible.
339 * @param IDatabase|null $db (Optional) the database connection to use. If null, resort to
340 * use the globally provided ways to get database connections.
342 function setDB( IDatabase
$db = null ) {
343 parent
::setDB( $db );
344 $this->forcedDb
= $db;
347 function __destruct() {
348 if ( isset( $this->lb
) ) {
349 $this->lb
->closeAll();
353 function backupServer() {
356 return $this->server ?
: $wgDBserver;
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" );