MediaWiki  master
BackupDumper.php
Go to the documentation of this file.
1 <?php
28 require_once __DIR__ . '/../Maintenance.php';
29 require_once __DIR__ . '/../../includes/export/WikiExporter.php';
30 
37 
42 abstract class BackupDumper extends Maintenance {
44  public $reporting = true;
46  public $pages = null;
48  public $skipHeader = false;
50  public $skipFooter = false;
52  public $startId = 0;
54  public $endId = 0;
56  public $revStartId = 0;
58  public $revEndId = 0;
60  public $dumpUploads = false;
62  public $dumpUploadFileContents = false;
64  public $orderRevs = false;
66  public $limitNamespaces = [];
68  public $stderr;
69 
71  protected $reportingInterval = 100;
73  protected $pageCount = 0;
75  protected $revCount = 0;
77  protected $schemaVersion = null;
79  protected $server = null;
81  protected $sink = null;
83  protected $lastTime = 0;
85  protected $pageCountLast = 0;
87  protected $revCountLast = 0;
88 
90  protected $outputTypes = [];
92  protected $filterTypes = [];
93 
95  protected $ID = 0;
96 
98  protected $startTime;
100  protected $pageCountPart;
102  protected $revCountPart;
104  protected $maxCount;
106  protected $timeOfCheckpoint;
108  protected $egress;
110  protected $buffer;
112  protected $openElement;
114  protected $atStart;
116  protected $thisRevModel;
118  protected $thisRevFormat;
120  protected $lastName;
122  protected $state;
123 
131  protected $forcedDb = null;
132 
134  protected $lb;
135 
139  public function __construct( $args = null ) {
140  parent::__construct();
141  $this->stderr = fopen( "php://stderr", "wt" );
142 
143  // Built-in output and filter plugins
144  $this->registerOutput( 'file', DumpFileOutput::class );
145  $this->registerOutput( 'gzip', DumpGZipOutput::class );
146  $this->registerOutput( 'bzip2', DumpBZip2Output::class );
147  $this->registerOutput( 'dbzip2', DumpDBZip2Output::class );
148  $this->registerOutput( 'lbzip2', DumpLBZip2Output::class );
149  $this->registerOutput( '7zip', Dump7ZipOutput::class );
150 
151  $this->registerFilter( 'latest', DumpLatestFilter::class );
152  $this->registerFilter( 'notalk', DumpNotalkFilter::class );
153  $this->registerFilter( 'namespace', DumpNamespaceFilter::class );
154 
155  // These three can be specified multiple times
156  $this->addOption( 'plugin', 'Load a dump plugin class. Specify as <class>[:<file>].',
157  false, true, false, true );
158  $this->addOption( 'output', 'Begin a filtered output stream; Specify as <type>:<file>. ' .
159  '<type>s: file, gzip, bzip2, 7zip, dbzip2, lbzip2', false, true, 'o', true );
160  $this->addOption( 'filter', 'Add a filter on an output branch. Specify as ' .
161  '<type>[:<options>]. <types>s: latest, notalk, namespace', false, true, false, true );
162  $this->addOption( 'report', 'Report position and speed after every n pages processed. ' .
163  'Default: 100.', false, true );
164  $this->addOption( 'server', 'Force reading from MySQL server', 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 = null ) {
181  parent::finalSetup( $settingsBuilder );
182  // re-declare the --schema-version option to include the default schema version
183  // in the description.
184  $schemaVersion = $settingsBuilder->getConfig()->get( MainConfigNames::XmlDumpSchemaVersion );
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 
220  public function execute() {
221  throw new MWException( 'execute() must be overridden in subclasses' );
222  }
223 
227  protected function processOptions() {
228  $sink = null;
229  $sinks = [];
230 
231  $this->schemaVersion = WikiExporter::schemaVersion();
232 
233  $options = $this->orderedOptions;
234  foreach ( $options as [ $opt, $param ] ) {
235  switch ( $opt ) {
236  case 'plugin':
237  $val = explode( ':', $param, 2 );
238 
239  if ( count( $val ) === 1 ) {
240  $this->loadPlugin( $val[0], '' );
241  } elseif ( count( $val ) === 2 ) {
242  $this->loadPlugin( $val[0], $val[1] );
243  }
244 
245  break;
246  case 'output':
247  $split = explode( ':', $param, 2 );
248  if ( count( $split ) !== 2 ) {
249  $this->fatalError( 'Invalid output parameter' );
250  }
251  [ $type, $file ] = $split;
252  if ( $sink !== null ) {
253  $sinks[] = $sink;
254  }
255  if ( !isset( $this->outputTypes[$type] ) ) {
256  $this->fatalError( "Unrecognized output sink type '$type'" );
257  }
258  $class = $this->outputTypes[$type];
259  if ( $type === "7zip" ) {
260  $sink = new $class( $file, intval( $this->getOption( '7ziplevel' ) ) );
261  } else {
262  $sink = new $class( $file );
263  }
264 
265  break;
266  case 'filter':
267  if ( $sink === null ) {
268  $sink = new DumpOutput();
269  }
270 
271  $split = explode( ':', $param, 2 );
272  $key = $split[0];
273 
274  if ( !isset( $this->filterTypes[$key] ) ) {
275  $this->fatalError( "Unrecognized filter type '$key'" );
276  }
277 
278  $type = $this->filterTypes[$key];
279 
280  if ( count( $split ) === 2 ) {
281  $filter = new $type( $sink, $split[1] );
282  } else {
283  $filter = new $type( $sink );
284  }
285 
286  // references are lame in php...
287  unset( $sink );
288  $sink = $filter;
289 
290  break;
291  case 'schema-version':
292  if ( !in_array( $param, XmlDumpWriter::$supportedSchemas ) ) {
293  $this->fatalError(
294  "Unsupported schema version $param. Supported versions: " .
295  implode( ', ', XmlDumpWriter::$supportedSchemas )
296  );
297  }
298  $this->schemaVersion = $param;
299  break;
300  }
301  }
302 
303  if ( $this->hasOption( 'report' ) ) {
304  $this->reportingInterval = intval( $this->getOption( 'report' ) );
305  }
306 
307  if ( $this->hasOption( 'server' ) ) {
308  $this->server = $this->getOption( 'server' );
309  }
310 
311  if ( $sink === null ) {
312  $sink = new DumpOutput();
313  }
314  $sinks[] = $sink;
315 
316  if ( count( $sinks ) > 1 ) {
317  $this->sink = new DumpMultiWriter( $sinks );
318  } else {
319  $this->sink = $sink;
320  }
321  }
322 
323  public function dump( $history, $text = WikiExporter::TEXT ) {
324  # Notice messages will foul up your XML output even if they're
325  # relatively harmless.
326  if ( ini_get( 'display_errors' ) ) {
327  ini_set( 'display_errors', 'stderr' );
328  }
329 
330  $this->initProgress( $history );
331 
332  $db = $this->backupDb();
333  $services = MediaWikiServices::getInstance();
334  $exporter = $services->getWikiExporterFactory()->getWikiExporter(
335  $db,
336  $history,
337  $text,
338  $this->limitNamespaces
339  );
340  $exporter->setSchemaVersion( $this->schemaVersion );
341  $exporter->dumpUploads = $this->dumpUploads;
342  $exporter->dumpUploadFileContents = $this->dumpUploadFileContents;
343 
344  $wrapper = new ExportProgressFilter( $this->sink, $this );
345  $exporter->setOutputSink( $wrapper );
346 
347  if ( !$this->skipHeader ) {
348  $exporter->openStream();
349  }
350  # Log item dumps: all or by range
351  if ( $history & WikiExporter::LOGS ) {
352  if ( $this->startId || $this->endId ) {
353  $exporter->logsByRange( $this->startId, $this->endId );
354  } else {
355  $exporter->allLogs();
356  }
357  } elseif ( $this->pages === null ) {
358  # Page dumps: all or by page ID range
359  if ( $this->startId || $this->endId ) {
360  $exporter->pagesByRange( $this->startId, $this->endId, $this->orderRevs );
361  } elseif ( $this->revStartId || $this->revEndId ) {
362  $exporter->revsByRange( $this->revStartId, $this->revEndId );
363  } else {
364  $exporter->allPages();
365  }
366  } else {
367  # Dump of specific pages
368  $exporter->pagesByName( $this->pages );
369  }
370 
371  if ( !$this->skipFooter ) {
372  $exporter->closeStream();
373  }
374 
375  $this->report( true );
376  }
377 
384  public function initProgress( $history = WikiExporter::FULL ) {
385  $table = ( $history == WikiExporter::CURRENT ) ? 'page' : 'revision';
386  $field = ( $history == WikiExporter::CURRENT ) ? 'page_id' : 'rev_id';
387 
389  if ( $this->forcedDb === null ) {
390  $dbr = $this->getDB( DB_REPLICA, [ 'dump' ] );
391  }
392  $this->maxCount = $dbr->selectField( $table, "MAX($field)", '', __METHOD__ );
393  $this->startTime = microtime( true );
394  $this->lastTime = $this->startTime;
395  $this->ID = getmypid();
396  }
397 
404  protected function backupDb() {
405  if ( $this->forcedDb !== null ) {
406  return $this->forcedDb;
407  }
408 
409  $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
410  $this->lb = $lbFactory->newMainLB();
411  $db = $this->lb->getMaintenanceConnectionRef( DB_REPLICA, 'dump' );
412 
413  // Discourage the server from disconnecting us if it takes a long time
414  // to read out the big ol' batch query.
415  $db->setSessionOptions( [ 'connTimeout' => 3600 * 24 ] );
416 
417  return $db;
418  }
419 
426  public function setDB( IMaintainableDatabase $db ) {
427  parent::setDB( $db );
428  $this->forcedDb = $db;
429  }
430 
431  public function __destruct() {
432  if ( isset( $this->lb ) ) {
433  $this->lb->closeAll( __METHOD__ );
434  }
435  }
436 
437  protected function backupServer() {
438  global $wgDBserver;
439 
440  return $this->server ?: $wgDBserver;
441  }
442 
443  public function reportPage() {
444  $this->pageCount++;
445  }
446 
447  public function revCount() {
448  $this->revCount++;
449  $this->report();
450  }
451 
452  public function report( $final = false ) {
453  if ( $final xor ( $this->revCount % $this->reportingInterval == 0 ) ) {
454  $this->showReport();
455  }
456  }
457 
458  public function showReport() {
459  if ( $this->reporting ) {
460  $now = wfTimestamp( TS_DB );
461  $nowts = microtime( true );
462  $deltaAll = $nowts - $this->startTime;
463  $deltaPart = $nowts - $this->lastTime;
464  $this->pageCountPart = $this->pageCount - $this->pageCountLast;
465  $this->revCountPart = $this->revCount - $this->revCountLast;
466 
467  if ( $deltaAll ) {
468  $portion = $this->revCount / $this->maxCount;
469  $eta = $this->startTime + $deltaAll / $portion;
470  $etats = wfTimestamp( TS_DB, intval( $eta ) );
471  $pageRate = $this->pageCount / $deltaAll;
472  $revRate = $this->revCount / $deltaAll;
473  } else {
474  $pageRate = '-';
475  $revRate = '-';
476  $etats = '-';
477  }
478  if ( $deltaPart ) {
479  $pageRatePart = $this->pageCountPart / $deltaPart;
480  $revRatePart = $this->revCountPart / $deltaPart;
481  } else {
482  $pageRatePart = '-';
483  $revRatePart = '-';
484  }
485 
486  $dbDomain = WikiMap::getCurrentWikiDbDomain()->getId();
487  $this->progress( sprintf(
488  "%s: %s (ID %d) %d pages (%0.1f|%0.1f/sec all|curr), "
489  . "%d revs (%0.1f|%0.1f/sec all|curr), ETA %s [max %d]",
490  $now, $dbDomain, $this->ID, $this->pageCount, $pageRate,
491  $pageRatePart, $this->revCount, $revRate, $revRatePart, $etats,
492  $this->maxCount
493  ) );
494  $this->lastTime = $nowts;
495  $this->revCountLast = $this->revCount;
496  }
497  }
498 
499  protected function progress( $string ) {
500  if ( $this->reporting ) {
501  fwrite( $this->stderr, $string . "\n" );
502  }
503  }
504 }
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
string null $server
null means use default
float $startTime
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.
int $reportingInterval
string[] $filterTypes
registerFilter( $name, $class)
progress( $string)
LoadBalancer $lb
string null $thisRevModel
string $lastName
string[] $outputTypes
__construct( $args=null)
execute()
Do the actual work.
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>
finalSetup(SettingsBuilder $settingsBuilder=null)
Handle some last-minute setup here.
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
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)
MediaWiki exception.
Definition: MWException.php:32
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
Definition: Maintenance.php:66
getDB( $db, $groups=[], $dbDomain=false)
Returns a database to be used by current maintenance script.
array $orderedOptions
Used to read the options in the order they were passed.
hasOption( $name)
Checks to see if a particular option was set.
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.
Service locator for MediaWiki core services.
Builder class for constructing a Config object from a set of sources during bootstrap.
Helper tools for dealing with other locally-hosted wikis.
Definition: WikiMap.php:33
static schemaVersion()
Returns the default export schema version, as defined by the XmlDumpSchemaVersion setting.
static string[] $supportedSchemas
the schema versions supported for output @final
$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
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Item class for a filearchive table row.
Definition: router.php:42