Merge "Title: Test the ->equals() method more thoughroughly"
[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
30 use MediaWiki\MediaWikiServices;
31 use Wikimedia\Rdbms\LoadBalancer;
32 use Wikimedia\Rdbms\IDatabase;
33
34 /**
35 * @ingroup Dump
36 * @ingroup Maintenance
37 */
38 abstract class BackupDumper extends Maintenance {
39 public $reporting = true;
40 public $pages = null; // all pages
41 public $skipHeader = false; // don't output <mediawiki> and <siteinfo>
42 public $skipFooter = false; // don't output </mediawiki>
43 public $startId = 0;
44 public $endId = 0;
45 public $revStartId = 0;
46 public $revEndId = 0;
47 public $dumpUploads = false;
48 public $dumpUploadFileContents = false;
49 public $orderRevs = false;
50
51 protected $reportingInterval = 100;
52 protected $pageCount = 0;
53 protected $revCount = 0;
54 protected $schemaVersion = null; // use default
55 protected $server = null; // use default
56 protected $sink = null; // Output filters
57 protected $lastTime = 0;
58 protected $pageCountLast = 0;
59 protected $revCountLast = 0;
60
61 protected $outputTypes = [];
62 protected $filterTypes = [];
63
64 protected $ID = 0;
65
66 /**
67 * The dependency-injected database to use.
68 *
69 * @var IDatabase|null
70 *
71 * @see self::setDB
72 */
73 protected $forcedDb = null;
74
75 /** @var LoadBalancer */
76 protected $lb;
77
78 /**
79 * @param array|null $args For backward compatibility
80 */
81 function __construct( $args = null ) {
82 parent::__construct();
83 $this->stderr = fopen( "php://stderr", "wt" );
84
85 // Built-in output and filter plugins
86 $this->registerOutput( 'file', DumpFileOutput::class );
87 $this->registerOutput( 'gzip', DumpGZipOutput::class );
88 $this->registerOutput( 'bzip2', DumpBZip2Output::class );
89 $this->registerOutput( 'dbzip2', DumpDBZip2Output::class );
90 $this->registerOutput( '7zip', Dump7ZipOutput::class );
91
92 $this->registerFilter( 'latest', DumpLatestFilter::class );
93 $this->registerFilter( 'notalk', DumpNotalkFilter::class );
94 $this->registerFilter( 'namespace', DumpNamespaceFilter::class );
95
96 // These three can be specified multiple times
97 $this->addOption( 'plugin', 'Load a dump plugin class. Specify as <class>[:<file>].',
98 false, true, false, true );
99 $this->addOption( 'output', 'Begin a filtered output stream; Specify as <type>:<file>. ' .
100 '<type>s: file, gzip, bzip2, 7zip, dbzip2', false, true, false, true );
101 $this->addOption( 'filter', 'Add a filter on an output branch. Specify as ' .
102 '<type>[:<options>]. <types>s: latest, notalk, namespace', false, true, false, true );
103 $this->addOption( 'report', 'Report position and speed after every n pages processed. ' .
104 'Default: 100.', false, true );
105 $this->addOption( 'schema-version', 'Schema version to use for output. ' .
106 'Default: ' . WikiExporter::schemaVersion(), false, true );
107 $this->addOption( 'server', 'Force reading from MySQL server', false, true );
108 $this->addOption( '7ziplevel', '7zip compression level for all 7zip outputs. Used for ' .
109 '-mx option to 7za command.', false, true );
110
111 if ( $args ) {
112 // Args should be loaded and processed so that dump() can be called directly
113 // instead of execute()
114 $this->loadWithArgv( $args );
115 $this->processOptions();
116 }
117 }
118
119 /**
120 * @param string $name
121 * @param string $class Name of output filter plugin class
122 */
123 function registerOutput( $name, $class ) {
124 $this->outputTypes[$name] = $class;
125 }
126
127 /**
128 * @param string $name
129 * @param string $class Name of filter plugin class
130 */
131 function registerFilter( $name, $class ) {
132 $this->filterTypes[$name] = $class;
133 }
134
135 /**
136 * Load a plugin and register it
137 *
138 * @param string $class Name of plugin class; must have a static 'register'
139 * method that takes a BackupDumper as a parameter.
140 * @param string $file Full or relative path to the PHP file to load, or empty
141 */
142 function loadPlugin( $class, $file ) {
143 if ( $file != '' ) {
144 require_once $file;
145 }
146 $register = [ $class, 'register' ];
147 $register( $this );
148 }
149
150 function execute() {
151 throw new MWException( 'execute() must be overridden in subclasses' );
152 }
153
154 /**
155 * Processes arguments and sets $this->$sink accordingly
156 */
157 function processOptions() {
158 $sink = null;
159 $sinks = [];
160
161 $this->schemaVersion = WikiExporter::schemaVersion();
162
163 $options = $this->orderedOptions;
164 foreach ( $options as $arg ) {
165 $opt = $arg[0];
166 $param = $arg[1];
167
168 switch ( $opt ) {
169 case 'plugin':
170 $val = explode( ':', $param, 2 );
171
172 if ( count( $val ) === 1 ) {
173 $this->loadPlugin( $val[0], '' );
174 } elseif ( count( $val ) === 2 ) {
175 $this->loadPlugin( $val[0], $val[1] );
176 }
177
178 break;
179 case 'output':
180 $split = explode( ':', $param, 2 );
181 if ( count( $split ) !== 2 ) {
182 $this->fatalError( 'Invalid output parameter' );
183 }
184 list( $type, $file ) = $split;
185 if ( !is_null( $sink ) ) {
186 $sinks[] = $sink;
187 }
188 if ( !isset( $this->outputTypes[$type] ) ) {
189 $this->fatalError( "Unrecognized output sink type '$type'" );
190 }
191 $class = $this->outputTypes[$type];
192 if ( $type === "7zip" ) {
193 $sink = new $class( $file, intval( $this->getOption( '7ziplevel' ) ) );
194 } else {
195 $sink = new $class( $file );
196 }
197
198 break;
199 case 'filter':
200 if ( is_null( $sink ) ) {
201 $sink = new DumpOutput();
202 }
203
204 $split = explode( ':', $param, 2 );
205 $key = $split[0];
206
207 if ( !isset( $this->filterTypes[$key] ) ) {
208 $this->fatalError( "Unrecognized filter type '$key'" );
209 }
210
211 $type = $this->filterTypes[$key];
212
213 if ( count( $split ) === 1 ) {
214 $filter = new $type( $sink );
215 } elseif ( count( $split ) === 2 ) {
216 $filter = new $type( $sink, $split[1] );
217 }
218
219 // references are lame in php...
220 unset( $sink );
221 $sink = $filter;
222
223 break;
224 case 'schema-version':
225 if ( !in_array( $param, XmlDumpWriter::$supportedSchemas ) ) {
226 $this->fatalError(
227 "Unsupported schema version $param. Supported versions: " .
228 implode( ', ', XmlDumpWriter::$supportedSchemas )
229 );
230 }
231 $this->schemaVersion = $param;
232 break;
233 }
234 }
235
236 if ( $this->hasOption( 'report' ) ) {
237 $this->reportingInterval = intval( $this->getOption( 'report' ) );
238 }
239
240 if ( $this->hasOption( 'server' ) ) {
241 $this->server = $this->getOption( 'server' );
242 }
243
244 if ( is_null( $sink ) ) {
245 $sink = new DumpOutput();
246 }
247 $sinks[] = $sink;
248
249 if ( count( $sinks ) > 1 ) {
250 $this->sink = new DumpMultiWriter( $sinks );
251 } else {
252 $this->sink = $sink;
253 }
254 }
255
256 function dump( $history, $text = WikiExporter::TEXT ) {
257 # Notice messages will foul up your XML output even if they're
258 # relatively harmless.
259 if ( ini_get( 'display_errors' ) ) {
260 ini_set( 'display_errors', 'stderr' );
261 }
262
263 $this->initProgress( $history );
264
265 $db = $this->backupDb();
266 $exporter = new WikiExporter( $db, $history, $text );
267 $exporter->setSchemaVersion( $this->schemaVersion );
268 $exporter->dumpUploads = $this->dumpUploads;
269 $exporter->dumpUploadFileContents = $this->dumpUploadFileContents;
270
271 $wrapper = new ExportProgressFilter( $this->sink, $this );
272 $exporter->setOutputSink( $wrapper );
273
274 if ( !$this->skipHeader ) {
275 $exporter->openStream();
276 }
277 # Log item dumps: all or by range
278 if ( $history & WikiExporter::LOGS ) {
279 if ( $this->startId || $this->endId ) {
280 $exporter->logsByRange( $this->startId, $this->endId );
281 } else {
282 $exporter->allLogs();
283 }
284 } elseif ( is_null( $this->pages ) ) {
285 # Page dumps: all or by page ID range
286 if ( $this->startId || $this->endId ) {
287 $exporter->pagesByRange( $this->startId, $this->endId, $this->orderRevs );
288 } elseif ( $this->revStartId || $this->revEndId ) {
289 $exporter->revsByRange( $this->revStartId, $this->revEndId );
290 } else {
291 $exporter->allPages();
292 }
293 } else {
294 # Dump of specific pages
295 $exporter->pagesByName( $this->pages );
296 }
297
298 if ( !$this->skipFooter ) {
299 $exporter->closeStream();
300 }
301
302 $this->report( true );
303 }
304
305 /**
306 * Initialise starting time and maximum revision count.
307 * We'll make ETA calculations based an progress, assuming relatively
308 * constant per-revision rate.
309 * @param int $history WikiExporter::CURRENT or WikiExporter::FULL
310 */
311 function initProgress( $history = WikiExporter::FULL ) {
312 $table = ( $history == WikiExporter::CURRENT ) ? 'page' : 'revision';
313 $field = ( $history == WikiExporter::CURRENT ) ? 'page_id' : 'rev_id';
314
315 $dbr = $this->forcedDb;
316 if ( $this->forcedDb === null ) {
317 $dbr = wfGetDB( DB_REPLICA );
318 }
319 $this->maxCount = $dbr->selectField( $table, "MAX($field)", '', __METHOD__ );
320 $this->startTime = microtime( true );
321 $this->lastTime = $this->startTime;
322 $this->ID = getmypid();
323 }
324
325 /**
326 * @todo Fixme: the --server parameter is currently not respected, as it
327 * doesn't seem terribly easy to ask the load balancer for a particular
328 * connection by name.
329 * @return IDatabase
330 */
331 function backupDb() {
332 if ( $this->forcedDb !== null ) {
333 return $this->forcedDb;
334 }
335
336 $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
337 $this->lb = $lbFactory->newMainLB();
338 $db = $this->lb->getConnection( DB_REPLICA, 'dump' );
339
340 // Discourage the server from disconnecting us if it takes a long time
341 // to read out the big ol' batch query.
342 $db->setSessionOptions( [ 'connTimeout' => 3600 * 24 ] );
343
344 return $db;
345 }
346
347 /**
348 * Force the dump to use the provided database connection for database
349 * operations, wherever possible.
350 *
351 * @param IDatabase|null $db (Optional) the database connection to use. If null, resort to
352 * use the globally provided ways to get database connections.
353 */
354 function setDB( IDatabase $db = null ) {
355 parent::setDB( $db );
356 $this->forcedDb = $db;
357 }
358
359 function __destruct() {
360 if ( isset( $this->lb ) ) {
361 $this->lb->closeAll();
362 }
363 }
364
365 function backupServer() {
366 global $wgDBserver;
367
368 return $this->server ?: $wgDBserver;
369 }
370
371 function reportPage() {
372 $this->pageCount++;
373 }
374
375 function revCount() {
376 $this->revCount++;
377 $this->report();
378 }
379
380 function report( $final = false ) {
381 if ( $final xor ( $this->revCount % $this->reportingInterval == 0 ) ) {
382 $this->showReport();
383 }
384 }
385
386 function showReport() {
387 if ( $this->reporting ) {
388 $now = wfTimestamp( TS_DB );
389 $nowts = microtime( true );
390 $deltaAll = $nowts - $this->startTime;
391 $deltaPart = $nowts - $this->lastTime;
392 $this->pageCountPart = $this->pageCount - $this->pageCountLast;
393 $this->revCountPart = $this->revCount - $this->revCountLast;
394
395 if ( $deltaAll ) {
396 $portion = $this->revCount / $this->maxCount;
397 $eta = $this->startTime + $deltaAll / $portion;
398 $etats = wfTimestamp( TS_DB, intval( $eta ) );
399 $pageRate = $this->pageCount / $deltaAll;
400 $revRate = $this->revCount / $deltaAll;
401 } else {
402 $pageRate = '-';
403 $revRate = '-';
404 $etats = '-';
405 }
406 if ( $deltaPart ) {
407 $pageRatePart = $this->pageCountPart / $deltaPart;
408 $revRatePart = $this->revCountPart / $deltaPart;
409 } else {
410 $pageRatePart = '-';
411 $revRatePart = '-';
412 }
413 $this->progress( sprintf(
414 "%s: %s (ID %d) %d pages (%0.1f|%0.1f/sec all|curr), "
415 . "%d revs (%0.1f|%0.1f/sec all|curr), ETA %s [max %d]",
416 $now, wfWikiID(), $this->ID, $this->pageCount, $pageRate,
417 $pageRatePart, $this->revCount, $revRate, $revRatePart, $etats,
418 $this->maxCount
419 ) );
420 $this->lastTime = $nowts;
421 $this->revCountLast = $this->revCount;
422 }
423 }
424
425 function progress( $string ) {
426 if ( $this->reporting ) {
427 fwrite( $this->stderr, $string . "\n" );
428 }
429 }
430 }