Add dynomite comments to WANObjectCache
[mediawiki.git] / maintenance / backup.inc
blob286fb58fb641c3b192cad5cdff09bea311e3922c
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  */
27 require_once __DIR__ . '/Maintenance.php';
28 require_once __DIR__ . '/../includes/export/DumpFilter.php';
30 use Wikimedia\Rdbms\LoadBalancer;
32 /**
33  * @ingroup Dump Maintenance
34  */
35 class BackupDumper extends Maintenance {
36         public $reporting = true;
37         public $pages = null; // all pages
38         public $skipHeader = false; // don't output <mediawiki> and <siteinfo>
39         public $skipFooter = false; // don't output </mediawiki>
40         public $startId = 0;
41         public $endId = 0;
42         public $revStartId = 0;
43         public $revEndId = 0;
44         public $dumpUploads = false;
45         public $dumpUploadFileContents = false;
46         public $orderRevs = false;
48         protected $reportingInterval = 100;
49         protected $pageCount = 0;
50         protected $revCount = 0;
51         protected $server = null; // use default
52         protected $sink = null; // Output filters
53         protected $lastTime = 0;
54         protected $pageCountLast = 0;
55         protected $revCountLast = 0;
57         protected $outputTypes = [];
58         protected $filterTypes = [];
60         protected $ID = 0;
62         /**
63          * The dependency-injected database to use.
64          *
65          * @var IDatabase|null
66          *
67          * @see self::setDB
68          */
69         protected $forcedDb = null;
71         /** @var LoadBalancer */
72         protected $lb;
74         // @todo Unused?
75         private $stubText = false; // include rev_text_id instead of text; for 2-pass dump
77         /**
78          * @param array $args For backward compatibility
79          */
80         function __construct( $args = null ) {
81                 parent::__construct();
82                 $this->stderr = fopen( "php://stderr", "wt" );
84                 // Built-in output and filter plugins
85                 $this->registerOutput( 'file', 'DumpFileOutput' );
86                 $this->registerOutput( 'gzip', 'DumpGZipOutput' );
87                 $this->registerOutput( 'bzip2', 'DumpBZip2Output' );
88                 $this->registerOutput( 'dbzip2', 'DumpDBZip2Output' );
89                 $this->registerOutput( '7zip', 'Dump7ZipOutput' );
91                 $this->registerFilter( 'latest', 'DumpLatestFilter' );
92                 $this->registerFilter( 'notalk', 'DumpNotalkFilter' );
93                 $this->registerFilter( 'namespace', 'DumpNamespaceFilter' );
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 );
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         }
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         }
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         }
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                 call_user_func_array( $register, [ $this ] );
145         }
147         function execute() {
148                 throw new MWException( 'execute() must be overridden in subclasses' );
149         }
151         /**
152          * Processes arguments and sets $this->$sink accordingly
153          */
154         function processOptions() {
155                 $sink = null;
156                 $sinks = [];
158                 $options = $this->orderedOptions;
159                 foreach ( $options as $arg ) {
160                         $opt = $arg[0];
161                         $param = $arg[1];
163                         switch ( $opt ) {
164                                 case 'plugin':
165                                         $val = explode( ':', $param );
167                                         if ( count( $val ) === 1 ) {
168                                                 $this->loadPlugin( $val[0], '' );
169                                         } elseif ( count( $val ) === 2 ) {
170                                                 $this->loadPlugin( $val[0], $val[1] );
171                                         } else {
172                                                 $this->fatalError( 'Invalid plugin parameter' );
173                                                 return;
174                                         }
176                                         break;
177                                 case 'output':
178                                         $split = explode( ':', $param, 2 );
179                                         if ( count( $split ) !== 2 ) {
180                                                 $this->fatalError( 'Invalid output parameter' );
181                                         }
182                                         list( $type, $file ) = $split;
183                                         if ( !is_null( $sink ) ) {
184                                                 $sinks[] = $sink;
185                                         }
186                                         if ( !isset( $this->outputTypes[$type] ) ) {
187                                                 $this->fatalError( "Unrecognized output sink type '$type'" );
188                                         }
189                                         $class = $this->outputTypes[$type];
190                                         if ( $type === "7zip" ) {
191                                                 $sink = new $class( $file, intval( $this->getOption( '7ziplevel' ) ) );
192                                         } else {
193                                                 $sink = new $class( $file );
194                                         }
196                                         break;
197                                 case 'filter':
198                                         if ( is_null( $sink ) ) {
199                                                 $sink = new DumpOutput();
200                                         }
202                                         $split = explode( ':', $param );
203                                         $key = $split[0];
205                                         if ( !isset( $this->filterTypes[$key] ) ) {
206                                                 $this->fatalError( "Unrecognized filter type '$key'" );
207                                         }
209                                         $type = $this->filterTypes[$key];
211                                         if ( count( $split ) === 1 ) {
212                                                 $filter = new $type( $sink );
213                                         } elseif ( count( $split ) === 2 ) {
214                                                 $filter = new $type( $sink, $split[1] );
215                                         } else {
216                                                 $this->fatalError( 'Invalid filter parameter' );
217                                         }
219                                         // references are lame in php...
220                                         unset( $sink );
221                                         $sink = $filter;
223                                         break;
224                         }
225                 }
227                 if ( $this->hasOption( 'report' ) ) {
228                         $this->reportingInterval = intval( $this->getOption( 'report' ) );
229                 }
231                 if ( $this->hasOption( 'server' ) ) {
232                         $this->server = $this->getOption( 'server' );
233                 }
235                 if ( is_null( $sink ) ) {
236                         $sink = new DumpOutput();
237                 }
238                 $sinks[] = $sink;
240                 if ( count( $sinks ) > 1 ) {
241                         $this->sink = new DumpMultiWriter( $sinks );
242                 } else {
243                         $this->sink = $sink;
244                 }
245         }
247         function dump( $history, $text = WikiExporter::TEXT ) {
248                 # Notice messages will foul up your XML output even if they're
249                 # relatively harmless.
250                 if ( ini_get( 'display_errors' ) ) {
251                         ini_set( 'display_errors', 'stderr' );
252                 }
254                 $this->initProgress( $history );
256                 $db = $this->backupDb();
257                 $exporter = new WikiExporter( $db, $history, WikiExporter::STREAM, $text );
258                 $exporter->dumpUploads = $this->dumpUploads;
259                 $exporter->dumpUploadFileContents = $this->dumpUploadFileContents;
261                 $wrapper = new ExportProgressFilter( $this->sink, $this );
262                 $exporter->setOutputSink( $wrapper );
264                 if ( !$this->skipHeader ) {
265                         $exporter->openStream();
266                 }
267                 # Log item dumps: all or by range
268                 if ( $history & WikiExporter::LOGS ) {
269                         if ( $this->startId || $this->endId ) {
270                                 $exporter->logsByRange( $this->startId, $this->endId );
271                         } else {
272                                 $exporter->allLogs();
273                         }
274                 } elseif ( is_null( $this->pages ) ) {
275                         # Page dumps: all or by page ID range
276                         if ( $this->startId || $this->endId ) {
277                                 $exporter->pagesByRange( $this->startId, $this->endId, $this->orderRevs );
278                         } elseif ( $this->revStartId || $this->revEndId ) {
279                                 $exporter->revsByRange( $this->revStartId, $this->revEndId );
280                         } else {
281                                 $exporter->allPages();
282                         }
283                 } else {
284                         # Dump of specific pages
285                         $exporter->pagesByName( $this->pages );
286                 }
288                 if ( !$this->skipFooter ) {
289                         $exporter->closeStream();
290                 }
292                 $this->report( true );
293         }
295         /**
296          * Initialise starting time and maximum revision count.
297          * We'll make ETA calculations based an progress, assuming relatively
298          * constant per-revision rate.
299          * @param int $history WikiExporter::CURRENT or WikiExporter::FULL
300          */
301         function initProgress( $history = WikiExporter::FULL ) {
302                 $table = ( $history == WikiExporter::CURRENT ) ? 'page' : 'revision';
303                 $field = ( $history == WikiExporter::CURRENT ) ? 'page_id' : 'rev_id';
305                 $dbr = $this->forcedDb;
306                 if ( $this->forcedDb === null ) {
307                         $dbr = wfGetDB( DB_REPLICA );
308                 }
309                 $this->maxCount = $dbr->selectField( $table, "MAX($field)", '', __METHOD__ );
310                 $this->startTime = microtime( true );
311                 $this->lastTime = $this->startTime;
312                 $this->ID = getmypid();
313         }
315         /**
316          * @todo Fixme: the --server parameter is currently not respected, as it
317          * doesn't seem terribly easy to ask the load balancer for a particular
318          * connection by name.
319          * @return IDatabase
320          */
321         function backupDb() {
322                 if ( $this->forcedDb !== null ) {
323                         return $this->forcedDb;
324                 }
326                 $this->lb = wfGetLBFactory()->newMainLB();
327                 $db = $this->lb->getConnection( DB_REPLICA, 'dump' );
329                 // Discourage the server from disconnecting us if it takes a long time
330                 // to read out the big ol' batch query.
331                 $db->setSessionOptions( [ 'connTimeout' => 3600 * 24 ] );
333                 return $db;
334         }
336         /**
337          * Force the dump to use the provided database connection for database
338          * operations, wherever possible.
339          *
340          * @param IDatabase|null $db (Optional) the database connection to use. If null, resort to
341          *   use the globally provided ways to get database connections.
342          */
343         function setDB( IDatabase $db = null ) {
344                 parent::setDB( $db );
345                 $this->forcedDb = $db;
346         }
348         function __destruct() {
349                 if ( isset( $this->lb ) ) {
350                         $this->lb->closeAll();
351                 }
352         }
354         function backupServer() {
355                 global $wgDBserver;
357                 return $this->server
358                         ? $this->server
359                         : $wgDBserver;
360         }
362         function reportPage() {
363                 $this->pageCount++;
364         }
366         function revCount() {
367                 $this->revCount++;
368                 $this->report();
369         }
371         function report( $final = false ) {
372                 if ( $final xor ( $this->revCount % $this->reportingInterval == 0 ) ) {
373                         $this->showReport();
374                 }
375         }
377         function showReport() {
378                 if ( $this->reporting ) {
379                         $now = wfTimestamp( TS_DB );
380                         $nowts = microtime( true );
381                         $deltaAll = $nowts - $this->startTime;
382                         $deltaPart = $nowts - $this->lastTime;
383                         $this->pageCountPart = $this->pageCount - $this->pageCountLast;
384                         $this->revCountPart = $this->revCount - $this->revCountLast;
386                         if ( $deltaAll ) {
387                                 $portion = $this->revCount / $this->maxCount;
388                                 $eta = $this->startTime + $deltaAll / $portion;
389                                 $etats = wfTimestamp( TS_DB, intval( $eta ) );
390                                 $pageRate = $this->pageCount / $deltaAll;
391                                 $revRate = $this->revCount / $deltaAll;
392                         } else {
393                                 $pageRate = '-';
394                                 $revRate = '-';
395                                 $etats = '-';
396                         }
397                         if ( $deltaPart ) {
398                                 $pageRatePart = $this->pageCountPart / $deltaPart;
399                                 $revRatePart = $this->revCountPart / $deltaPart;
400                         } else {
401                                 $pageRatePart = '-';
402                                 $revRatePart = '-';
403                         }
404                         $this->progress( sprintf(
405                                 "%s: %s (ID %d) %d pages (%0.1f|%0.1f/sec all|curr), "
406                                         . "%d revs (%0.1f|%0.1f/sec all|curr), ETA %s [max %d]",
407                                 $now, wfWikiID(), $this->ID, $this->pageCount, $pageRate,
408                                 $pageRatePart, $this->revCount, $revRate, $revRatePart, $etats,
409                                 $this->maxCount
410                         ) );
411                         $this->lastTime = $nowts;
412                         $this->revCountLast = $this->revCount;
413                 }
414         }
416         function progress( $string ) {
417                 if ( $this->reporting ) {
418                         fwrite( $this->stderr, $string . "\n" );
419                 }
420         }
422         function fatalError( $msg ) {
423                 $this->error( "$msg\n", 1 );
424         }
427 class ExportProgressFilter extends DumpFilter {
428         function __construct( &$sink, &$progress ) {
429                 parent::__construct( $sink );
430                 $this->progress = $progress;
431         }
433         function writeClosePage( $string ) {
434                 parent::writeClosePage( $string );
435                 $this->progress->reportPage();
436         }
438         function writeRevision( $rev, $string ) {
439                 parent::writeRevision( $rev, $string );
440                 $this->progress->revCount();
441         }