MediaWiki master
BackupDumper.php
Go to the documentation of this file.
1<?php
13
14namespace MediaWiki\Maintenance;
15
16// @codeCoverageIgnoreStart
17require_once __DIR__ . '/../Maintenance.php';
18require_once __DIR__ . '/../../includes/Export/WikiExporter.php';
19// @codeCoverageIgnoreEnd
20
39use Wikimedia\Rdbms\IMaintainableDatabase;
40use Wikimedia\Rdbms\IReadableDatabase;
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 $lastTimer = 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;
103
105 protected $startTimer;
107 protected $pageCountPart;
109 protected $revCountPart;
111 protected $maxCount;
115 protected $egress;
117 protected $buffer;
119 protected $openElement;
121 protected $atStart;
123 protected $thisRevModel;
125 protected $thisRevFormat;
127 protected $lastName;
129 protected $state;
130
136 private ?IReadableDatabase $forcedDb = null;
137
141 public function __construct( $args = null ) {
142 parent::__construct();
143 $this->stderr = fopen( "php://stderr", "wt" );
144
145 // Built-in output and filter plugins
146 $this->registerOutput( 'file', DumpFileOutput::class );
147 $this->registerOutput( 'gzip', DumpGZipOutput::class );
148 $this->registerOutput( 'bzip2', DumpBZip2Output::class );
149 $this->registerOutput( 'dbzip2', DumpDBZip2Output::class );
150 $this->registerOutput( 'lbzip2', DumpLBZip2Output::class );
151 $this->registerOutput( '7zip', Dump7ZipOutput::class );
152
153 $this->registerFilter( 'latest', DumpLatestFilter::class );
154 $this->registerFilter( 'notalk', DumpNotalkFilter::class );
155 $this->registerFilter( 'namespace', DumpNamespaceFilter::class );
156
157 // These three can be specified multiple times
158 $this->addOption( 'plugin', 'Load a dump plugin class. Specify as <class>[:<file>].',
159 false, true, false, true );
160 $this->addOption( 'output', 'Begin a filtered output stream; Specify as <type>:<file>. ' .
161 '<type>s: file, gzip, bzip2, 7zip, dbzip2, lbzip2', false, true, 'o', true );
162 $this->addOption( 'filter', 'Add a filter on an output branch. Specify as ' .
163 '<type>[:<options>]. <types>s: latest, notalk, namespace', false, true, false, true );
164 $this->addOption( 'report', 'Report position and speed after every n pages processed. ' .
165 'Default: 100.', false, true );
166 $this->addOption( '7ziplevel', '7zip compression level for all 7zip outputs. Used for ' .
167 '-mx option to 7za command.', false, true );
168 // NOTE: we can't know the default schema version yet, since configuration has not been
169 // loaded when this constructor is called. To work around this, we re-declare
170 // this option in validateParamsAndArgs().
171 $this->addOption( 'schema-version', 'Schema version to use for output.', false, true );
172
173 if ( $args ) {
174 // Args should be loaded and processed so that dump() can be called directly
175 // instead of execute()
176 $this->loadWithArgv( $args );
177 $this->processOptions();
178 }
179 }
180
181 public function finalSetup( SettingsBuilder $settingsBuilder ) {
182 parent::finalSetup( $settingsBuilder );
183 // re-declare the --schema-version option to include the default schema version
184 // in the description.
186 $this->addOption( 'schema-version', 'Schema version to use for output. ' .
187 'Default: ' . $schemaVersion, false, true );
188 }
189
194 public function registerOutput( $name, $class ) {
195 $this->outputTypes[$name] = $class;
196 }
197
202 public function registerFilter( $name, $class ) {
203 $this->filterTypes[$name] = $class;
204 }
205
213 public function loadPlugin( $class, $file ) {
214 if ( $file != '' ) {
215 require_once $file;
216 }
217 $register = [ $class, 'register' ];
218 $register( $this );
219 }
220
224 protected function processOptions() {
225 $sink = null;
226 $sinks = [];
227
228 $this->schemaVersion = WikiExporter::schemaVersion();
229
230 $options = $this->orderedOptions;
231 foreach ( $options as [ $opt, $param ] ) {
232 switch ( $opt ) {
233 case 'plugin':
234 $val = explode( ':', $param, 2 );
235
236 if ( count( $val ) === 1 ) {
237 $this->loadPlugin( $val[0], '' );
238 } elseif ( count( $val ) === 2 ) {
239 $this->loadPlugin( $val[0], $val[1] );
240 }
241
242 break;
243 case 'output':
244 $split = explode( ':', $param, 2 );
245 if ( count( $split ) !== 2 ) {
246 $this->fatalError( 'Invalid output parameter' );
247 }
248 [ $type, $file ] = $split;
249 if ( $sink !== null ) {
250 $sinks[] = $sink;
251 }
252 if ( !isset( $this->outputTypes[$type] ) ) {
253 $this->fatalError( "Unrecognized output sink type '$type'" );
254 }
255 $class = $this->outputTypes[$type];
256 if ( $type === "7zip" ) {
257 $sink = new $class( $file, intval( $this->getOption( '7ziplevel' ) ) );
258 } else {
259 $sink = new $class( $file );
260 }
261
262 break;
263 case 'filter':
264 $sink ??= new DumpOutput();
265
266 $split = explode( ':', $param, 2 );
267 $key = $split[0];
268
269 if ( !isset( $this->filterTypes[$key] ) ) {
270 $this->fatalError( "Unrecognized filter type '$key'" );
271 }
272
273 $type = $this->filterTypes[$key];
274
275 if ( count( $split ) === 2 ) {
276 $filter = new $type( $sink, $split[1] );
277 } else {
278 $filter = new $type( $sink );
279 }
280
281 // references are lame in php...
282 unset( $sink );
283 $sink = $filter;
284
285 break;
286 case 'schema-version':
287 if ( !in_array( $param, XmlDumpWriter::$supportedSchemas ) ) {
288 $this->fatalError(
289 "Unsupported schema version $param. Supported versions: " .
290 implode( ', ', XmlDumpWriter::$supportedSchemas )
291 );
292 }
293 $this->schemaVersion = $param;
294 break;
295 }
296 }
297
298 if ( $this->hasOption( 'report' ) ) {
299 $this->reportingInterval = intval( $this->getOption( 'report' ) );
300 }
301
302 $sink ??= new DumpOutput();
303 $sinks[] = $sink;
304
305 if ( count( $sinks ) > 1 ) {
306 $this->sink = new DumpMultiWriter( $sinks );
307 } else {
308 $this->sink = $sink;
309 }
310 }
311
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 $services = $this->getServiceContainer();
326 $exporter = $services->getWikiExporterFactory()->getWikiExporter(
327 $this->getBackupDatabase(),
328 $history,
329 $text,
330 $this->limitNamespaces
331 );
332 $exporter->setSchemaVersion( $this->schemaVersion );
333 $exporter->dumpUploads = $this->dumpUploads;
334 $exporter->dumpUploadFileContents = $this->dumpUploadFileContents;
335
336 $wrapper = new ExportProgressFilter( $this->sink, $this );
337 $exporter->setOutputSink( $wrapper );
338
339 if ( !$this->skipHeader ) {
340 $exporter->openStream();
341 }
342 # Log item dumps: all or by range
343 if ( $history & WikiExporter::LOGS ) {
344 if ( $this->startId || $this->endId ) {
345 $exporter->logsByRange( $this->startId, $this->endId );
346 } else {
347 $exporter->allLogs();
348 }
349 } elseif ( $this->pages === null ) {
350 # Page dumps: all or by page ID range
351 if ( $this->startId || $this->endId ) {
352 $exporter->pagesByRange( $this->startId, $this->endId, $this->orderRevs );
353 } elseif ( $this->revStartId || $this->revEndId ) {
354 $exporter->revsByRange( $this->revStartId, $this->revEndId );
355 } else {
356 $exporter->allPages();
357 }
358 } else {
359 # Dump of specific pages
360 $exporter->pagesByName( $this->pages );
361 }
362
363 if ( !$this->skipFooter ) {
364 $exporter->closeStream();
365 }
366
367 $this->report( true );
368 }
369
376 public function initProgress( $history = WikiExporter::FULL ) {
377 $table = ( $history == WikiExporter::CURRENT ) ? 'page' : 'revision';
378 $field = ( $history == WikiExporter::CURRENT ) ? 'page_id' : 'rev_id';
379
380 $dbr = $this->forcedDb ?? $this->getAnalyticsReplica();
381 $this->maxCount = $dbr->newSelectQueryBuilder()
382 ->select( "MAX($field)" )
383 ->from( $table )
384 ->caller( __METHOD__ )->fetchField();
385 $this->startTime = microtime( true );
386 $this->startTimer = ConvertibleTimestamp::hrtime();
387 $this->lastTimer = $this->startTimer;
388 $this->ID = getmypid();
389 }
390
391 protected function getBackupDatabase(): IReadableDatabase {
392 if ( $this->forcedDb ) {
393 return $this->forcedDb;
394 }
395
396 $db = $this->getServiceContainer()
397 ->getDBLoadBalancerFactory()
398 ->getMainLB()
399 ->getConnection( DB_REPLICA, 'dump' );
400
401 // Discourage the server from disconnecting us if it takes a long time
402 // to read out the big ol' batch query.
403 $db->setSessionOptions( [ 'connTimeout' => 3600 * 24 ] );
404
405 return $db;
406 }
407
414 public function setDB( IMaintainableDatabase $db ) {
415 parent::setDB( $db );
416 $this->forcedDb = $db;
417 }
418
419 public function reportPage() {
420 $this->pageCount++;
421 }
422
423 public function revCount() {
424 $this->revCount++;
425 $this->report();
426 }
427
428 public function report( bool $final = false ) {
429 if ( $final xor ( $this->revCount % $this->reportingInterval == 0 ) ) {
430 $this->showReport();
431 }
432 }
433
434 public function showReport() {
435 if ( $this->reporting ) {
436 $now = ConvertibleTimestamp::now( TS::DB );
437 $nowTimer = ConvertibleTimestamp::hrtime();
438 $deltaAll = ( $nowTimer - $this->startTimer ) / 1e9;
439 $deltaPart = ( $nowTimer - $this->lastTimer ) / 1e9;
440 $this->pageCountPart = $this->pageCount - $this->pageCountLast;
441 $this->revCountPart = $this->revCount - $this->revCountLast;
442
443 if ( $deltaAll ) {
444 $portion = $this->revCount / $this->maxCount;
445 // The ETA is rendered as a date, so it has to be built from the
446 // wall clock rather than the timer. If the system clock is
447 // adjusted while this runs, the ETA shifts with it; the deltas
448 // and rates are measured with the timer and are unaffected.
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->lastTimer = $nowTimer;
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
if(!defined('MW_SETUP_CALLBACK'))
Definition WebStart.php:72
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>
finalSetup(SettingsBuilder $settingsBuilder)
Handle some last-minute setup here.
dump( $history, $text=WikiExporter::TEXT)
int float $lastTimer
Timer reading of the previous report, not a timestamp.
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.
int float $startTimer
Timer reading taken at the same moment as $startTime.
float $startTime
UNIX timestamp, used as the basis for the reported ETA.
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.
getAnalyticsReplica(string|false $virtualDomain=false)
Get a replica connection meant for slow, long-running or analytics-style queries (the "vslow" query g...
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.
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
Advanced database interface for IDatabase handles that include maintenance methods.
A database connection without write operations.