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