Merge "Provide command to adjust phpunit.xml for code coverage"
[lhc/web/wiklou.git] / maintenance / includes / BackupDumper.php
1 <?php
2 /**
3 * Base classes for database-dumping maintenance scripts.
4 *
5 * Copyright © 2005 Brion Vibber <brion@pobox.com>
6 * https://www.mediawiki.org/
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
22 *
23 * @file
24 * @ingroup Dump
25 * @ingroup Maintenance
26 */
27
28 require_once __DIR__ . '/../Maintenance.php';
29 require_once __DIR__ . '/../../includes/export/WikiExporter.php';
30
31 use MediaWiki\MediaWikiServices;
32 use Wikimedia\Rdbms\LoadBalancer;
33 use Wikimedia\Rdbms\IMaintainableDatabase;
34
35 /**
36 * @ingroup Dump
37 * @ingroup Maintenance
38 */
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 = [];
52 /** @var bool|resource */
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
70 /** @var int */
71 protected $startTime;
72 /** @var int */
73 protected $pageCountPart;
74 /** @var int */
75 protected $revCountPart;
76 /** @var int */
77 protected $maxCount;
78 /** @var int */
79 protected $timeOfCheckpoint;
80 /** @var ExportProgressFilter */
81 protected $egress;
82 /** @var string */
83 protected $buffer;
84 /** @var array|false */
85 protected $openElement;
86 /** @var bool */
87 protected $atStart;
88 /** @var string|null */
89 protected $thisRevModel;
90 /** @var string|null */
91 protected $thisRevFormat;
92 /** @var string */
93 protected $lastName;
94 /** @var string */
95 protected $state;
96
97 /**
98 * The dependency-injected database to use.
99 *
100 * @var IMaintainableDatabase|null
101 *
102 * @see self::setDB
103 */
104 protected $forcedDb = null;
105
106 /** @var LoadBalancer */
107 protected $lb;
108
109 /**
110 * @param array|null $args For backward compatibility
111 */
112 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, false, 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
151 /**
152 * @param string $name
153 * @param string $class Name of output filter plugin class
154 */
155 function registerOutput( $name, $class ) {
156 $this->outputTypes[$name] = $class;
157 }
158
159 /**
160 * @param string $name
161 * @param string $class Name of filter plugin class
162 */
163 function registerFilter( $name, $class ) {
164 $this->filterTypes[$name] = $class;
165 }
166
167 /**
168 * Load a plugin and register it
169 *
170 * @param string $class Name of plugin class; must have a static 'register'
171 * method that takes a BackupDumper as a parameter.
172 * @param string $file Full or relative path to the PHP file to load, or empty
173 */
174 function loadPlugin( $class, $file ) {
175 if ( $file != '' ) {
176 require_once $file;
177 }
178 $register = [ $class, 'register' ];
179 $register( $this );
180 }
181
182 function execute() {
183 throw new MWException( 'execute() must be overridden in subclasses' );
184 }
185
186 /**
187 * Processes arguments and sets $this->$sink accordingly
188 */
189 function processOptions() {
190 $sink = null;
191 $sinks = [];
192
193 $this->schemaVersion = WikiExporter::schemaVersion();
194
195 $options = $this->orderedOptions;
196 foreach ( $options as $arg ) {
197 list( $opt, $param ) = $arg;
198
199 switch ( $opt ) {
200 case 'plugin':
201 $val = explode( ':', $param, 2 );
202
203 if ( count( $val ) === 1 ) {
204 $this->loadPlugin( $val[0], '' );
205 } elseif ( count( $val ) === 2 ) {
206 $this->loadPlugin( $val[0], $val[1] );
207 }
208
209 break;
210 case 'output':
211 $split = explode( ':', $param, 2 );
212 if ( count( $split ) !== 2 ) {
213 $this->fatalError( 'Invalid output parameter' );
214 }
215 list( $type, $file ) = $split;
216 if ( !is_null( $sink ) ) {
217 $sinks[] = $sink;
218 }
219 if ( !isset( $this->outputTypes[$type] ) ) {
220 $this->fatalError( "Unrecognized output sink type '$type'" );
221 }
222 $class = $this->outputTypes[$type];
223 if ( $type === "7zip" ) {
224 $sink = new $class( $file, intval( $this->getOption( '7ziplevel' ) ) );
225 } else {
226 $sink = new $class( $file );
227 }
228
229 break;
230 case 'filter':
231 if ( is_null( $sink ) ) {
232 $sink = new DumpOutput();
233 }
234
235 $split = explode( ':', $param, 2 );
236 $key = $split[0];
237
238 if ( !isset( $this->filterTypes[$key] ) ) {
239 $this->fatalError( "Unrecognized filter type '$key'" );
240 }
241
242 $type = $this->filterTypes[$key];
243
244 if ( count( $split ) === 1 ) {
245 $filter = new $type( $sink );
246 } elseif ( count( $split ) === 2 ) {
247 $filter = new $type( $sink, $split[1] );
248 }
249
250 // references are lame in php...
251 unset( $sink );
252 $sink = $filter;
253
254 break;
255 case 'schema-version':
256 if ( !in_array( $param, XmlDumpWriter::$supportedSchemas ) ) {
257 $this->fatalError(
258 "Unsupported schema version $param. Supported versions: " .
259 implode( ', ', XmlDumpWriter::$supportedSchemas )
260 );
261 }
262 $this->schemaVersion = $param;
263 break;
264 }
265 }
266
267 if ( $this->hasOption( 'report' ) ) {
268 $this->reportingInterval = intval( $this->getOption( 'report' ) );
269 }
270
271 if ( $this->hasOption( 'server' ) ) {
272 $this->server = $this->getOption( 'server' );
273 }
274
275 if ( is_null( $sink ) ) {
276 $sink = new DumpOutput();
277 }
278 $sinks[] = $sink;
279
280 if ( count( $sinks ) > 1 ) {
281 $this->sink = new DumpMultiWriter( $sinks );
282 } else {
283 $this->sink = $sink;
284 }
285 }
286
287 function dump( $history, $text = WikiExporter::TEXT ) {
288 # Notice messages will foul up your XML output even if they're
289 # relatively harmless.
290 if ( ini_get( 'display_errors' ) ) {
291 ini_set( 'display_errors', 'stderr' );
292 }
293
294 $this->initProgress( $history );
295
296 $db = $this->backupDb();
297 $exporter = new WikiExporter( $db, $history, $text, $this->limitNamespaces );
298 $exporter->setSchemaVersion( $this->schemaVersion );
299 $exporter->dumpUploads = $this->dumpUploads;
300 $exporter->dumpUploadFileContents = $this->dumpUploadFileContents;
301
302 $wrapper = new ExportProgressFilter( $this->sink, $this );
303 $exporter->setOutputSink( $wrapper );
304
305 if ( !$this->skipHeader ) {
306 $exporter->openStream();
307 }
308 # Log item dumps: all or by range
309 if ( $history & WikiExporter::LOGS ) {
310 if ( $this->startId || $this->endId ) {
311 $exporter->logsByRange( $this->startId, $this->endId );
312 } else {
313 $exporter->allLogs();
314 }
315 } elseif ( is_null( $this->pages ) ) {
316 # Page dumps: all or by page ID range
317 if ( $this->startId || $this->endId ) {
318 $exporter->pagesByRange( $this->startId, $this->endId, $this->orderRevs );
319 } elseif ( $this->revStartId || $this->revEndId ) {
320 $exporter->revsByRange( $this->revStartId, $this->revEndId );
321 } else {
322 $exporter->allPages();
323 }
324 } else {
325 # Dump of specific pages
326 $exporter->pagesByName( $this->pages );
327 }
328
329 if ( !$this->skipFooter ) {
330 $exporter->closeStream();
331 }
332
333 $this->report( true );
334 }
335
336 /**
337 * Initialise starting time and maximum revision count.
338 * We'll make ETA calculations based an progress, assuming relatively
339 * constant per-revision rate.
340 * @param int $history WikiExporter::CURRENT or WikiExporter::FULL
341 */
342 function initProgress( $history = WikiExporter::FULL ) {
343 $table = ( $history == WikiExporter::CURRENT ) ? 'page' : 'revision';
344 $field = ( $history == WikiExporter::CURRENT ) ? 'page_id' : 'rev_id';
345
346 $dbr = $this->forcedDb;
347 if ( $this->forcedDb === null ) {
348 $dbr = $this->getDB( DB_REPLICA );
349 }
350 $this->maxCount = $dbr->selectField( $table, "MAX($field)", '', __METHOD__ );
351 $this->startTime = microtime( true );
352 $this->lastTime = $this->startTime;
353 $this->ID = getmypid();
354 }
355
356 /**
357 * @todo Fixme: the --server parameter is currently not respected, as it
358 * doesn't seem terribly easy to ask the load balancer for a particular
359 * connection by name.
360 * @return IMaintainableDatabase
361 */
362 function backupDb() {
363 if ( $this->forcedDb !== null ) {
364 return $this->forcedDb;
365 }
366
367 $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
368 $this->lb = $lbFactory->newMainLB();
369 $db = $this->lb->getMaintenanceConnectionRef( DB_REPLICA, 'dump' );
370
371 // Discourage the server from disconnecting us if it takes a long time
372 // to read out the big ol' batch query.
373 $db->setSessionOptions( [ 'connTimeout' => 3600 * 24 ] );
374
375 return $db;
376 }
377
378 /**
379 * Force the dump to use the provided database connection for database
380 * operations, wherever possible.
381 *
382 * @param IMaintainableDatabase $db The database connection to use
383 */
384 function setDB( IMaintainableDatabase $db ) {
385 parent::setDB( $db );
386 $this->forcedDb = $db;
387 }
388
389 function __destruct() {
390 if ( isset( $this->lb ) ) {
391 $this->lb->closeAll();
392 }
393 }
394
395 function backupServer() {
396 global $wgDBserver;
397
398 return $this->server ?: $wgDBserver;
399 }
400
401 function reportPage() {
402 $this->pageCount++;
403 }
404
405 function revCount() {
406 $this->revCount++;
407 $this->report();
408 }
409
410 function report( $final = false ) {
411 if ( $final xor ( $this->revCount % $this->reportingInterval == 0 ) ) {
412 $this->showReport();
413 }
414 }
415
416 function showReport() {
417 if ( $this->reporting ) {
418 $now = wfTimestamp( TS_DB );
419 $nowts = microtime( true );
420 $deltaAll = $nowts - $this->startTime;
421 $deltaPart = $nowts - $this->lastTime;
422 $this->pageCountPart = $this->pageCount - $this->pageCountLast;
423 $this->revCountPart = $this->revCount - $this->revCountLast;
424
425 if ( $deltaAll ) {
426 $portion = $this->revCount / $this->maxCount;
427 $eta = $this->startTime + $deltaAll / $portion;
428 $etats = wfTimestamp( TS_DB, intval( $eta ) );
429 $pageRate = $this->pageCount / $deltaAll;
430 $revRate = $this->revCount / $deltaAll;
431 } else {
432 $pageRate = '-';
433 $revRate = '-';
434 $etats = '-';
435 }
436 if ( $deltaPart ) {
437 $pageRatePart = $this->pageCountPart / $deltaPart;
438 $revRatePart = $this->revCountPart / $deltaPart;
439 } else {
440 $pageRatePart = '-';
441 $revRatePart = '-';
442 }
443
444 $dbDomain = WikiMap::getCurrentWikiDbDomain()->getId();
445 $this->progress( sprintf(
446 "%s: %s (ID %d) %d pages (%0.1f|%0.1f/sec all|curr), "
447 . "%d revs (%0.1f|%0.1f/sec all|curr), ETA %s [max %d]",
448 $now, $dbDomain, $this->ID, $this->pageCount, $pageRate,
449 $pageRatePart, $this->revCount, $revRate, $revRatePart, $etats,
450 $this->maxCount
451 ) );
452 $this->lastTime = $nowts;
453 $this->revCountLast = $this->revCount;
454 }
455 }
456
457 function progress( $string ) {
458 if ( $this->reporting ) {
459 fwrite( $this->stderr, $string . "\n" );
460 }
461 }
462 }