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 
34 
39 abstract class BackupDumper extends Maintenance {
40  public $reporting = true;
41  public $pages = null; // all pages
42  public $skipHeader = false; // don't output <mediawiki> and <siteinfo>
43  public $skipFooter = false; // don't output </mediawiki>
44  public $startId = 0;
45  public $endId = 0;
46  public $revStartId = 0;
47  public $revEndId = 0;
48  public $dumpUploads = false;
49  public $dumpUploadFileContents = false;
50  public $orderRevs = false;
51  public $limitNamespaces = [];
53  public $stderr;
54 
55  protected $reportingInterval = 100;
56  protected $pageCount = 0;
57  protected $revCount = 0;
58  protected $schemaVersion = null; // use default
59  protected $server = null; // use default
60  protected $sink = null; // Output filters
61  protected $lastTime = 0;
62  protected $pageCountLast = 0;
63  protected $revCountLast = 0;
64 
65  protected $outputTypes = [];
66  protected $filterTypes = [];
67 
68  protected $ID = 0;
69 
71  protected $startTime;
73  protected $pageCountPart;
75  protected $revCountPart;
77  protected $maxCount;
79  protected $timeOfCheckpoint;
81  protected $egress;
83  protected $buffer;
85  protected $openElement;
87  protected $atStart;
89  protected $thisRevModel;
91  protected $thisRevFormat;
93  protected $lastName;
95  protected $state;
96 
104  protected $forcedDb = null;
105 
107  protected $lb;
108 
112  public function __construct( $args = null ) {
113  parent::__construct();
114  $this->stderr = fopen( "php://stderr", "wt" );
115 
116  // Built-in output and filter plugins
117  $this->registerOutput( 'file', DumpFileOutput::class );
118  $this->registerOutput( 'gzip', DumpGZipOutput::class );
119  $this->registerOutput( 'bzip2', DumpBZip2Output::class );
120  $this->registerOutput( 'dbzip2', DumpDBZip2Output::class );
121  $this->registerOutput( 'lbzip2', DumpLBZip2Output::class );
122  $this->registerOutput( '7zip', Dump7ZipOutput::class );
123 
124  $this->registerFilter( 'latest', DumpLatestFilter::class );
125  $this->registerFilter( 'notalk', DumpNotalkFilter::class );
126  $this->registerFilter( 'namespace', DumpNamespaceFilter::class );
127 
128  // These three can be specified multiple times
129  $this->addOption( 'plugin', 'Load a dump plugin class. Specify as <class>[:<file>].',
130  false, true, false, true );
131  $this->addOption( 'output', 'Begin a filtered output stream; Specify as <type>:<file>. ' .
132  '<type>s: file, gzip, bzip2, 7zip, dbzip2, lbzip2', false, true, 'o', true );
133  $this->addOption( 'filter', 'Add a filter on an output branch. Specify as ' .
134  '<type>[:<options>]. <types>s: latest, notalk, namespace', false, true, false, true );
135  $this->addOption( 'report', 'Report position and speed after every n pages processed. ' .
136  'Default: 100.', false, true );
137  $this->addOption( 'server', 'Force reading from MySQL server', false, true );
138  $this->addOption( '7ziplevel', '7zip compression level for all 7zip outputs. Used for ' .
139  '-mx option to 7za command.', false, true );
140  // NOTE: we can't know the default schema version yet, since configuration has not been
141  // loaded when this constructor is called. To work around this, we re-declare
142  // this option in validateParamsAndArgs().
143  $this->addOption( 'schema-version', 'Schema version to use for output.', false, true );
144 
145  if ( $args ) {
146  // Args should be loaded and processed so that dump() can be called directly
147  // instead of execute()
148  $this->loadWithArgv( $args );
149  $this->processOptions();
150  }
151  }
152 
153  public function validateParamsAndArgs() {
154  // re-declare the --schema-version option to include the default schema version
155  // in the description.
156  $this->addOption( 'schema-version', 'Schema version to use for output. ' .
157  'Default: ' . WikiExporter::schemaVersion(), false, true );
158  parent::validateParamsAndArgs();
159  }
160 
165  public function registerOutput( $name, $class ) {
166  $this->outputTypes[$name] = $class;
167  }
168 
173  public function registerFilter( $name, $class ) {
174  $this->filterTypes[$name] = $class;
175  }
176 
184  public function loadPlugin( $class, $file ) {
185  if ( $file != '' ) {
186  require_once $file;
187  }
188  $register = [ $class, 'register' ];
189  $register( $this );
190  }
191 
192  public function execute() {
193  throw new MWException( 'execute() must be overridden in subclasses' );
194  }
195 
199  protected function processOptions() {
200  $sink = null;
201  $sinks = [];
202 
203  $this->schemaVersion = WikiExporter::schemaVersion();
204 
205  $options = $this->orderedOptions;
206  foreach ( $options as [ $opt, $param ] ) {
207  switch ( $opt ) {
208  case 'plugin':
209  $val = explode( ':', $param, 2 );
210 
211  if ( count( $val ) === 1 ) {
212  $this->loadPlugin( $val[0], '' );
213  } elseif ( count( $val ) === 2 ) {
214  $this->loadPlugin( $val[0], $val[1] );
215  }
216 
217  break;
218  case 'output':
219  $split = explode( ':', $param, 2 );
220  if ( count( $split ) !== 2 ) {
221  $this->fatalError( 'Invalid output parameter' );
222  }
223  list( $type, $file ) = $split;
224  if ( $sink !== null ) {
225  $sinks[] = $sink;
226  }
227  if ( !isset( $this->outputTypes[$type] ) ) {
228  $this->fatalError( "Unrecognized output sink type '$type'" );
229  }
230  $class = $this->outputTypes[$type];
231  if ( $type === "7zip" ) {
232  $sink = new $class( $file, intval( $this->getOption( '7ziplevel' ) ) );
233  } else {
234  $sink = new $class( $file );
235  }
236 
237  break;
238  case 'filter':
239  if ( $sink === null ) {
240  $sink = new DumpOutput();
241  }
242 
243  $split = explode( ':', $param, 2 );
244  $key = $split[0];
245 
246  if ( !isset( $this->filterTypes[$key] ) ) {
247  $this->fatalError( "Unrecognized filter type '$key'" );
248  }
249 
250  $type = $this->filterTypes[$key];
251 
252  if ( count( $split ) === 1 ) {
253  $filter = new $type( $sink );
254  } elseif ( count( $split ) === 2 ) {
255  $filter = new $type( $sink, $split[1] );
256  }
257 
258  // references are lame in php...
259  unset( $sink );
260  $sink = $filter;
261 
262  break;
263  case 'schema-version':
264  if ( !in_array( $param, XmlDumpWriter::$supportedSchemas ) ) {
265  $this->fatalError(
266  "Unsupported schema version $param. Supported versions: " .
267  implode( ', ', XmlDumpWriter::$supportedSchemas )
268  );
269  }
270  $this->schemaVersion = $param;
271  break;
272  }
273  }
274 
275  if ( $this->hasOption( 'report' ) ) {
276  $this->reportingInterval = intval( $this->getOption( 'report' ) );
277  }
278 
279  if ( $this->hasOption( 'server' ) ) {
280  $this->server = $this->getOption( 'server' );
281  }
282 
283  if ( $sink === null ) {
284  $sink = new DumpOutput();
285  }
286  $sinks[] = $sink;
287 
288  if ( count( $sinks ) > 1 ) {
289  $this->sink = new DumpMultiWriter( $sinks );
290  } else {
291  $this->sink = $sink;
292  }
293  }
294 
295  public function dump( $history, $text = WikiExporter::TEXT ) {
296  # Notice messages will foul up your XML output even if they're
297  # relatively harmless.
298  if ( ini_get( 'display_errors' ) ) {
299  ini_set( 'display_errors', 'stderr' );
300  }
301 
302  $this->initProgress( $history );
303 
304  $db = $this->backupDb();
305  $services = MediaWikiServices::getInstance();
306  $exporter = $services->getWikiExporterFactory()->getWikiExporter(
307  $db,
308  $history,
309  $text,
310  $this->limitNamespaces
311  );
312  $exporter->setSchemaVersion( $this->schemaVersion );
313  $exporter->dumpUploads = $this->dumpUploads;
314  $exporter->dumpUploadFileContents = $this->dumpUploadFileContents;
315 
316  $wrapper = new ExportProgressFilter( $this->sink, $this );
317  $exporter->setOutputSink( $wrapper );
318 
319  if ( !$this->skipHeader ) {
320  $exporter->openStream();
321  }
322  # Log item dumps: all or by range
323  if ( $history & WikiExporter::LOGS ) {
324  if ( $this->startId || $this->endId ) {
325  $exporter->logsByRange( $this->startId, $this->endId );
326  } else {
327  $exporter->allLogs();
328  }
329  } elseif ( $this->pages === null ) {
330  # Page dumps: all or by page ID range
331  if ( $this->startId || $this->endId ) {
332  $exporter->pagesByRange( $this->startId, $this->endId, $this->orderRevs );
333  } elseif ( $this->revStartId || $this->revEndId ) {
334  $exporter->revsByRange( $this->revStartId, $this->revEndId );
335  } else {
336  $exporter->allPages();
337  }
338  } else {
339  # Dump of specific pages
340  $exporter->pagesByName( $this->pages );
341  }
342 
343  if ( !$this->skipFooter ) {
344  $exporter->closeStream();
345  }
346 
347  $this->report( true );
348  }
349 
356  public function initProgress( $history = WikiExporter::FULL ) {
357  $table = ( $history == WikiExporter::CURRENT ) ? 'page' : 'revision';
358  $field = ( $history == WikiExporter::CURRENT ) ? 'page_id' : 'rev_id';
359 
361  if ( $this->forcedDb === null ) {
362  $dbr = $this->getDB( DB_REPLICA, [ 'dump' ] );
363  }
364  $this->maxCount = $dbr->selectField( $table, "MAX($field)", '', __METHOD__ );
365  $this->startTime = microtime( true );
366  $this->lastTime = $this->startTime;
367  $this->ID = getmypid();
368  }
369 
376  protected function backupDb() {
377  if ( $this->forcedDb !== null ) {
378  return $this->forcedDb;
379  }
380 
381  $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
382  $this->lb = $lbFactory->newMainLB();
383  $db = $this->lb->getMaintenanceConnectionRef( DB_REPLICA, 'dump' );
384 
385  // Discourage the server from disconnecting us if it takes a long time
386  // to read out the big ol' batch query.
387  $db->setSessionOptions( [ 'connTimeout' => 3600 * 24 ] );
388 
389  return $db;
390  }
391 
398  public function setDB( IMaintainableDatabase $db ) {
399  parent::setDB( $db );
400  $this->forcedDb = $db;
401  }
402 
403  public function __destruct() {
404  if ( isset( $this->lb ) ) {
405  $this->lb->closeAll( __METHOD__ );
406  }
407  }
408 
409  protected function backupServer() {
410  global $wgDBserver;
411 
412  return $this->server ?: $wgDBserver;
413  }
414 
415  public function reportPage() {
416  $this->pageCount++;
417  }
418 
419  public function revCount() {
420  $this->revCount++;
421  $this->report();
422  }
423 
424  public function report( $final = false ) {
425  if ( $final xor ( $this->revCount % $this->reportingInterval == 0 ) ) {
426  $this->showReport();
427  }
428  }
429 
430  public function showReport() {
431  if ( $this->reporting ) {
432  $now = wfTimestamp( TS_DB );
433  $nowts = microtime( true );
434  $deltaAll = $nowts - $this->startTime;
435  $deltaPart = $nowts - $this->lastTime;
436  $this->pageCountPart = $this->pageCount - $this->pageCountLast;
437  $this->revCountPart = $this->revCount - $this->revCountLast;
438 
439  if ( $deltaAll ) {
440  $portion = $this->revCount / $this->maxCount;
441  $eta = $this->startTime + $deltaAll / $portion;
442  $etats = wfTimestamp( TS_DB, intval( $eta ) );
443  $pageRate = $this->pageCount / $deltaAll;
444  $revRate = $this->revCount / $deltaAll;
445  } else {
446  $pageRate = '-';
447  $revRate = '-';
448  $etats = '-';
449  }
450  if ( $deltaPart ) {
451  $pageRatePart = $this->pageCountPart / $deltaPart;
452  $revRatePart = $this->revCountPart / $deltaPart;
453  } else {
454  $pageRatePart = '-';
455  $revRatePart = '-';
456  }
457 
458  $dbDomain = WikiMap::getCurrentWikiDbDomain()->getId();
459  $this->progress( sprintf(
460  "%s: %s (ID %d) %d pages (%0.1f|%0.1f/sec all|curr), "
461  . "%d revs (%0.1f|%0.1f/sec all|curr), ETA %s [max %d]",
462  $now, $dbDomain, $this->ID, $this->pageCount, $pageRate,
463  $pageRatePart, $this->revCount, $revRate, $revRatePart, $etats,
464  $this->maxCount
465  ) );
466  $this->lastTime = $nowts;
467  $this->revCountLast = $this->revCount;
468  }
469  }
470 
471  protected function progress( $string ) {
472  if ( $this->reporting ) {
473  fwrite( $this->stderr, $string . "\n" );
474  }
475  }
476 }
BackupDumper\registerOutput
registerOutput( $name, $class)
Definition: BackupDumper.php:165
BackupDumper\$thisRevFormat
string null $thisRevFormat
Definition: BackupDumper.php:91
WikiExporter\schemaVersion
static schemaVersion()
Returns the default export schema version, as defined by the XmlDumpSchemaVersion setting.
Definition: WikiExporter.php:98
BackupDumper\$endId
$endId
Definition: BackupDumper.php:45
BackupDumper\revCount
revCount()
Definition: BackupDumper.php:419
WikiMap\getCurrentWikiDbDomain
static getCurrentWikiDbDomain()
Definition: WikiMap.php:293
BackupDumper\backupDb
backupDb()
Definition: BackupDumper.php:376
$wgDBserver
$wgDBserver
Database host name or IP address.
Definition: DefaultSettings.php:2090
BackupDumper\$startTime
int $startTime
Definition: BackupDumper.php:71
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:203
BackupDumper\$revCountPart
int $revCountPart
Definition: BackupDumper.php:75
Maintenance\fatalError
fatalError( $msg, $exitCode=1)
Output a message and terminate the current script.
Definition: Maintenance.php:489
WikiExporter\CURRENT
const CURRENT
Definition: WikiExporter.php:57
BackupDumper\$revEndId
$revEndId
Definition: BackupDumper.php:47
wfTimestamp
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Definition: GlobalFunctions.php:1649
BackupDumper\backupServer
backupServer()
Definition: BackupDumper.php:409
BackupDumper\$limitNamespaces
$limitNamespaces
Definition: BackupDumper.php:51
BackupDumper\$thisRevModel
string null $thisRevModel
Definition: BackupDumper.php:89
BackupDumper\$openElement
array false $openElement
Definition: BackupDumper.php:85
BackupDumper\__destruct
__destruct()
Definition: BackupDumper.php:403
BackupDumper\$revCountLast
$revCountLast
Definition: BackupDumper.php:63
$file
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Item class for a filearchive table row.
Definition: router.php:42
BackupDumper\$pageCountLast
$pageCountLast
Definition: BackupDumper.php:62
BackupDumper\$revCount
$revCount
Definition: BackupDumper.php:57
BackupDumper\$sink
$sink
Definition: BackupDumper.php:60
Maintenance
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
Definition: Maintenance.php:59
BackupDumper\$lb
LoadBalancer $lb
Definition: BackupDumper.php:107
XmlDumpWriter\$supportedSchemas
static string[] $supportedSchemas
the schema versions supported for output @final
Definition: XmlDumpWriter.php:57
BackupDumper\$skipFooter
$skipFooter
Definition: BackupDumper.php:43
BackupDumper\$orderRevs
$orderRevs
Definition: BackupDumper.php:50
BackupDumper\$buffer
string $buffer
Definition: BackupDumper.php:83
Maintenance\loadWithArgv
loadWithArgv( $argv)
Load params and arguments from a given array of command-line arguments.
Definition: Maintenance.php:817
$dbr
$dbr
Definition: testCompression.php:54
BackupDumper\$schemaVersion
$schemaVersion
Definition: BackupDumper.php:58
DumpMultiWriter
Definition: DumpMultiWriter.php:29
BackupDumper\$skipHeader
$skipHeader
Definition: BackupDumper.php:42
BackupDumper\$reporting
$reporting
Definition: BackupDumper.php:40
MWException
MediaWiki exception.
Definition: MWException.php:29
BackupDumper\showReport
showReport()
Definition: BackupDumper.php:430
WikiExporter\TEXT
const TEXT
Definition: WikiExporter.php:62
BackupDumper\$startId
$startId
Definition: BackupDumper.php:44
BackupDumper\$maxCount
int $maxCount
Definition: BackupDumper.php:77
Maintenance\addOption
addOption( $name, $description, $required=false, $withArg=false, $shortName=false, $multiOccurrence=false)
Add a parameter to the script.
Definition: Maintenance.php:249
$args
if( $line===false) $args
Definition: mcc.php:124
Maintenance\$orderedOptions
array $orderedOptions
Used to read the options in the order they were passed.
Definition: Maintenance.php:172
BackupDumper\loadPlugin
loadPlugin( $class, $file)
Load a plugin and register it.
Definition: BackupDumper.php:184
BackupDumper\$dumpUploadFileContents
$dumpUploadFileContents
Definition: BackupDumper.php:49
DB_REPLICA
const DB_REPLICA
Definition: defines.php:25
DumpOutput
Definition: DumpOutput.php:29
BackupDumper\$timeOfCheckpoint
int $timeOfCheckpoint
Definition: BackupDumper.php:79
BackupDumper\$ID
$ID
Definition: BackupDumper.php:68
Wikimedia\Rdbms\LoadBalancer
Database connection, tracking, load balancing, and transaction manager for a cluster.
Definition: LoadBalancer.php:43
BackupDumper\initProgress
initProgress( $history=WikiExporter::FULL)
Initialise starting time and maximum revision count.
Definition: BackupDumper.php:356
BackupDumper\$state
string $state
Definition: BackupDumper.php:95
BackupDumper\report
report( $final=false)
Definition: BackupDumper.php:424
BackupDumper\$pageCountPart
int $pageCountPart
Definition: BackupDumper.php:73
BackupDumper\$outputTypes
$outputTypes
Definition: BackupDumper.php:65
BackupDumper\$reportingInterval
$reportingInterval
Definition: BackupDumper.php:55
BackupDumper\$pages
$pages
Definition: BackupDumper.php:41
WikiExporter\FULL
const FULL
Definition: WikiExporter.php:56
BackupDumper\$dumpUploads
$dumpUploads
Definition: BackupDumper.php:48
Maintenance\getDB
getDB( $db, $groups=[], $dbDomain=false)
Returns a database to be used by current maintenance script.
Definition: Maintenance.php:1375
BackupDumper\__construct
__construct( $args=null)
Definition: BackupDumper.php:112
BackupDumper\$atStart
bool $atStart
Definition: BackupDumper.php:87
BackupDumper\progress
progress( $string)
Definition: BackupDumper.php:471
BackupDumper\$stderr
bool resource $stderr
Definition: BackupDumper.php:53
BackupDumper
Definition: BackupDumper.php:39
BackupDumper\execute
execute()
Do the actual work.
Definition: BackupDumper.php:192
Maintenance\getOption
getOption( $name, $default=null)
Get an option, or return the default.
Definition: Maintenance.php:286
WikiExporter\LOGS
const LOGS
Definition: WikiExporter.php:59
BackupDumper\$server
$server
Definition: BackupDumper.php:59
BackupDumper\reportPage
reportPage()
Definition: BackupDumper.php:415
BackupDumper\processOptions
processOptions()
Processes arguments and sets $this->$sink accordingly.
Definition: BackupDumper.php:199
BackupDumper\$lastTime
$lastTime
Definition: BackupDumper.php:61
BackupDumper\dump
dump( $history, $text=WikiExporter::TEXT)
Definition: BackupDumper.php:295
BackupDumper\$filterTypes
$filterTypes
Definition: BackupDumper.php:66
BackupDumper\validateParamsAndArgs
validateParamsAndArgs()
Run some validation checks on the params, etc.
Definition: BackupDumper.php:153
ExportProgressFilter
Definition: ExportProgressFilter.php:27
Maintenance\hasOption
hasOption( $name)
Checks to see if a particular option was set.
Definition: Maintenance.php:271
Wikimedia\Rdbms\IDatabase\setSessionOptions
setSessionOptions(array $options)
Override database's default behavior.
Wikimedia\Rdbms\IMaintainableDatabase
Advanced database interface for IDatabase handles that include maintenance methods.
Definition: IMaintainableDatabase.php:38
BackupDumper\setDB
setDB(IMaintainableDatabase $db)
Force the dump to use the provided database connection for database operations, wherever possible.
Definition: BackupDumper.php:398
BackupDumper\$forcedDb
IMaintainableDatabase null $forcedDb
The dependency-injected database to use.
Definition: BackupDumper.php:104
BackupDumper\$egress
ExportProgressFilter $egress
Definition: BackupDumper.php:81
BackupDumper\$revStartId
$revStartId
Definition: BackupDumper.php:46
BackupDumper\$pageCount
$pageCount
Definition: BackupDumper.php:56
BackupDumper\$lastName
string $lastName
Definition: BackupDumper.php:93
$type
$type
Definition: testCompression.php:52
BackupDumper\registerFilter
registerFilter( $name, $class)
Definition: BackupDumper.php:173