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