Code cleanup
[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 * 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 */
26
27 /**
28 * @ingroup Dump Maintenance
29 */
30 class DumpDBZip2Output extends DumpPipeOutput {
31 function DumpDBZip2Output( $file ) {
32 parent::__construct( "dbzip2", $file );
33 }
34 }
35
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;
58
59 var $outputTypes = array(), $filterTypes = array();
60
61 /**
62 * @var LoadBalancer
63 */
64 protected $lb;
65
66 function __construct( $args ) {
67 $this->stderr = fopen( "php://stderr", "wt" );
68
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' );
75
76 $this->registerFilter( 'latest', 'DumpLatestFilter' );
77 $this->registerFilter( 'notalk', 'DumpNotalkFilter' );
78 $this->registerFilter( 'namespace', 'DumpNamespaceFilter' );
79
80 $this->sink = $this->processArgs( $args );
81 }
82
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 }
90
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 }
98
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 }
113
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 );
148
149 // references are lame in php...
150 unset( $sink );
151 $sink = $filter;
152
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 }
174
175 if ( is_null( $sink ) ) {
176 $sink = new DumpOutput();
177 }
178 $sinks[] = $sink;
179
180 if ( count( $sinks ) > 1 ) {
181 return new DumpMultiWriter( $sinks );
182 } else {
183 return $sink;
184 }
185 }
186
187 function processOption( $opt, $val, $param ) {
188 // extension point for subclasses to add options
189 }
190
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' );
196
197 $this->initProgress( $history );
198
199 $db = $this->backupDb();
200 $exporter = new WikiExporter( $db, $history, WikiExporter::STREAM, $text );
201 $exporter->dumpUploads = $this->dumpUploads;
202 $exporter->dumpUploadFileContents = $this->dumpUploadFileContents;
203
204 $wrapper = new ExportProgressFilter( $this->sink, $this );
205 $exporter->setOutputSink( $wrapper );
206
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 } else {
221 $exporter->allPages();
222 }
223 # Dump of specific pages
224 } else {
225 $exporter->pagesByName( $this->pages );
226 }
227
228 if ( !$this->skipFooter )
229 $exporter->closeStream();
230
231 $this->report( true );
232 }
233
234 /**
235 * Initialise starting time and maximum revision count.
236 * We'll make ETA calculations based an progress, assuming relatively
237 * constant per-revision rate.
238 * @param $history Integer: WikiExporter::CURRENT or WikiExporter::FULL
239 */
240 function initProgress( $history = WikiExporter::FULL ) {
241 $table = ( $history == WikiExporter::CURRENT ) ? 'page' : 'revision';
242 $field = ( $history == WikiExporter::CURRENT ) ? 'page_id' : 'rev_id';
243
244 $dbr = wfGetDB( DB_SLAVE );
245 $this->maxCount = $dbr->selectField( $table, "MAX($field)", '', __METHOD__ );
246 $this->startTime = wfTime();
247 $this->lastTime = $this->startTime;
248 $this->ID = getmypid();
249 }
250
251 /**
252 * @todo Fixme: the --server parameter is currently not respected, as it
253 * doesn't seem terribly easy to ask the load balancer for a particular
254 * connection by name.
255 */
256 function backupDb() {
257 $this->lb = wfGetLBFactory()->newMainLB();
258 $db = $this->lb->getConnection( DB_SLAVE, 'backup' );
259
260 // Discourage the server from disconnecting us if it takes a long time
261 // to read out the big ol' batch query.
262 $db->setTimeout( 3600 * 24 );
263
264 return $db;
265 }
266
267 function __destruct() {
268 if ( isset( $this->lb ) ) {
269 $this->lb->closeAll();
270 }
271 }
272
273 function backupServer() {
274 global $wgDBserver;
275 return $this->server
276 ? $this->server
277 : $wgDBserver;
278 }
279
280 function reportPage() {
281 $this->pageCount++;
282 }
283
284 function revCount() {
285 $this->revCount++;
286 $this->report();
287 }
288
289 function report( $final = false ) {
290 if ( $final xor ( $this->revCount % $this->reportingInterval == 0 ) ) {
291 $this->showReport();
292 }
293 }
294
295 function showReport() {
296 if ( $this->reporting ) {
297 $now = wfTimestamp( TS_DB );
298 $nowts = wfTime();
299 $deltaAll = wfTime() - $this->startTime;
300 $deltaPart = wfTime() - $this->lastTime;
301 $this->pageCountPart = $this->pageCount - $this->pageCountLast;
302 $this->revCountPart = $this->revCount - $this->revCountLast;
303
304 if ( $deltaAll ) {
305 $portion = $this->revCount / $this->maxCount;
306 $eta = $this->startTime + $deltaAll / $portion;
307 $etats = wfTimestamp( TS_DB, intval( $eta ) );
308 $pageRate = $this->pageCount / $deltaAll;
309 $revRate = $this->revCount / $deltaAll;
310 } else {
311 $pageRate = '-';
312 $revRate = '-';
313 $etats = '-';
314 }
315 if ( $deltaPart ) {
316 $pageRatePart = $this->pageCountPart / $deltaPart;
317 $revRatePart = $this->revCountPart / $deltaPart;
318 } else {
319 $pageRatePart = '-';
320 $revRatePart = '-';
321 }
322 $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]",
323 $now, wfWikiID(), $this->ID, $this->pageCount, $pageRate, $pageRatePart, $this->revCount, $revRate, $revRatePart, $etats, $this->maxCount ) );
324 $this->lastTime = $nowts;
325 $this->revCountLast = $this->revCount;
326 }
327 }
328
329 function progress( $string ) {
330 fwrite( $this->stderr, $string . "\n" );
331 }
332
333 function fatalError( $msg ) {
334 $this->progress( "$msg\n" );
335 die(1);
336 }
337 }
338
339 class ExportProgressFilter extends DumpFilter {
340 function ExportProgressFilter( &$sink, &$progress ) {
341 parent::__construct( $sink );
342 $this->progress = $progress;
343 }
344
345 function writeClosePage( $string ) {
346 parent::writeClosePage( $string );
347 $this->progress->reportPage();
348 }
349
350 function writeRevision( $rev, $string ) {
351 parent::writeRevision( $rev, $string );
352 $this->progress->revCount();
353 }
354 }