MediaWiki REL1_37
BackupDumper.php
Go to the documentation of this file.
1<?php
28require_once __DIR__ . '/../Maintenance.php';
29require_once __DIR__ . '/../../includes/export/WikiExporter.php';
30
34
39abstract 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;
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;
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( 'schema-version', 'Schema version to use for output. ' .
138 'Default: ' . WikiExporter::schemaVersion(), false, true );
139 $this->addOption( 'server', 'Force reading from MySQL server', false, true );
140 $this->addOption( '7ziplevel', '7zip compression level for all 7zip outputs. Used for ' .
141 '-mx option to 7za command.', false, true );
142
143 if ( $args ) {
144 // Args should be loaded and processed so that dump() can be called directly
145 // instead of execute()
146 $this->loadWithArgv( $args );
147 $this->processOptions();
148 }
149 }
150
155 public function registerOutput( $name, $class ) {
156 $this->outputTypes[$name] = $class;
157 }
158
163 public function registerFilter( $name, $class ) {
164 $this->filterTypes[$name] = $class;
165 }
166
174 public function loadPlugin( $class, $file ) {
175 if ( $file != '' ) {
176 require_once $file;
177 }
178 $register = [ $class, 'register' ];
179 $register( $this );
180 }
181
182 public function execute() {
183 throw new MWException( 'execute() must be overridden in subclasses' );
184 }
185
189 protected function processOptions() {
190 $sink = null;
191 $sinks = [];
192
193 $this->schemaVersion = WikiExporter::schemaVersion();
194
195 $options = $this->orderedOptions;
196 foreach ( $options as [ $opt, $param ] ) {
197 switch ( $opt ) {
198 case 'plugin':
199 $val = explode( ':', $param, 2 );
200
201 if ( count( $val ) === 1 ) {
202 $this->loadPlugin( $val[0], '' );
203 } elseif ( count( $val ) === 2 ) {
204 $this->loadPlugin( $val[0], $val[1] );
205 }
206
207 break;
208 case 'output':
209 $split = explode( ':', $param, 2 );
210 if ( count( $split ) !== 2 ) {
211 $this->fatalError( 'Invalid output parameter' );
212 }
213 list( $type, $file ) = $split;
214 if ( $sink !== null ) {
215 $sinks[] = $sink;
216 }
217 if ( !isset( $this->outputTypes[$type] ) ) {
218 $this->fatalError( "Unrecognized output sink type '$type'" );
219 }
220 $class = $this->outputTypes[$type];
221 if ( $type === "7zip" ) {
222 $sink = new $class( $file, intval( $this->getOption( '7ziplevel' ) ) );
223 } else {
224 $sink = new $class( $file );
225 }
226
227 break;
228 case 'filter':
229 if ( $sink === null ) {
230 $sink = new DumpOutput();
231 }
232
233 $split = explode( ':', $param, 2 );
234 $key = $split[0];
235
236 if ( !isset( $this->filterTypes[$key] ) ) {
237 $this->fatalError( "Unrecognized filter type '$key'" );
238 }
239
240 $type = $this->filterTypes[$key];
241
242 if ( count( $split ) === 1 ) {
243 $filter = new $type( $sink );
244 } elseif ( count( $split ) === 2 ) {
245 $filter = new $type( $sink, $split[1] );
246 }
247
248 // references are lame in php...
249 unset( $sink );
250 $sink = $filter;
251
252 break;
253 case 'schema-version':
254 if ( !in_array( $param, XmlDumpWriter::$supportedSchemas ) ) {
255 $this->fatalError(
256 "Unsupported schema version $param. Supported versions: " .
257 implode( ', ', XmlDumpWriter::$supportedSchemas )
258 );
259 }
260 $this->schemaVersion = $param;
261 break;
262 }
263 }
264
265 if ( $this->hasOption( 'report' ) ) {
266 $this->reportingInterval = intval( $this->getOption( 'report' ) );
267 }
268
269 if ( $this->hasOption( 'server' ) ) {
270 $this->server = $this->getOption( 'server' );
271 }
272
273 if ( $sink === null ) {
274 $sink = new DumpOutput();
275 }
276 $sinks[] = $sink;
277
278 if ( count( $sinks ) > 1 ) {
279 $this->sink = new DumpMultiWriter( $sinks );
280 } else {
281 $this->sink = $sink;
282 }
283 }
284
285 public function dump( $history, $text = WikiExporter::TEXT ) {
286 # Notice messages will foul up your XML output even if they're
287 # relatively harmless.
288 if ( ini_get( 'display_errors' ) ) {
289 ini_set( 'display_errors', 'stderr' );
290 }
291
292 $this->initProgress( $history );
293
294 $db = $this->backupDb();
295 $exporter = new WikiExporter( $db, $history, $text, $this->limitNamespaces );
296 $exporter->setSchemaVersion( $this->schemaVersion );
297 $exporter->dumpUploads = $this->dumpUploads;
298 $exporter->dumpUploadFileContents = $this->dumpUploadFileContents;
299
300 $wrapper = new ExportProgressFilter( $this->sink, $this );
301 $exporter->setOutputSink( $wrapper );
302
303 if ( !$this->skipHeader ) {
304 $exporter->openStream();
305 }
306 # Log item dumps: all or by range
307 if ( $history & WikiExporter::LOGS ) {
308 if ( $this->startId || $this->endId ) {
309 $exporter->logsByRange( $this->startId, $this->endId );
310 } else {
311 $exporter->allLogs();
312 }
313 } elseif ( $this->pages === null ) {
314 # Page dumps: all or by page ID range
315 if ( $this->startId || $this->endId ) {
316 $exporter->pagesByRange( $this->startId, $this->endId, $this->orderRevs );
317 } elseif ( $this->revStartId || $this->revEndId ) {
318 $exporter->revsByRange( $this->revStartId, $this->revEndId );
319 } else {
320 $exporter->allPages();
321 }
322 } else {
323 # Dump of specific pages
324 $exporter->pagesByName( $this->pages );
325 }
326
327 if ( !$this->skipFooter ) {
328 $exporter->closeStream();
329 }
330
331 $this->report( true );
332 }
333
340 public function initProgress( $history = WikiExporter::FULL ) {
341 $table = ( $history == WikiExporter::CURRENT ) ? 'page' : 'revision';
342 $field = ( $history == WikiExporter::CURRENT ) ? 'page_id' : 'rev_id';
343
345 if ( $this->forcedDb === null ) {
346 $dbr = $this->getDB( DB_REPLICA, [ 'dump' ] );
347 }
348 $this->maxCount = $dbr->selectField( $table, "MAX($field)", '', __METHOD__ );
349 $this->startTime = microtime( true );
350 $this->lastTime = $this->startTime;
351 $this->ID = getmypid();
352 }
353
360 protected function backupDb() {
361 if ( $this->forcedDb !== null ) {
362 return $this->forcedDb;
363 }
364
365 $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
366 $this->lb = $lbFactory->newMainLB();
367 $db = $this->lb->getMaintenanceConnectionRef( DB_REPLICA, 'dump' );
368
369 // Discourage the server from disconnecting us if it takes a long time
370 // to read out the big ol' batch query.
371 $db->setSessionOptions( [ 'connTimeout' => 3600 * 24 ] );
372
373 return $db;
374 }
375
382 public function setDB( IMaintainableDatabase $db ) {
383 parent::setDB( $db );
384 $this->forcedDb = $db;
385 }
386
387 public function __destruct() {
388 if ( isset( $this->lb ) ) {
389 $this->lb->closeAll( __METHOD__ );
390 }
391 }
392
393 protected function backupServer() {
394 global $wgDBserver;
395
396 return $this->server ?: $wgDBserver;
397 }
398
399 public function reportPage() {
400 $this->pageCount++;
401 }
402
403 public function revCount() {
404 $this->revCount++;
405 $this->report();
406 }
407
408 public function report( $final = false ) {
409 if ( $final xor ( $this->revCount % $this->reportingInterval == 0 ) ) {
410 $this->showReport();
411 }
412 }
413
414 public function showReport() {
415 if ( $this->reporting ) {
416 $now = wfTimestamp( TS_DB );
417 $nowts = microtime( true );
418 $deltaAll = $nowts - $this->startTime;
419 $deltaPart = $nowts - $this->lastTime;
420 $this->pageCountPart = $this->pageCount - $this->pageCountLast;
421 $this->revCountPart = $this->revCount - $this->revCountLast;
422
423 if ( $deltaAll ) {
424 $portion = $this->revCount / $this->maxCount;
425 $eta = $this->startTime + $deltaAll / $portion;
426 $etats = wfTimestamp( TS_DB, intval( $eta ) );
427 $pageRate = $this->pageCount / $deltaAll;
428 $revRate = $this->revCount / $deltaAll;
429 } else {
430 $pageRate = '-';
431 $revRate = '-';
432 $etats = '-';
433 }
434 if ( $deltaPart ) {
435 $pageRatePart = $this->pageCountPart / $deltaPart;
436 $revRatePart = $this->revCountPart / $deltaPart;
437 } else {
438 $pageRatePart = '-';
439 $revRatePart = '-';
440 }
441
442 $dbDomain = WikiMap::getCurrentWikiDbDomain()->getId();
443 $this->progress( sprintf(
444 "%s: %s (ID %d) %d pages (%0.1f|%0.1f/sec all|curr), "
445 . "%d revs (%0.1f|%0.1f/sec all|curr), ETA %s [max %d]",
446 $now, $dbDomain, $this->ID, $this->pageCount, $pageRate,
447 $pageRatePart, $this->revCount, $revRate, $revRatePart, $etats,
448 $this->maxCount
449 ) );
450 $this->lastTime = $nowts;
451 $this->revCountLast = $this->revCount;
452 }
453 }
454
455 protected function progress( $string ) {
456 if ( $this->reporting ) {
457 fwrite( $this->stderr, $string . "\n" );
458 }
459 }
460}
getDB()
$wgDBserver
Database host name or IP address.
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
bool resource $stderr
dump( $history, $text=WikiExporter::TEXT)
setDB(IMaintainableDatabase $db)
Force the dump to use the provided database connection for database operations, wherever possible.
registerFilter( $name, $class)
progress( $string)
LoadBalancer $lb
string null $thisRevModel
__construct( $args=null)
execute()
Do the actual work.
IMaintainableDatabase null $forcedDb
The dependency-injected database to use.
string null $thisRevFormat
initProgress( $history=WikiExporter::FULL)
Initialise starting time and maximum revision count.
array false $openElement
processOptions()
Processes arguments and sets $this->$sink accordingly.
registerOutput( $name, $class)
ExportProgressFilter $egress
loadPlugin( $class, $file)
Load a plugin and register it.
report( $final=false)
MediaWiki exception.
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.
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.
MediaWikiServices is the service locator for the application scope of MediaWiki.
static schemaVersion()
Returns the default export schema version, as defined by $wgXmlDumpSchemaVersion.
Database connection, tracking, load balancing, and transaction manager for a cluster.
setSessionOptions(array $options)
Override database's default behavior.
Advanced database interface for IDatabase handles that include maintenance methods.
if( $line===false) $args
Definition mcc.php:124
const DB_REPLICA
Definition defines.php:25
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Item class for a filearchive table row.
Definition router.php:42