Merge "Remove 3 unused upload related error messages"
[mediawiki.git] / maintenance / backup.inc
blob323a870e6847962d48339de0881deebd1eade33c
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 /**
28  * @ingroup Dump Maintenance
29  */
30 class DumpDBZip2Output extends DumpPipeOutput {
31         function __construct( $file ) {
32                 parent::__construct( "dbzip2", $file );
33         }
36 /**
37  * @ingroup Dump Maintenance
38  */
39 class BackupDumper {
40         var $reportingInterval = 100;
41         var $reporting = true;
42         var $pageCount = 0;
43         var $revCount = 0;
44         var $server = null; // use default
45         var $pages = null; // all pages
46         var $skipHeader = false; // don't output <mediawiki> and <siteinfo>
47         var $skipFooter = false; // don't output </mediawiki>
48         var $startId = 0;
49         var $endId = 0;
50         var $revStartId = 0;
51         var $revEndId = 0;
52         var $sink = null; // Output filters
53         var $stubText = false; // include rev_text_id instead of text; for 2-pass dump
54         var $dumpUploads = false;
55         var $dumpUploadFileContents = false;
56         var $lastTime = 0;
57         var $pageCountLast = 0;
58         var $revCountLast = 0;
59         var $ID = 0;
61         var $outputTypes = array(), $filterTypes = array();
63         /**
64          * The dependency-injected database to use.
65          *
66          * @var DatabaseBase|null
67          *
68          * @see self::setDb
69          */
70         protected $forcedDb = null;
72         /**
73          * @var LoadBalancer
74          */
75         protected $lb;
77         function __construct( $args ) {
78                 $this->stderr = fopen( "php://stderr", "wt" );
80                 // Built-in output and filter plugins
81                 $this->registerOutput( 'file', 'DumpFileOutput' );
82                 $this->registerOutput( 'gzip', 'DumpGZipOutput' );
83                 $this->registerOutput( 'bzip2', 'DumpBZip2Output' );
84                 $this->registerOutput( 'dbzip2', 'DumpDBZip2Output' );
85                 $this->registerOutput( '7zip', 'Dump7ZipOutput' );
87                 $this->registerFilter( 'latest', 'DumpLatestFilter' );
88                 $this->registerFilter( 'notalk', 'DumpNotalkFilter' );
89                 $this->registerFilter( 'namespace', 'DumpNamespaceFilter' );
91                 $this->sink = $this->processArgs( $args );
92         }
94         /**
95          * @param string $name
96          * @param string $class Name of output filter plugin class
97          */
98         function registerOutput( $name, $class ) {
99                 $this->outputTypes[$name] = $class;
100         }
102         /**
103          * @param string $name
104          * @param string $class Name of filter plugin class
105          */
106         function registerFilter( $name, $class ) {
107                 $this->filterTypes[$name] = $class;
108         }
110         /**
111          * Load a plugin and register it
112          *
113          * @param string $class Name of plugin class; must have a static 'register'
114          *   method that takes a BackupDumper as a parameter.
115          * @param string $file Full or relative path to the PHP file to load, or empty
116          */
117         function loadPlugin( $class, $file ) {
118                 if ( $file != '' ) {
119                         require_once $file;
120                 }
121                 $register = array( $class, 'register' );
122                 call_user_func_array( $register, array( &$this ) );
123         }
125         /**
126          * @param array $args
127          * @return array
128          */
129         function processArgs( $args ) {
130                 $sink = null;
131                 $sinks = array();
132                 foreach ( $args as $arg ) {
133                         $matches = array();
134                         if ( preg_match( '/^--(.+?)(?:=(.+?)(?::(.+?))?)?$/', $arg, $matches ) ) {
135                                 @list( /* $full */ , $opt, $val, $param ) = $matches;
136                                 switch ( $opt ) {
137                                 case "plugin":
138                                         $this->loadPlugin( $val, $param );
139                                         break;
140                                 case "output":
141                                         if ( !is_null( $sink ) ) {
142                                                 $sinks[] = $sink;
143                                         }
144                                         if ( !isset( $this->outputTypes[$val] ) ) {
145                                                 $this->fatalError( "Unrecognized output sink type '$val'" );
146                                         }
147                                         $type = $this->outputTypes[$val];
148                                         $sink = new $type( $param );
149                                         break;
150                                 case "filter":
151                                         if ( is_null( $sink ) ) {
152                                                 $sink = new DumpOutput();
153                                         }
154                                         if ( !isset( $this->filterTypes[$val] ) ) {
155                                                 $this->fatalError( "Unrecognized filter type '$val'" );
156                                         }
157                                         $type = $this->filterTypes[$val];
158                                         $filter = new $type( $sink, $param );
160                                         // references are lame in php...
161                                         unset( $sink );
162                                         $sink = $filter;
164                                         break;
165                                 case "report":
166                                         $this->reportingInterval = intval( $val );
167                                         break;
168                                 case "server":
169                                         $this->server = $val;
170                                         break;
171                                 case "force-normal":
172                                         if ( !function_exists( 'utf8_normalize' ) ) {
173                                                 $this->fatalError( "UTF-8 normalization extension not loaded. " .
174                                                         "Install or remove --force-normal parameter to use slower code." );
175                                         }
176                                         break;
177                                 default:
178                                         $this->processOption( $opt, $val, $param );
179                                 }
180                         }
181                 }
183                 if ( is_null( $sink ) ) {
184                         $sink = new DumpOutput();
185                 }
186                 $sinks[] = $sink;
188                 if ( count( $sinks ) > 1 ) {
189                         return new DumpMultiWriter( $sinks );
190                 } else {
191                         return $sink;
192                 }
193         }
195         function processOption( $opt, $val, $param ) {
196                 // extension point for subclasses to add options
197         }
199         function dump( $history, $text = WikiExporter::TEXT ) {
200                 # Notice messages will foul up your XML output even if they're
201                 # relatively harmless.
202                 if ( ini_get( 'display_errors' ) ) {
203                         ini_set( 'display_errors', 'stderr' );
204                 }
206                 $this->initProgress( $history );
208                 $db = $this->backupDb();
209                 $exporter = new WikiExporter( $db, $history, WikiExporter::STREAM, $text );
210                 $exporter->dumpUploads = $this->dumpUploads;
211                 $exporter->dumpUploadFileContents = $this->dumpUploadFileContents;
213                 $wrapper = new ExportProgressFilter( $this->sink, $this );
214                 $exporter->setOutputSink( $wrapper );
216                 if ( !$this->skipHeader ) {
217                         $exporter->openStream();
218                 }
219                 # Log item dumps: all or by range
220                 if ( $history & WikiExporter::LOGS ) {
221                         if ( $this->startId || $this->endId ) {
222                                 $exporter->logsByRange( $this->startId, $this->endId );
223                         } else {
224                                 $exporter->allLogs();
225                         }
226                 # Page dumps: all or by page ID range
227                 } elseif ( is_null( $this->pages ) ) {
228                         if ( $this->startId || $this->endId ) {
229                                 $exporter->pagesByRange( $this->startId, $this->endId );
230                         } elseif ( $this->revStartId || $this->revEndId ) {
231                                 $exporter->revsByRange( $this->revStartId, $this->revEndId );
232                         } else {
233                                 $exporter->allPages();
234                         }
235                 # Dump of specific pages
236                 } else {
237                         $exporter->pagesByName( $this->pages );
238                 }
240                 if ( !$this->skipFooter ) {
241                         $exporter->closeStream();
242                 }
244                 $this->report( true );
245         }
247         /**
248          * Initialise starting time and maximum revision count.
249          * We'll make ETA calculations based an progress, assuming relatively
250          * constant per-revision rate.
251          * @param int $history WikiExporter::CURRENT or WikiExporter::FULL
252          */
253         function initProgress( $history = WikiExporter::FULL ) {
254                 $table = ( $history == WikiExporter::CURRENT ) ? 'page' : 'revision';
255                 $field = ( $history == WikiExporter::CURRENT ) ? 'page_id' : 'rev_id';
257                 $dbr = $this->forcedDb;
258                 if ( $this->forcedDb === null ) {
259                         $dbr = wfGetDB( DB_SLAVE );
260                 }
261                 $this->maxCount = $dbr->selectField( $table, "MAX($field)", '', __METHOD__ );
262                 $this->startTime = microtime( true );
263                 $this->lastTime = $this->startTime;
264                 $this->ID = getmypid();
265         }
267         /**
268          * @todo Fixme: the --server parameter is currently not respected, as it
269          * doesn't seem terribly easy to ask the load balancer for a particular
270          * connection by name.
271          * @return DatabaseBase
272          */
273         function backupDb() {
274                 if ( $this->forcedDb !== null ) {
275                         return $this->forcedDb;
276                 }
278                 $this->lb = wfGetLBFactory()->newMainLB();
279                 $db = $this->lb->getConnection( DB_SLAVE, 'dump' );
281                 // Discourage the server from disconnecting us if it takes a long time
282                 // to read out the big ol' batch query.
283                 $db->setSessionOptions( array( 'connTimeout' => 3600 * 24 ) );
285                 return $db;
286         }
288         /**
289          * Force the dump to use the provided database connection for database
290          * operations, wherever possible.
291          *
292          * @param DatabaseBase|null $db (Optional) the database connection to use. If null, resort to
293          *   use the globally provided ways to get database connections.
294          */
295         function setDb( DatabaseBase $db = null ) {
296                 $this->forcedDb = $db;
297         }
299         function __destruct() {
300                 if ( isset( $this->lb ) ) {
301                         $this->lb->closeAll();
302                 }
303         }
305         function backupServer() {
306                 global $wgDBserver;
307                 return $this->server
308                         ? $this->server
309                         : $wgDBserver;
310         }
312         function reportPage() {
313                 $this->pageCount++;
314         }
316         function revCount() {
317                 $this->revCount++;
318                 $this->report();
319         }
321         function report( $final = false ) {
322                 if ( $final xor ( $this->revCount % $this->reportingInterval == 0 ) ) {
323                         $this->showReport();
324                 }
325         }
327         function showReport() {
328                 if ( $this->reporting ) {
329                         $now = wfTimestamp( TS_DB );
330                         $nowts = microtime( true );
331                         $deltaAll = $nowts - $this->startTime;
332                         $deltaPart = $nowts - $this->lastTime;
333                         $this->pageCountPart = $this->pageCount - $this->pageCountLast;
334                         $this->revCountPart = $this->revCount - $this->revCountLast;
336                         if ( $deltaAll ) {
337                                 $portion = $this->revCount / $this->maxCount;
338                                 $eta = $this->startTime + $deltaAll / $portion;
339                                 $etats = wfTimestamp( TS_DB, intval( $eta ) );
340                                 $pageRate = $this->pageCount / $deltaAll;
341                                 $revRate = $this->revCount / $deltaAll;
342                         } else {
343                                 $pageRate = '-';
344                                 $revRate = '-';
345                                 $etats = '-';
346                         }
347                         if ( $deltaPart ) {
348                                 $pageRatePart = $this->pageCountPart / $deltaPart;
349                                 $revRatePart = $this->revCountPart / $deltaPart;
350                         } else {
351                                 $pageRatePart = '-';
352                                 $revRatePart = '-';
353                         }
354                         $this->progress( sprintf( "%s: %s (ID %d) %d pages (%0.1f|%0.1f/sec all|curr), %d revs (%0.1f|%0.1f/sec all|curr), ETA %s [max %d]",
355                                         $now, wfWikiID(), $this->ID, $this->pageCount, $pageRate, $pageRatePart, $this->revCount, $revRate, $revRatePart, $etats, $this->maxCount ) );
356                         $this->lastTime = $nowts;
357                         $this->revCountLast = $this->revCount;
358                 }
359         }
361         function progress( $string ) {
362                 fwrite( $this->stderr, $string . "\n" );
363         }
365         function fatalError( $msg ) {
366                 $this->progress( "$msg\n" );
367                 die( 1 );
368         }
371 class ExportProgressFilter extends DumpFilter {
372         function __construct( &$sink, &$progress ) {
373                 parent::__construct( $sink );
374                 $this->progress = $progress;
375         }
377         function writeClosePage( $string ) {
378                 parent::writeClosePage( $string );
379                 $this->progress->reportPage();
380         }
382         function writeRevision( $rev, $string ) {
383                 parent::writeRevision( $rev, $string );
384                 $this->progress->revCount();
385         }