Add MessagesBi.php
[lhc/web/wiklou.git] / maintenance / backup.inc
1 <?php
2 /**
3 * Base classes for database dumpers
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 Maintenance
25 */
26
27 require_once __DIR__ . '/Maintenance.php';
28
29 use MediaWiki\MediaWikiServices;
30 use Wikimedia\Rdbms\LoadBalancer;
31 use Wikimedia\Rdbms\IDatabase;
32
33 /**
34 * @ingroup Dump Maintenance
35 */
36 class BackupDumper extends Maintenance {
37 public $reporting = true;
38 public $pages = null; // all pages
39 public $skipHeader = false; // don't output <mediawiki> and <siteinfo>
40 public $skipFooter = false; // don't output </mediawiki>
41 public $startId = 0;
42 public $endId = 0;
43 public $revStartId = 0;
44 public $revEndId = 0;
45 public $dumpUploads = false;
46 public $dumpUploadFileContents = false;
47 public $orderRevs = false;
48
49 protected $reportingInterval = 100;
50 protected $pageCount = 0;
51 protected $revCount = 0;
52 protected $server = null; // use default
53 protected $sink = null; // Output filters
54 protected $lastTime = 0;
55 protected $pageCountLast = 0;
56 protected $revCountLast = 0;
57
58 protected $outputTypes = [];
59 protected $filterTypes = [];
60
61 protected $ID = 0;
62
63 /**
64 * The dependency-injected database to use.
65 *
66 * @var IDatabase|null
67 *
68 * @see self::setDB
69 */
70 protected $forcedDb = null;
71
72 /** @var LoadBalancer */
73 protected $lb;
74
75 // @todo Unused?
76 private $stubText = false; // include rev_text_id instead of text; for 2-pass dump
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( '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 );
167
168 if ( count( $val ) === 1 ) {
169 $this->loadPlugin( $val[0], '' );
170 } elseif ( count( $val ) === 2 ) {
171 $this->loadPlugin( $val[0], $val[1] );
172 } else {
173 $this->fatalError( 'Invalid plugin parameter' );
174 return;
175 }
176
177 break;
178 case 'output':
179 $split = explode( ':', $param, 2 );
180 if ( count( $split ) !== 2 ) {
181 $this->fatalError( 'Invalid output parameter' );
182 }
183 list( $type, $file ) = $split;
184 if ( !is_null( $sink ) ) {
185 $sinks[] = $sink;
186 }
187 if ( !isset( $this->outputTypes[$type] ) ) {
188 $this->fatalError( "Unrecognized output sink type '$type'" );
189 }
190 $class = $this->outputTypes[$type];
191 if ( $type === "7zip" ) {
192 $sink = new $class( $file, intval( $this->getOption( '7ziplevel' ) ) );
193 } else {
194 $sink = new $class( $file );
195 }
196
197 break;
198 case 'filter':
199 if ( is_null( $sink ) ) {
200 $sink = new DumpOutput();
201 }
202
203 $split = explode( ':', $param );
204 $key = $split[0];
205
206 if ( !isset( $this->filterTypes[$key] ) ) {
207 $this->fatalError( "Unrecognized filter type '$key'" );
208 }
209
210 $type = $this->filterTypes[$key];
211
212 if ( count( $split ) === 1 ) {
213 $filter = new $type( $sink );
214 } elseif ( count( $split ) === 2 ) {
215 $filter = new $type( $sink, $split[1] );
216 } else {
217 $this->fatalError( 'Invalid filter parameter' );
218 }
219
220 // references are lame in php...
221 unset( $sink );
222 $sink = $filter;
223
224 break;
225 }
226 }
227
228 if ( $this->hasOption( 'report' ) ) {
229 $this->reportingInterval = intval( $this->getOption( 'report' ) );
230 }
231
232 if ( $this->hasOption( 'server' ) ) {
233 $this->server = $this->getOption( 'server' );
234 }
235
236 if ( is_null( $sink ) ) {
237 $sink = new DumpOutput();
238 }
239 $sinks[] = $sink;
240
241 if ( count( $sinks ) > 1 ) {
242 $this->sink = new DumpMultiWriter( $sinks );
243 } else {
244 $this->sink = $sink;
245 }
246 }
247
248 function dump( $history, $text = WikiExporter::TEXT ) {
249 # Notice messages will foul up your XML output even if they're
250 # relatively harmless.
251 if ( ini_get( 'display_errors' ) ) {
252 ini_set( 'display_errors', 'stderr' );
253 }
254
255 $this->initProgress( $history );
256
257 $db = $this->backupDb();
258 $exporter = new WikiExporter( $db, $history, WikiExporter::STREAM, $text );
259 $exporter->dumpUploads = $this->dumpUploads;
260 $exporter->dumpUploadFileContents = $this->dumpUploadFileContents;
261
262 $wrapper = new ExportProgressFilter( $this->sink, $this );
263 $exporter->setOutputSink( $wrapper );
264
265 if ( !$this->skipHeader ) {
266 $exporter->openStream();
267 }
268 # Log item dumps: all or by range
269 if ( $history & WikiExporter::LOGS ) {
270 if ( $this->startId || $this->endId ) {
271 $exporter->logsByRange( $this->startId, $this->endId );
272 } else {
273 $exporter->allLogs();
274 }
275 } elseif ( is_null( $this->pages ) ) {
276 # Page dumps: all or by page ID range
277 if ( $this->startId || $this->endId ) {
278 $exporter->pagesByRange( $this->startId, $this->endId, $this->orderRevs );
279 } elseif ( $this->revStartId || $this->revEndId ) {
280 $exporter->revsByRange( $this->revStartId, $this->revEndId );
281 } else {
282 $exporter->allPages();
283 }
284 } else {
285 # Dump of specific pages
286 $exporter->pagesByName( $this->pages );
287 }
288
289 if ( !$this->skipFooter ) {
290 $exporter->closeStream();
291 }
292
293 $this->report( true );
294 }
295
296 /**
297 * Initialise starting time and maximum revision count.
298 * We'll make ETA calculations based an progress, assuming relatively
299 * constant per-revision rate.
300 * @param int $history WikiExporter::CURRENT or WikiExporter::FULL
301 */
302 function initProgress( $history = WikiExporter::FULL ) {
303 $table = ( $history == WikiExporter::CURRENT ) ? 'page' : 'revision';
304 $field = ( $history == WikiExporter::CURRENT ) ? 'page_id' : 'rev_id';
305
306 $dbr = $this->forcedDb;
307 if ( $this->forcedDb === null ) {
308 $dbr = wfGetDB( DB_REPLICA );
309 }
310 $this->maxCount = $dbr->selectField( $table, "MAX($field)", '', __METHOD__ );
311 $this->startTime = microtime( true );
312 $this->lastTime = $this->startTime;
313 $this->ID = getmypid();
314 }
315
316 /**
317 * @todo Fixme: the --server parameter is currently not respected, as it
318 * doesn't seem terribly easy to ask the load balancer for a particular
319 * connection by name.
320 * @return IDatabase
321 */
322 function backupDb() {
323 if ( $this->forcedDb !== null ) {
324 return $this->forcedDb;
325 }
326
327 $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
328 $this->lb = $lbFactory->newMainLB();
329 $db = $this->lb->getConnection( DB_REPLICA, 'dump' );
330
331 // Discourage the server from disconnecting us if it takes a long time
332 // to read out the big ol' batch query.
333 $db->setSessionOptions( [ 'connTimeout' => 3600 * 24 ] );
334
335 return $db;
336 }
337
338 /**
339 * Force the dump to use the provided database connection for database
340 * operations, wherever possible.
341 *
342 * @param IDatabase|null $db (Optional) the database connection to use. If null, resort to
343 * use the globally provided ways to get database connections.
344 */
345 function setDB( IDatabase $db = null ) {
346 parent::setDB( $db );
347 $this->forcedDb = $db;
348 }
349
350 function __destruct() {
351 if ( isset( $this->lb ) ) {
352 $this->lb->closeAll();
353 }
354 }
355
356 function backupServer() {
357 global $wgDBserver;
358
359 return $this->server
360 ? $this->server
361 : $wgDBserver;
362 }
363
364 function reportPage() {
365 $this->pageCount++;
366 }
367
368 function revCount() {
369 $this->revCount++;
370 $this->report();
371 }
372
373 function report( $final = false ) {
374 if ( $final xor ( $this->revCount % $this->reportingInterval == 0 ) ) {
375 $this->showReport();
376 }
377 }
378
379 function showReport() {
380 if ( $this->reporting ) {
381 $now = wfTimestamp( TS_DB );
382 $nowts = microtime( true );
383 $deltaAll = $nowts - $this->startTime;
384 $deltaPart = $nowts - $this->lastTime;
385 $this->pageCountPart = $this->pageCount - $this->pageCountLast;
386 $this->revCountPart = $this->revCount - $this->revCountLast;
387
388 if ( $deltaAll ) {
389 $portion = $this->revCount / $this->maxCount;
390 $eta = $this->startTime + $deltaAll / $portion;
391 $etats = wfTimestamp( TS_DB, intval( $eta ) );
392 $pageRate = $this->pageCount / $deltaAll;
393 $revRate = $this->revCount / $deltaAll;
394 } else {
395 $pageRate = '-';
396 $revRate = '-';
397 $etats = '-';
398 }
399 if ( $deltaPart ) {
400 $pageRatePart = $this->pageCountPart / $deltaPart;
401 $revRatePart = $this->revCountPart / $deltaPart;
402 } else {
403 $pageRatePart = '-';
404 $revRatePart = '-';
405 }
406 $this->progress( sprintf(
407 "%s: %s (ID %d) %d pages (%0.1f|%0.1f/sec all|curr), "
408 . "%d revs (%0.1f|%0.1f/sec all|curr), ETA %s [max %d]",
409 $now, wfWikiID(), $this->ID, $this->pageCount, $pageRate,
410 $pageRatePart, $this->revCount, $revRate, $revRatePart, $etats,
411 $this->maxCount
412 ) );
413 $this->lastTime = $nowts;
414 $this->revCountLast = $this->revCount;
415 }
416 }
417
418 function progress( $string ) {
419 if ( $this->reporting ) {
420 fwrite( $this->stderr, $string . "\n" );
421 }
422 }
423 }