MediaWiki master
BackupDumper.php
Go to the documentation of this file.
1<?php
28// @codeCoverageIgnoreStart
29require_once __DIR__ . '/../Maintenance.php';
30require_once __DIR__ . '/../../includes/export/WikiExporter.php';
31// @codeCoverageIgnoreEnd
32
38
43abstract class BackupDumper extends Maintenance {
45 public $reporting = true;
47 public $pages = null;
49 public $skipHeader = false;
51 public $skipFooter = false;
53 public $startId = 0;
55 public $endId = 0;
57 public $revStartId = 0;
59 public $revEndId = 0;
61 public $dumpUploads = false;
65 public $orderRevs = false;
67 public $limitNamespaces = [];
69 public $stderr;
70
72 protected $reportingInterval = 100;
74 protected $pageCount = 0;
76 protected $revCount = 0;
78 protected $schemaVersion = null;
80 protected $server = null;
82 protected $sink = null;
84 protected $lastTime = 0;
86 protected $pageCountLast = 0;
88 protected $revCountLast = 0;
89
91 protected $outputTypes = [];
93 protected $filterTypes = [];
94
96 protected $ID = 0;
97
99 protected $startTime;
101 protected $pageCountPart;
103 protected $revCountPart;
105 protected $maxCount;
109 protected $egress;
111 protected $buffer;
113 protected $openElement;
115 protected $atStart;
117 protected $thisRevModel;
119 protected $thisRevFormat;
121 protected $lastName;
123 protected $state;
124
132 protected $forcedDb = null;
133
135 protected $lb;
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( 'server', 'Force reading from MySQL server', 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.
185 $schemaVersion = $settingsBuilder->getConfig()->get( MainConfigNames::XmlDumpSchemaVersion );
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 if ( $this->hasOption( 'server' ) ) {
303 $this->server = $this->getOption( 'server' );
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
400 protected function backupDb() {
401 if ( $this->forcedDb !== null ) {
402 return $this->forcedDb;
403 }
404
405 $lbFactory = $this->getServiceContainer()->getDBLoadBalancerFactory();
406 $this->lb = $lbFactory->newMainLB();
407 $db = $this->lb->getMaintenanceConnectionRef( DB_REPLICA, 'dump' );
408
409 // Discourage the server from disconnecting us if it takes a long time
410 // to read out the big ol' batch query.
411 $db->setSessionOptions( [ 'connTimeout' => 3600 * 24 ] );
412
413 return $db;
414 }
415
422 public function setDB( IMaintainableDatabase $db ) {
423 parent::setDB( $db );
424 $this->forcedDb = $db;
425 }
426
427 public function __destruct() {
428 if ( isset( $this->lb ) ) {
429 $this->lb->closeAll( __METHOD__ );
430 }
431 }
432
433 protected function backupServer() {
434 global $wgDBserver;
435
436 return $this->server ?: $wgDBserver;
437 }
438
439 public function reportPage() {
440 $this->pageCount++;
441 }
442
443 public function revCount() {
444 $this->revCount++;
445 $this->report();
446 }
447
448 public function report( $final = false ) {
449 if ( $final xor ( $this->revCount % $this->reportingInterval == 0 ) ) {
450 $this->showReport();
451 }
452 }
453
454 public function showReport() {
455 if ( $this->reporting ) {
456 $now = wfTimestamp( TS_DB );
457 $nowts = microtime( true );
458 $deltaAll = $nowts - $this->startTime;
459 $deltaPart = $nowts - $this->lastTime;
460 $this->pageCountPart = $this->pageCount - $this->pageCountLast;
461 $this->revCountPart = $this->revCount - $this->revCountLast;
462
463 if ( $deltaAll ) {
464 $portion = $this->revCount / $this->maxCount;
465 $eta = $this->startTime + $deltaAll / $portion;
466 $etats = wfTimestamp( TS_DB, intval( $eta ) );
467 $pageRate = $this->pageCount / $deltaAll;
468 $revRate = $this->revCount / $deltaAll;
469 } else {
470 $pageRate = '-';
471 $revRate = '-';
472 $etats = '-';
473 }
474 if ( $deltaPart ) {
475 $pageRatePart = $this->pageCountPart / $deltaPart;
476 $revRatePart = $this->revCountPart / $deltaPart;
477 } else {
478 $pageRatePart = '-';
479 $revRatePart = '-';
480 }
481
482 $dbDomain = WikiMap::getCurrentWikiDbDomain()->getId();
483 $this->progress( sprintf(
484 "%s: %s (ID %d) %d pages (%0.1f|%0.1f/sec all|curr), "
485 . "%d revs (%0.1f|%0.1f/sec all|curr), ETA %s [max %d]",
486 $now, $dbDomain, $this->ID, $this->pageCount, $pageRate,
487 $pageRatePart, $this->revCount, $revRate, $revRatePart, $etats,
488 $this->maxCount
489 ) );
490 $this->lastTime = $nowts;
491 $this->revCountLast = $this->revCount;
492 }
493 }
494
495 protected function progress( $string ) {
496 if ( $this->reporting ) {
497 fwrite( $this->stderr, $string . "\n" );
498 }
499 }
500}
getDB()
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
string null $server
null means use default
float $timeOfCheckpoint
array null $limitNamespaces
dump( $history, $text=WikiExporter::TEXT)
setDB(IMaintainableDatabase $db)
Force the dump to use the provided database connection for database operations, wherever possible.
string[] $filterTypes
registerFilter( $name, $class)
progress( $string)
LoadBalancer $lb
string null $thisRevModel
string[] $outputTypes
__construct( $args=null)
IMaintainableDatabase null $forcedDb
The dependency-injected database to use.
DumpMultiWriter DumpOutput null $sink
Output filters.
bool $skipHeader
don't output <mediawiki> and <siteinfo>
bool $skipFooter
don't output </mediawiki>
string[] null $pages
null means all pages
string null $thisRevFormat
initProgress( $history=WikiExporter::FULL)
Initialise starting time and maximum revision count.
string null $schemaVersion
null means use default
finalSetup(SettingsBuilder $settingsBuilder)
Handle some last-minute setup here.
array false $openElement
processOptions()
Processes arguments and sets $this->$sink accordingly.
registerOutput( $name, $class)
bool $dumpUploadFileContents
ExportProgressFilter $egress
resource false $stderr
loadPlugin( $class, $file)
Load a plugin and register it.
report( $final=false)
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.
hasOption( $name)
Checks to see if a particular option was set.
getServiceContainer()
Returns the main service container.
loadWithArgv( $argv)
Load params and arguments from a given array of command-line arguments.
addOption( $name, $description, $required=false, $withArg=false, $shortName=false, $multiOccurrence=false)
Add a parameter to the script.
getOption( $name, $default=null)
Get an option, or return the default.
fatalError( $msg, $exitCode=1)
Output a message and terminate the current script.
A class containing constants representing the names of configuration variables.
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
$wgDBserver
Config variable stub for the DBserver setting, for use by phpdoc and IDEs.
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