MediaWiki master
BackupDumper.php
Go to the documentation of this file.
1<?php
14namespace MediaWiki\Maintenance;
15
16// @codeCoverageIgnoreStart
17require_once __DIR__ . '/../Maintenance.php';
18require_once __DIR__ . '/../../includes/Export/WikiExporter.php';
19// @codeCoverageIgnoreEnd
20
41use Wikimedia\Timestamp\ConvertibleTimestamp;
42use Wikimedia\Timestamp\TimestampFormat as TS;
43
48abstract class BackupDumper extends Maintenance {
50 public $reporting = true;
52 public $pages = null;
54 public $skipHeader = false;
56 public $skipFooter = false;
58 public $startId = 0;
60 public $endId = 0;
62 public $revStartId = 0;
64 public $revEndId = 0;
66 public $dumpUploads = false;
70 public $orderRevs = false;
72 public $limitNamespaces = [];
74 public $stderr;
75
77 protected $reportingInterval = 100;
79 protected $pageCount = 0;
81 protected $revCount = 0;
83 protected $schemaVersion = null;
85 protected $sink = null;
87 protected $lastTime = 0;
89 protected $pageCountLast = 0;
91 protected $revCountLast = 0;
92
94 protected $outputTypes = [];
96 protected $filterTypes = [];
97
99 protected $ID = 0;
100
102 protected $startTime;
104 protected $pageCountPart;
106 protected $revCountPart;
108 protected $maxCount;
112 protected $egress;
114 protected $buffer;
116 protected $openElement;
118 protected $atStart;
120 protected $thisRevModel;
122 protected $thisRevFormat;
124 protected $lastName;
126 protected $state;
127
135 protected $forcedDb = null;
136
140 public function __construct( $args = null ) {
141 parent::__construct();
142 $this->stderr = fopen( "php://stderr", "wt" );
143
144 // Built-in output and filter plugins
145 $this->registerOutput( 'file', DumpFileOutput::class );
146 $this->registerOutput( 'gzip', DumpGZipOutput::class );
147 $this->registerOutput( 'bzip2', DumpBZip2Output::class );
148 $this->registerOutput( 'dbzip2', DumpDBZip2Output::class );
149 $this->registerOutput( 'lbzip2', DumpLBZip2Output::class );
150 $this->registerOutput( '7zip', Dump7ZipOutput::class );
151
152 $this->registerFilter( 'latest', DumpLatestFilter::class );
153 $this->registerFilter( 'notalk', DumpNotalkFilter::class );
154 $this->registerFilter( 'namespace', DumpNamespaceFilter::class );
155
156 // These three can be specified multiple times
157 $this->addOption( 'plugin', 'Load a dump plugin class. Specify as <class>[:<file>].',
158 false, true, false, true );
159 $this->addOption( 'output', 'Begin a filtered output stream; Specify as <type>:<file>. ' .
160 '<type>s: file, gzip, bzip2, 7zip, dbzip2, lbzip2', false, true, 'o', true );
161 $this->addOption( 'filter', 'Add a filter on an output branch. Specify as ' .
162 '<type>[:<options>]. <types>s: latest, notalk, namespace', false, true, false, true );
163 $this->addOption( 'report', 'Report position and speed after every n pages processed. ' .
164 'Default: 100.', false, true );
165 $this->addOption( '7ziplevel', '7zip compression level for all 7zip outputs. Used for ' .
166 '-mx option to 7za command.', false, true );
167 // NOTE: we can't know the default schema version yet, since configuration has not been
168 // loaded when this constructor is called. To work around this, we re-declare
169 // this option in validateParamsAndArgs().
170 $this->addOption( 'schema-version', 'Schema version to use for output.', false, true );
171
172 if ( $args ) {
173 // Args should be loaded and processed so that dump() can be called directly
174 // instead of execute()
175 $this->loadWithArgv( $args );
176 $this->processOptions();
177 }
178 }
179
180 public function finalSetup( SettingsBuilder $settingsBuilder ) {
181 parent::finalSetup( $settingsBuilder );
182 // re-declare the --schema-version option to include the default schema version
183 // in the description.
185 $this->addOption( 'schema-version', 'Schema version to use for output. ' .
186 'Default: ' . $schemaVersion, false, true );
187 }
188
193 public function registerOutput( $name, $class ) {
194 $this->outputTypes[$name] = $class;
195 }
196
201 public function registerFilter( $name, $class ) {
202 $this->filterTypes[$name] = $class;
203 }
204
212 public function loadPlugin( $class, $file ) {
213 if ( $file != '' ) {
214 require_once $file;
215 }
216 $register = [ $class, 'register' ];
217 $register( $this );
218 }
219
223 protected function processOptions() {
224 $sink = null;
225 $sinks = [];
226
227 $this->schemaVersion = WikiExporter::schemaVersion();
228
229 $options = $this->orderedOptions;
230 foreach ( $options as [ $opt, $param ] ) {
231 switch ( $opt ) {
232 case 'plugin':
233 $val = explode( ':', $param, 2 );
234
235 if ( count( $val ) === 1 ) {
236 $this->loadPlugin( $val[0], '' );
237 } elseif ( count( $val ) === 2 ) {
238 $this->loadPlugin( $val[0], $val[1] );
239 }
240
241 break;
242 case 'output':
243 $split = explode( ':', $param, 2 );
244 if ( count( $split ) !== 2 ) {
245 $this->fatalError( 'Invalid output parameter' );
246 }
247 [ $type, $file ] = $split;
248 if ( $sink !== null ) {
249 $sinks[] = $sink;
250 }
251 if ( !isset( $this->outputTypes[$type] ) ) {
252 $this->fatalError( "Unrecognized output sink type '$type'" );
253 }
254 $class = $this->outputTypes[$type];
255 if ( $type === "7zip" ) {
256 $sink = new $class( $file, intval( $this->getOption( '7ziplevel' ) ) );
257 } else {
258 $sink = new $class( $file );
259 }
260
261 break;
262 case 'filter':
263 $sink ??= new DumpOutput();
264
265 $split = explode( ':', $param, 2 );
266 $key = $split[0];
267
268 if ( !isset( $this->filterTypes[$key] ) ) {
269 $this->fatalError( "Unrecognized filter type '$key'" );
270 }
271
272 $type = $this->filterTypes[$key];
273
274 if ( count( $split ) === 2 ) {
275 $filter = new $type( $sink, $split[1] );
276 } else {
277 $filter = new $type( $sink );
278 }
279
280 // references are lame in php...
281 unset( $sink );
282 $sink = $filter;
283
284 break;
285 case 'schema-version':
286 if ( !in_array( $param, XmlDumpWriter::$supportedSchemas ) ) {
287 $this->fatalError(
288 "Unsupported schema version $param. Supported versions: " .
289 implode( ', ', XmlDumpWriter::$supportedSchemas )
290 );
291 }
292 $this->schemaVersion = $param;
293 break;
294 }
295 }
296
297 if ( $this->hasOption( 'report' ) ) {
298 $this->reportingInterval = intval( $this->getOption( 'report' ) );
299 }
300
301 $sink ??= new DumpOutput();
302 $sinks[] = $sink;
303
304 if ( count( $sinks ) > 1 ) {
305 $this->sink = new DumpMultiWriter( $sinks );
306 } else {
307 $this->sink = $sink;
308 }
309 }
310
315 public function dump( $history, $text = WikiExporter::TEXT ) {
316 # Notice messages will foul up your XML output even if they're
317 # relatively harmless.
318 if ( ini_get( 'display_errors' ) ) {
319 ini_set( 'display_errors', 'stderr' );
320 }
321
322 $this->initProgress( $history );
323
324 $services = $this->getServiceContainer();
325 $exporter = $services->getWikiExporterFactory()->getWikiExporter(
326 $this->getBackupDatabase(),
327 $history,
328 $text,
329 $this->limitNamespaces
330 );
331 $exporter->setSchemaVersion( $this->schemaVersion );
332 $exporter->dumpUploads = $this->dumpUploads;
333 $exporter->dumpUploadFileContents = $this->dumpUploadFileContents;
334
335 $wrapper = new ExportProgressFilter( $this->sink, $this );
336 $exporter->setOutputSink( $wrapper );
337
338 if ( !$this->skipHeader ) {
339 $exporter->openStream();
340 }
341 # Log item dumps: all or by range
342 if ( $history & WikiExporter::LOGS ) {
343 if ( $this->startId || $this->endId ) {
344 $exporter->logsByRange( $this->startId, $this->endId );
345 } else {
346 $exporter->allLogs();
347 }
348 } elseif ( $this->pages === null ) {
349 # Page dumps: all or by page ID range
350 if ( $this->startId || $this->endId ) {
351 $exporter->pagesByRange( $this->startId, $this->endId, $this->orderRevs );
352 } elseif ( $this->revStartId || $this->revEndId ) {
353 $exporter->revsByRange( $this->revStartId, $this->revEndId );
354 } else {
355 $exporter->allPages();
356 }
357 } else {
358 # Dump of specific pages
359 $exporter->pagesByName( $this->pages );
360 }
361
362 if ( !$this->skipFooter ) {
363 $exporter->closeStream();
364 }
365
366 $this->report( true );
367 }
368
375 public function initProgress( $history = WikiExporter::FULL ) {
376 $table = ( $history == WikiExporter::CURRENT ) ? 'page' : 'revision';
377 $field = ( $history == WikiExporter::CURRENT ) ? 'page_id' : 'rev_id';
378
379 $dbr = $this->forcedDb;
380 if ( $this->forcedDb === null ) {
381 $dbr = $this->getDB( DB_REPLICA, [ 'dump' ] );
382 }
383 $this->maxCount = $dbr->newSelectQueryBuilder()
384 ->select( "MAX($field)" )
385 ->from( $table )
386 ->caller( __METHOD__ )->fetchField();
387 $this->startTime = microtime( true );
388 $this->lastTime = $this->startTime;
389 $this->ID = getmypid();
390 }
391
395 protected function getBackupDatabase() {
396 if ( $this->forcedDb !== null ) {
397 return $this->forcedDb;
398 }
399
400 $db = $this->getServiceContainer()
401 ->getDBLoadBalancerFactory()
402 ->getMainLB()
403 ->getConnection( DB_REPLICA, 'dump' );
404
405 // Discourage the server from disconnecting us if it takes a long time
406 // to read out the big ol' batch query.
407 $db->setSessionOptions( [ 'connTimeout' => 3600 * 24 ] );
408
409 return $db;
410 }
411
418 public function setDB( IMaintainableDatabase $db ) {
419 parent::setDB( $db );
420 $this->forcedDb = $db;
421 }
422
423 public function reportPage() {
424 $this->pageCount++;
425 }
426
427 public function revCount() {
428 $this->revCount++;
429 $this->report();
430 }
431
432 public function report( bool $final = false ) {
433 if ( $final xor ( $this->revCount % $this->reportingInterval == 0 ) ) {
434 $this->showReport();
435 }
436 }
437
438 public function showReport() {
439 if ( $this->reporting ) {
440 $now = ConvertibleTimestamp::now( TS::DB );
441 $nowts = microtime( true );
442 $deltaAll = $nowts - $this->startTime;
443 $deltaPart = $nowts - $this->lastTime;
444 $this->pageCountPart = $this->pageCount - $this->pageCountLast;
445 $this->revCountPart = $this->revCount - $this->revCountLast;
446
447 if ( $deltaAll ) {
448 $portion = $this->revCount / $this->maxCount;
449 $eta = $this->startTime + $deltaAll / $portion;
450 $etats = wfTimestamp( TS::DB, intval( $eta ) );
451 $pageRate = $this->pageCount / $deltaAll;
452 $revRate = $this->revCount / $deltaAll;
453 } else {
454 $pageRate = '-';
455 $revRate = '-';
456 $etats = '-';
457 }
458 if ( $deltaPart ) {
459 $pageRatePart = $this->pageCountPart / $deltaPart;
460 $revRatePart = $this->revCountPart / $deltaPart;
461 } else {
462 $pageRatePart = '-';
463 $revRatePart = '-';
464 }
465
466 $dbDomain = WikiMap::getCurrentWikiDbDomain()->getId();
467 $this->progress( sprintf(
468 "%s: %s (ID %d) %d pages (%0.1f|%0.1f/sec all|curr), "
469 . "%d revs (%0.1f|%0.1f/sec all|curr), ETA %s [max %d]",
470 $now, $dbDomain, $this->ID, $this->pageCount, $pageRate,
471 $pageRatePart, $this->revCount, $revRate, $revRatePart, $etats,
472 $this->maxCount
473 ) );
474 $this->lastTime = $nowts;
475 $this->revCountLast = $this->revCount;
476 }
477 }
478
479 protected function progress( string $string ) {
480 if ( $this->reporting ) {
481 fwrite( $this->stderr, $string . "\n" );
482 }
483 }
484}
485
487class_alias( BackupDumper::class, 'BackupDumper' );
wfTimestamp( $outputtype=TS::UNIX, $ts=0)
Get a timestamp string in one of various formats.
const DB_REPLICA
Definition defines.php:26
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)
array< string, class-string< DumpOutput > > $outputTypes
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.
array< string, class-string< DumpFilter > > $filterTypes
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:19
Interface to a relational database.
Definition IDatabase.php:31
setSessionOptions(array $options)
Override database's default behavior.
Advanced database interface for IDatabase handles that include maintenance methods.
Update the CREDITS list by merging in the list of git commit authors.