r108300: also destroy the repo/backend singletons for upload test
[mediawiki.git] / maintenance / backup.inc
blob814d0c09d06273157b2fd1826f18b098c732d3a1
1 <?php
2 /**
3  * Base classes for database dumpers
4  *
5  * Copyright © 2005 Brion Vibber <brion@pobox.com>
6  * http://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 DumpDBZip2Output( $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 $sink       = null; // Output filters
51         var $stubText   = false; // include rev_text_id instead of text; for 2-pass dump
52         var $dumpUploads = false;
53         var $dumpUploadFileContents = false;
54         var $lastTime = 0;
55         var $pageCountLast = 0;
56         var $revCountLast = 0;
57         var $ID = 0;
59         var $outputTypes = array(), $filterTypes = array();
61         /**
62          * @var LoadBalancer
63          */
64         protected $lb;
66         function __construct( $args ) {
67                 $this->stderr = fopen( "php://stderr", "wt" );
69                 // Built-in output and filter plugins
70                 $this->registerOutput( 'file', 'DumpFileOutput' );
71                 $this->registerOutput( 'gzip', 'DumpGZipOutput' );
72                 $this->registerOutput( 'bzip2', 'DumpBZip2Output' );
73                 $this->registerOutput( 'dbzip2', 'DumpDBZip2Output' );
74                 $this->registerOutput( '7zip', 'Dump7ZipOutput' );
76                 $this->registerFilter( 'latest', 'DumpLatestFilter' );
77                 $this->registerFilter( 'notalk', 'DumpNotalkFilter' );
78                 $this->registerFilter( 'namespace', 'DumpNamespaceFilter' );
80                 $this->sink = $this->processArgs( $args );
81         }
83         /**
84          * @param $name String
85          * @param $class String: name of output filter plugin class
86          */
87         function registerOutput( $name, $class ) {
88                 $this->outputTypes[$name] = $class;
89         }
91         /**
92          * @param $name String
93          * @param $class String: name of filter plugin class
94          */
95         function registerFilter( $name, $class ) {
96                 $this->filterTypes[$name] = $class;
97         }
99         /**
100          * Load a plugin and register it
101          *
102          * @param $class String: name of plugin class; must have a static 'register'
103          *               method that takes a BackupDumper as a parameter.
104          * @param $file String: full or relative path to the PHP file to load, or empty
105          */
106         function loadPlugin( $class, $file ) {
107                 if ( $file != '' ) {
108                         require_once( $file );
109                 }
110                 $register = array( $class, 'register' );
111                 call_user_func_array( $register, array( &$this ) );
112         }
114         /**
115          * @param $args Array
116          * @return Array
117          */
118         function processArgs( $args ) {
119                 $sink = null;
120                 $sinks = array();
121                 foreach ( $args as $arg ) {
122                         $matches = array();
123                         if ( preg_match( '/^--(.+?)(?:=(.+?)(?::(.+?))?)?$/', $arg, $matches ) ) {
124                                 @list( /* $full */ , $opt, $val, $param ) = $matches;
125                                 switch( $opt ) {
126                                 case "plugin":
127                                         $this->loadPlugin( $val, $param );
128                                         break;
129                                 case "output":
130                                         if ( !is_null( $sink ) ) {
131                                                 $sinks[] = $sink;
132                                         }
133                                         if ( !isset( $this->outputTypes[$val] ) ) {
134                                                 $this->fatalError( "Unrecognized output sink type '$val'" );
135                                         }
136                                         $type = $this->outputTypes[$val];
137                                         $sink = new $type( $param );
138                                         break;
139                                 case "filter":
140                                         if ( is_null( $sink ) ) {
141                                                 $sink = new DumpOutput();
142                                         }
143                                         if ( !isset( $this->filterTypes[$val] ) ) {
144                                                 $this->fatalError( "Unrecognized filter type '$val'" );
145                                         }
146                                         $type = $this->filterTypes[$val];
147                                         $filter = new $type( $sink, $param );
149                                         // references are lame in php...
150                                         unset( $sink );
151                                         $sink = $filter;
153                                         break;
154                                 case "report":
155                                         $this->reportingInterval = intval( $val );
156                                         break;
157                                 case "server":
158                                         $this->server = $val;
159                                         break;
160                                 case "force-normal":
161                                         if ( !function_exists( 'utf8_normalize' ) ) {
162                                                 wfDl( "php_utfnormal.so" );
163                                                 if ( !function_exists( 'utf8_normalize' ) ) {
164                                                         $this->fatalError( "Failed to load UTF-8 normalization extension. " .
165                                                                 "Install or remove --force-normal parameter to use slower code." );
166                                                 }
167                                         }
168                                         break;
169                                 default:
170                                         $this->processOption( $opt, $val, $param );
171                                 }
172                         }
173                 }
175                 if ( is_null( $sink ) ) {
176                         $sink = new DumpOutput();
177                 }
178                 $sinks[] = $sink;
180                 if ( count( $sinks ) > 1 ) {
181                         return new DumpMultiWriter( $sinks );
182                 } else {
183                         return $sink;
184                 }
185         }
187         function processOption( $opt, $val, $param ) {
188                 // extension point for subclasses to add options
189         }
191         function dump( $history, $text = WikiExporter::TEXT ) {
192                 # Notice messages will foul up your XML output even if they're
193                 # relatively harmless.
194                 if ( ini_get( 'display_errors' ) )
195                         ini_set( 'display_errors', 'stderr' );
197                 $this->initProgress( $history );
199                 $db = $this->backupDb();
200                 $exporter = new WikiExporter( $db, $history, WikiExporter::STREAM, $text );
201                 $exporter->dumpUploads = $this->dumpUploads;
202                 $exporter->dumpUploadFileContents = $this->dumpUploadFileContents;
204                 $wrapper = new ExportProgressFilter( $this->sink, $this );
205                 $exporter->setOutputSink( $wrapper );
207                 if ( !$this->skipHeader )
208                         $exporter->openStream();
209                 # Log item dumps: all or by range
210                 if ( $history & WikiExporter::LOGS ) {
211                         if ( $this->startId || $this->endId ) {
212                                 $exporter->logsByRange( $this->startId, $this->endId );
213                         } else {
214                                 $exporter->allLogs();
215                         }
216                 # Page dumps: all or by page ID range
217                 } else if ( is_null( $this->pages ) ) {
218                         if ( $this->startId || $this->endId ) {
219                                 $exporter->pagesByRange( $this->startId, $this->endId );
220                         } elseif ( $this->revStartId || $this->revEndId ) {
221                                 $exporter->revsByRange( $this->revStartId, $this->revEndId );
222                         } else {
223                                 $exporter->allPages();
224                         }
225                 # Dump of specific pages
226                 } else {
227                         $exporter->pagesByName( $this->pages );
228                 }
230                 if ( !$this->skipFooter )
231                         $exporter->closeStream();
233                 $this->report( true );
234         }
236         /**
237          * Initialise starting time and maximum revision count.
238          * We'll make ETA calculations based an progress, assuming relatively
239          * constant per-revision rate.
240          * @param $history Integer: WikiExporter::CURRENT or WikiExporter::FULL
241          */
242         function initProgress( $history = WikiExporter::FULL ) {
243                 $table = ( $history == WikiExporter::CURRENT ) ? 'page' : 'revision';
244                 $field = ( $history == WikiExporter::CURRENT ) ? 'page_id' : 'rev_id';
246                 $dbr = wfGetDB( DB_SLAVE );
247                 $this->maxCount = $dbr->selectField( $table, "MAX($field)", '', __METHOD__ );
248                 $this->startTime = wfTime();
249                 $this->lastTime = $this->startTime;
250                 $this->ID = getmypid();
251         }
253         /**
254          * @todo Fixme: the --server parameter is currently not respected, as it
255          * doesn't seem terribly easy to ask the load balancer for a particular
256          * connection by name.
257          * @return DatabaseBase
258          */
259         function backupDb() {
260                 $this->lb = wfGetLBFactory()->newMainLB();
261                 $db = $this->lb->getConnection( DB_SLAVE, 'backup' );
263                 // Discourage the server from disconnecting us if it takes a long time
264                 // to read out the big ol' batch query.
265                 $db->setTimeout( 3600 * 24 );
267                 return $db;
268         }
270         function __destruct() {
271                 if ( isset( $this->lb ) ) {
272                         $this->lb->closeAll();
273                 }
274         }
276         function backupServer() {
277                 global $wgDBserver;
278                 return $this->server
279                         ? $this->server
280                         : $wgDBserver;
281         }
283         function reportPage() {
284                 $this->pageCount++;
285         }
287         function revCount() {
288                 $this->revCount++;
289                 $this->report();
290         }
292         function report( $final = false ) {
293                 if ( $final xor ( $this->revCount % $this->reportingInterval == 0 ) ) {
294                         $this->showReport();
295                 }
296         }
298         function showReport() {
299                 if ( $this->reporting ) {
300                         $now = wfTimestamp( TS_DB );
301                         $nowts = wfTime();
302                         $deltaAll = wfTime() - $this->startTime;
303                         $deltaPart = wfTime() - $this->lastTime;
304                         $this->pageCountPart = $this->pageCount - $this->pageCountLast;
305                         $this->revCountPart = $this->revCount - $this->revCountLast;
307                         if ( $deltaAll ) {
308                                 $portion = $this->revCount / $this->maxCount;
309                                 $eta = $this->startTime + $deltaAll / $portion;
310                                 $etats = wfTimestamp( TS_DB, intval( $eta ) );
311                                 $pageRate = $this->pageCount / $deltaAll;
312                                 $revRate = $this->revCount / $deltaAll;
313                         } else {
314                                 $pageRate = '-';
315                                 $revRate = '-';
316                                 $etats = '-';
317                         }
318                         if ( $deltaPart ) {
319                                 $pageRatePart = $this->pageCountPart / $deltaPart;
320                                 $revRatePart = $this->revCountPart / $deltaPart;
321                         } else {
322                                 $pageRatePart = '-';
323                                 $revRatePart = '-';
324                         }
325                         $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]",
326                                         $now, wfWikiID(), $this->ID, $this->pageCount, $pageRate, $pageRatePart, $this->revCount, $revRate, $revRatePart, $etats, $this->maxCount ) );
327                         $this->lastTime = $nowts;
328                         $this->revCountLast = $this->revCount;
329                 }
330         }
332         function progress( $string ) {
333                 fwrite( $this->stderr, $string . "\n" );
334         }
336         function fatalError( $msg ) {
337                 $this->progress( "$msg\n" );
338                 die(1);
339         }
342 class ExportProgressFilter extends DumpFilter {
343         function __construct( &$sink, &$progress ) {
344                 parent::__construct( $sink );
345                 $this->progress = $progress;
346         }
348         function writeClosePage( $string ) {
349                 parent::writeClosePage( $string );
350                 $this->progress->reportPage();
351         }
353         function writeRevision( $rev, $string ) {
354                 parent::writeRevision( $rev, $string );
355                 $this->progress->revCount();
356         }