MediaWiki 1.43.1
BackupDumper.php
Go to the documentation of this file.
1<?php
28namespace MediaWiki\Maintenance;
29
30// @codeCoverageIgnoreStart
31require_once __DIR__ . '/../Maintenance.php';
32require_once __DIR__ . '/../../includes/export/WikiExporter.php';
33// @codeCoverageIgnoreEnd
34
36use DumpOutput;
41use WikiExporter;
45
50abstract class BackupDumper extends Maintenance {
52 public $reporting = true;
54 public $pages = null;
56 public $skipHeader = false;
58 public $skipFooter = false;
60 public $startId = 0;
62 public $endId = 0;
64 public $revStartId = 0;
66 public $revEndId = 0;
68 public $dumpUploads = false;
72 public $orderRevs = false;
74 public $limitNamespaces = [];
76 public $stderr;
77
79 protected $reportingInterval = 100;
81 protected $pageCount = 0;
83 protected $revCount = 0;
85 protected $schemaVersion = null;
87 protected $sink = null;
89 protected $lastTime = 0;
91 protected $pageCountLast = 0;
93 protected $revCountLast = 0;
94
96 protected $outputTypes = [];
98 protected $filterTypes = [];
99
101 protected $ID = 0;
102
104 protected $startTime;
106 protected $pageCountPart;
108 protected $revCountPart;
110 protected $maxCount;
114 protected $egress;
116 protected $buffer;
118 protected $openElement;
120 protected $atStart;
122 protected $thisRevModel;
124 protected $thisRevFormat;
126 protected $lastName;
128 protected $state;
129
137 protected $forcedDb = null;
138
140 protected $lb;
141
145 public function __construct( $args = null ) {
146 parent::__construct();
147 $this->stderr = fopen( "php://stderr", "wt" );
148
149 // Built-in output and filter plugins
150 $this->registerOutput( 'file', \DumpFileOutput::class );
151 $this->registerOutput( 'gzip', \DumpGZipOutput::class );
152 $this->registerOutput( 'bzip2', \DumpBZip2Output::class );
153 $this->registerOutput( 'dbzip2', \DumpDBZip2Output::class );
154 $this->registerOutput( 'lbzip2', \DumpLBZip2Output::class );
155 $this->registerOutput( '7zip', \Dump7ZipOutput::class );
156
157 $this->registerFilter( 'latest', \DumpLatestFilter::class );
158 $this->registerFilter( 'notalk', \DumpNotalkFilter::class );
159 $this->registerFilter( 'namespace', \DumpNamespaceFilter::class );
160
161 // These three can be specified multiple times
162 $this->addOption( 'plugin', 'Load a dump plugin class. Specify as <class>[:<file>].',
163 false, true, false, true );
164 $this->addOption( 'output', 'Begin a filtered output stream; Specify as <type>:<file>. ' .
165 '<type>s: file, gzip, bzip2, 7zip, dbzip2, lbzip2', false, true, 'o', true );
166 $this->addOption( 'filter', 'Add a filter on an output branch. Specify as ' .
167 '<type>[:<options>]. <types>s: latest, notalk, namespace', false, true, false, true );
168 $this->addOption( 'report', 'Report position and speed after every n pages processed. ' .
169 'Default: 100.', false, true );
170 $this->addOption( '7ziplevel', '7zip compression level for all 7zip outputs. Used for ' .
171 '-mx option to 7za command.', false, true );
172 // NOTE: we can't know the default schema version yet, since configuration has not been
173 // loaded when this constructor is called. To work around this, we re-declare
174 // this option in validateParamsAndArgs().
175 $this->addOption( 'schema-version', 'Schema version to use for output.', false, true );
176
177 if ( $args ) {
178 // Args should be loaded and processed so that dump() can be called directly
179 // instead of execute()
180 $this->loadWithArgv( $args );
181 $this->processOptions();
182 }
183 }
184
185 public function finalSetup( SettingsBuilder $settingsBuilder ) {
186 parent::finalSetup( $settingsBuilder );
187 // re-declare the --schema-version option to include the default schema version
188 // in the description.
190 $this->addOption( 'schema-version', 'Schema version to use for output. ' .
191 'Default: ' . $schemaVersion, false, true );
192 }
193
198 public function registerOutput( $name, $class ) {
199 $this->outputTypes[$name] = $class;
200 }
201
206 public function registerFilter( $name, $class ) {
207 $this->filterTypes[$name] = $class;
208 }
209
217 public function loadPlugin( $class, $file ) {
218 if ( $file != '' ) {
219 require_once $file;
220 }
221 $register = [ $class, 'register' ];
222 $register( $this );
223 }
224
228 protected function processOptions() {
229 $sink = null;
230 $sinks = [];
231
232 $this->schemaVersion = WikiExporter::schemaVersion();
233
234 $options = $this->orderedOptions;
235 foreach ( $options as [ $opt, $param ] ) {
236 switch ( $opt ) {
237 case 'plugin':
238 $val = explode( ':', $param, 2 );
239
240 if ( count( $val ) === 1 ) {
241 $this->loadPlugin( $val[0], '' );
242 } elseif ( count( $val ) === 2 ) {
243 $this->loadPlugin( $val[0], $val[1] );
244 }
245
246 break;
247 case 'output':
248 $split = explode( ':', $param, 2 );
249 if ( count( $split ) !== 2 ) {
250 $this->fatalError( 'Invalid output parameter' );
251 }
252 [ $type, $file ] = $split;
253 if ( $sink !== null ) {
254 $sinks[] = $sink;
255 }
256 if ( !isset( $this->outputTypes[$type] ) ) {
257 $this->fatalError( "Unrecognized output sink type '$type'" );
258 }
259 $class = $this->outputTypes[$type];
260 if ( $type === "7zip" ) {
261 $sink = new $class( $file, intval( $this->getOption( '7ziplevel' ) ) );
262 } else {
263 $sink = new $class( $file );
264 }
265
266 break;
267 case 'filter':
268 $sink ??= new DumpOutput();
269
270 $split = explode( ':', $param, 2 );
271 $key = $split[0];
272
273 if ( !isset( $this->filterTypes[$key] ) ) {
274 $this->fatalError( "Unrecognized filter type '$key'" );
275 }
276
277 $type = $this->filterTypes[$key];
278
279 if ( count( $split ) === 2 ) {
280 $filter = new $type( $sink, $split[1] );
281 } else {
282 $filter = new $type( $sink );
283 }
284
285 // references are lame in php...
286 unset( $sink );
287 $sink = $filter;
288
289 break;
290 case 'schema-version':
291 if ( !in_array( $param, XmlDumpWriter::$supportedSchemas ) ) {
292 $this->fatalError(
293 "Unsupported schema version $param. Supported versions: " .
294 implode( ', ', XmlDumpWriter::$supportedSchemas )
295 );
296 }
297 $this->schemaVersion = $param;
298 break;
299 }
300 }
301
302 if ( $this->hasOption( 'report' ) ) {
303 $this->reportingInterval = intval( $this->getOption( 'report' ) );
304 }
305
306 $sink ??= new DumpOutput();
307 $sinks[] = $sink;
308
309 if ( count( $sinks ) > 1 ) {
310 $this->sink = new DumpMultiWriter( $sinks );
311 } else {
312 $this->sink = $sink;
313 }
314 }
315
316 public function dump( $history, $text = WikiExporter::TEXT ) {
317 # Notice messages will foul up your XML output even if they're
318 # relatively harmless.
319 if ( ini_get( 'display_errors' ) ) {
320 ini_set( 'display_errors', 'stderr' );
321 }
322
323 $this->initProgress( $history );
324
325 $db = $this->backupDb();
326 $services = $this->getServiceContainer();
327 $exporter = $services->getWikiExporterFactory()->getWikiExporter(
328 $db,
329 $history,
330 $text,
331 $this->limitNamespaces
332 );
333 $exporter->setSchemaVersion( $this->schemaVersion );
334 $exporter->dumpUploads = $this->dumpUploads;
335 $exporter->dumpUploadFileContents = $this->dumpUploadFileContents;
336
337 $wrapper = new ExportProgressFilter( $this->sink, $this );
338 $exporter->setOutputSink( $wrapper );
339
340 if ( !$this->skipHeader ) {
341 $exporter->openStream();
342 }
343 # Log item dumps: all or by range
344 if ( $history & WikiExporter::LOGS ) {
345 if ( $this->startId || $this->endId ) {
346 $exporter->logsByRange( $this->startId, $this->endId );
347 } else {
348 $exporter->allLogs();
349 }
350 } elseif ( $this->pages === null ) {
351 # Page dumps: all or by page ID range
352 if ( $this->startId || $this->endId ) {
353 $exporter->pagesByRange( $this->startId, $this->endId, $this->orderRevs );
354 } elseif ( $this->revStartId || $this->revEndId ) {
355 $exporter->revsByRange( $this->revStartId, $this->revEndId );
356 } else {
357 $exporter->allPages();
358 }
359 } else {
360 # Dump of specific pages
361 $exporter->pagesByName( $this->pages );
362 }
363
364 if ( !$this->skipFooter ) {
365 $exporter->closeStream();
366 }
367
368 $this->report( true );
369 }
370
377 public function initProgress( $history = WikiExporter::FULL ) {
378 $table = ( $history == WikiExporter::CURRENT ) ? 'page' : 'revision';
379 $field = ( $history == WikiExporter::CURRENT ) ? 'page_id' : 'rev_id';
380
381 $dbr = $this->forcedDb;
382 if ( $this->forcedDb === null ) {
383 $dbr = $this->getDB( DB_REPLICA, [ 'dump' ] );
384 }
385 $this->maxCount = $dbr->newSelectQueryBuilder()
386 ->select( "MAX($field)" )
387 ->from( $table )
388 ->caller( __METHOD__ )->fetchField();
389 $this->startTime = microtime( true );
390 $this->lastTime = $this->startTime;
391 $this->ID = getmypid();
392 }
393
397 protected function backupDb() {
398 if ( $this->forcedDb !== null ) {
399 return $this->forcedDb;
400 }
401
402 $lbFactory = $this->getServiceContainer()->getDBLoadBalancerFactory();
403 $this->lb = $lbFactory->newMainLB();
404 $db = $this->lb->getMaintenanceConnectionRef( DB_REPLICA, 'dump' );
405
406 // Discourage the server from disconnecting us if it takes a long time
407 // to read out the big ol' batch query.
408 $db->setSessionOptions( [ 'connTimeout' => 3600 * 24 ] );
409
410 return $db;
411 }
412
419 public function setDB( IMaintainableDatabase $db ) {
420 parent::setDB( $db );
421 $this->forcedDb = $db;
422 }
423
424 public function __destruct() {
425 if ( isset( $this->lb ) ) {
426 $this->lb->closeAll( __METHOD__ );
427 }
428 }
429
430 public function reportPage() {
431 $this->pageCount++;
432 }
433
434 public function revCount() {
435 $this->revCount++;
436 $this->report();
437 }
438
439 public function report( $final = false ) {
440 if ( $final xor ( $this->revCount % $this->reportingInterval == 0 ) ) {
441 $this->showReport();
442 }
443 }
444
445 public function showReport() {
446 if ( $this->reporting ) {
447 $now = wfTimestamp( TS_DB );
448 $nowts = microtime( true );
449 $deltaAll = $nowts - $this->startTime;
450 $deltaPart = $nowts - $this->lastTime;
451 $this->pageCountPart = $this->pageCount - $this->pageCountLast;
452 $this->revCountPart = $this->revCount - $this->revCountLast;
453
454 if ( $deltaAll ) {
455 $portion = $this->revCount / $this->maxCount;
456 $eta = $this->startTime + $deltaAll / $portion;
457 $etats = wfTimestamp( TS_DB, intval( $eta ) );
458 $pageRate = $this->pageCount / $deltaAll;
459 $revRate = $this->revCount / $deltaAll;
460 } else {
461 $pageRate = '-';
462 $revRate = '-';
463 $etats = '-';
464 }
465 if ( $deltaPart ) {
466 $pageRatePart = $this->pageCountPart / $deltaPart;
467 $revRatePart = $this->revCountPart / $deltaPart;
468 } else {
469 $pageRatePart = '-';
470 $revRatePart = '-';
471 }
472
473 $dbDomain = WikiMap::getCurrentWikiDbDomain()->getId();
474 $this->progress( sprintf(
475 "%s: %s (ID %d) %d pages (%0.1f|%0.1f/sec all|curr), "
476 . "%d revs (%0.1f|%0.1f/sec all|curr), ETA %s [max %d]",
477 $now, $dbDomain, $this->ID, $this->pageCount, $pageRate,
478 $pageRatePart, $this->revCount, $revRate, $revRatePart, $etats,
479 $this->maxCount
480 ) );
481 $this->lastTime = $nowts;
482 $this->revCountLast = $this->revCount;
483 }
484 }
485
486 protected function progress( $string ) {
487 if ( $this->reporting ) {
488 fwrite( $this->stderr, $string . "\n" );
489 }
490 }
491}
492
494class_alias( BackupDumper::class, 'BackupDumper' );
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
A class containing constants representing the names of configuration variables.
const XmlDumpSchemaVersion
Name constant for the XmlDumpSchemaVersion setting, for use with Config::get()
bool $skipHeader
don't output <mediawiki> and <siteinfo>
IMaintainableDatabase null $forcedDb
The dependency-injected database to use.
finalSetup(SettingsBuilder $settingsBuilder)
Handle some last-minute setup here.
dump( $history, $text=WikiExporter::TEXT)
string null $schemaVersion
null means use default
string[] null $pages
null means all pages
processOptions()
Processes arguments and sets $this->$sink accordingly.
bool $skipFooter
don't output </mediawiki>
setDB(IMaintainableDatabase $db)
Force the dump to use the provided database connection for database operations, wherever possible.
DumpMultiWriter DumpOutput null $sink
Output filters.
initProgress( $history=WikiExporter::FULL)
Initialise starting time and maximum revision count.
loadPlugin( $class, $file)
Load a plugin and register it.
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
array $orderedOptions
Used to read the options in the order they were passed.
loadWithArgv( $argv)
Load params and arguments from a given array of command-line arguments.
fatalError( $msg, $exitCode=1)
Output a message and terminate the current script.
addOption( $name, $description, $required=false, $withArg=false, $shortName=false, $multiOccurrence=false)
Add a parameter to the script.
getDB( $db, $groups=[], $dbDomain=false)
Returns a database to be used by current maintenance script.
hasOption( $name)
Checks to see if a particular option was set.
getOption( $name, $default=null)
Get an option, or return the default.
getServiceContainer()
Returns the main service container.
Builder class for constructing a Config object from a set of sources during bootstrap.
getConfig()
Returns the config loaded so far.
Tools for dealing with other locally-hosted wikis.
Definition WikiMap.php:31
setSessionOptions(array $options)
Override database's default behavior.
Advanced database interface for IDatabase handles that include maintenance methods.
const DB_REPLICA
Definition defines.php:26