Rewrite compressOld to subclass maintenanance
[lhc/web/wiklou.git] / maintenance / storage / compressOld.php
1 <?php
2 /**
3 * Compress the text of a wiki.
4 *
5 * Usage:
6 *
7 * Non-wikimedia
8 * php compressOld.php [options...]
9 *
10 * Wikimedia
11 * php compressOld.php <database> [options...]
12 *
13 * Options are:
14 * -t <type> set compression type to either:
15 * gzip: compress revisions independently
16 * concat: concatenate revisions and compress in chunks (default)
17 * -c <chunk-size> maximum number of revisions in a concat chunk
18 * -b <begin-date> earliest date to check for uncompressed revisions
19 * -e <end-date> latest revision date to compress
20 * -s <start-id> the old_id to start from
21 * --extdb <cluster> store specified revisions in an external cluster (untested)
22 *
23 * This program is free software; you can redistribute it and/or modify
24 * it under the terms of the GNU General Public License as published by
25 * the Free Software Foundation; either version 2 of the License, or
26 * (at your option) any later version.
27 *
28 * This program is distributed in the hope that it will be useful,
29 * but WITHOUT ANY WARRANTY; without even the implied warranty of
30 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
31 * GNU General Public License for more details.
32 *
33 * You should have received a copy of the GNU General Public License along
34 * with this program; if not, write to the Free Software Foundation, Inc.,
35 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
36 * http://www.gnu.org/copyleft/gpl.html
37 *
38 * @file
39 * @ingroup Maintenance ExternalStorage
40 */
41
42 require_once( dirname( __FILE__ ) . '/../Maintenance.php' );
43
44 class CompressOld extends Maintenance {
45 /**
46 * @todo document
47 */
48 const LS_INDIVIDUAL = 0;
49 const LS_CHUNKED = 1;
50
51 public function __construct() {
52 parent::__construct();
53 $this->mDescription = 'Compress the text of a wiki';
54 $this->addOption( 'type', 'Set compression type to either: gzip|concat', false, true, 't' );
55 $this->addOption( 'chunksize', 'Maximum number of revisions in a concat chunk', false, true, 'c' );
56 $this->addOption( 'begin-date', 'Earliest date to check for uncompressed revisions', false, true, 'b' );
57 $this->addOption( 'end-date', 'Latest revision date to compress', false, true, 'e' );
58 $this->addOption( 'start-id', 'The old_id to start from', false, true, 's');
59 $this->addOption( 'extdb', 'Store specified revisions in an external cluster (untested)', false, true );
60 $this->addOption( 'endid', 'Stop at this old_id', false, true, 'n' );
61 }
62
63 public function execute() {
64 global $wgDBname;
65 if ( !function_exists( "gzdeflate" ) ) {
66 $this->error( "You must enable zlib support in PHP to compress old revisions!\n" .
67 "Please see http://www.php.net/manual/en/ref.zlib.php\n", true );
68 }
69
70 $type = $this->getOption( 'type', 'concat' );
71 $chunkSize = $this->getOption( 'chunksize', 20 );
72 $startId = $this->getOption( 'start-id', 0 );
73 $beginDate = $this->getOption( 'begin-date', '' );
74 $endDate = $this->getOption( 'end-date', '' );
75 $extDB = $this->getOption( 'extdb', '' );
76 $endId = $this->getOption( 'endid', false );
77
78 if ( $type != 'concat' && $type != 'gzip' ) {
79 $this->error( "Type \"{$type}\" not supported" );
80 }
81
82 if ( $extDB != '' ) {
83 $this->output( "Compressing database {$wgDBname} to external cluster {$extDB}\n"
84 . str_repeat( '-', 76 ) . "\n\n" );
85 } else {
86 $this->output( "Compressing database {$wgDBname}\n"
87 . str_repeat( '-', 76 ) . "\n\n" );
88 }
89
90 $success = true;
91 if ( $type == 'concat' ) {
92 $success = $this->compressWithConcat( $startId, $chunkSize, $beginDate,
93 $endDate, $extDB, $endId );
94 } else {
95 $this->compressOldPages( $startId, $extDB );
96 }
97
98 if ( $success ) {
99 $this->output( "Done.\n" );
100 }
101 }
102
103 /** @todo document */
104 private function compressOldPages( $start = 0, $extdb = '' ) {
105 $chunksize = 50;
106 $this->output( "Starting from old_id $start...\n" );
107 $dbw = wfGetDB( DB_MASTER );
108 do {
109 $res = $dbw->select( 'text', array( 'old_id','old_flags','old_text' ),
110 "old_id>=$start", __METHOD__, array( 'ORDER BY' => 'old_id', 'LIMIT' => $chunksize, 'FOR UPDATE' ) );
111 if( $dbw->numRows( $res ) == 0 ) {
112 break;
113 }
114 $last = $start;
115 foreach ( $res as $row ) {
116 # print " {$row->old_id} - {$row->old_namespace}:{$row->old_title}\n";
117 $this->compressPage( $row, $extdb );
118 $last = $row->old_id;
119 }
120 $start = $last + 1; # Deletion may leave long empty stretches
121 $this->output( "$start...\n" );
122 } while( true );
123 }
124
125 /** @todo document */
126 private function compressPage( $row, $extdb ) {
127 if ( false !== strpos( $row->old_flags, 'gzip' ) || false !== strpos( $row->old_flags, 'object' ) ) {
128 #print "Already compressed row {$row->old_id}\n";
129 return false;
130 }
131 $dbw = wfGetDB( DB_MASTER );
132 $flags = $row->old_flags ? "{$row->old_flags},gzip" : "gzip";
133 $compress = gzdeflate( $row->old_text );
134
135 # Store in external storage if required
136 if ( $extdb !== '' ) {
137 $storeObj = new ExternalStoreDB;
138 $compress = $storeObj->store( $extdb, $compress );
139 if ( $compress === false ) {
140 $this->error( "Unable to store object" );
141 return false;
142 }
143 }
144
145 # Update text row
146 $dbw->update( 'text',
147 array( /* SET */
148 'old_flags' => $flags,
149 'old_text' => $compress
150 ), array( /* WHERE */
151 'old_id' => $row->old_id
152 ), __METHOD__,
153 array( 'LIMIT' => 1 )
154 );
155 return true;
156 }
157
158 /** @todo document */
159 private function compressWithConcat( $startId, $maxChunkSize, $beginDate,
160 $endDate, $extdb = "", $maxPageId = false )
161 {
162 $loadStyle = self::LS_CHUNKED;
163
164 $dbr = wfGetDB( DB_SLAVE );
165 $dbw = wfGetDB( DB_MASTER );
166
167 # Set up external storage
168 if ( $extdb != '' ) {
169 $storeObj = new ExternalStoreDB;
170 }
171
172 # Get all articles by page_id
173 if ( !$maxPageId ) {
174 $maxPageId = $dbr->selectField( 'page', 'max(page_id)', '', __METHOD__ );
175 }
176 $this->output( "Starting from $startId of $maxPageId\n" );
177 $pageConds = array();
178
179 /*
180 if ( $exclude_ns0 ) {
181 print "Excluding main namespace\n";
182 $pageConds[] = 'page_namespace<>0';
183 }
184 if ( $queryExtra ) {
185 $pageConds[] = $queryExtra;
186 }
187 */
188
189 # For each article, get a list of revisions which fit the criteria
190
191 # No recompression, use a condition on old_flags
192 # Don't compress object type entities, because that might produce data loss when
193 # overwriting bulk storage concat rows. Don't compress external references, because
194 # the script doesn't yet delete rows from external storage.
195 $conds = array(
196 'old_flags NOT ' . $dbr->buildLike( $dbr->anyString(), 'object', $dbr->anyString() ) . ' AND old_flags NOT '
197 . $dbr->buildLike( $dbr->anyString(), 'external', $dbr->anyString() ) );
198
199 if ( $beginDate ) {
200 if ( !preg_match( '/^\d{14}$/', $beginDate ) ) {
201 $this->error( "Invalid begin date \"$beginDate\"\n" );
202 return false;
203 }
204 $conds[] = "rev_timestamp>'" . $beginDate . "'";
205 }
206 if ( $endDate ) {
207 if ( !preg_match( '/^\d{14}$/', $endDate ) ) {
208 $this->error( "Invalid end date \"$endDate\"\n" );
209 return false;
210 }
211 $conds[] = "rev_timestamp<'" . $endDate . "'";
212 }
213 if ( $loadStyle == self::LS_CHUNKED ) {
214 $tables = array( 'revision', 'text' );
215 $fields = array( 'rev_id', 'rev_text_id', 'old_flags', 'old_text' );
216 $conds[] = 'rev_text_id=old_id';
217 $revLoadOptions = 'FOR UPDATE';
218 } else {
219 $tables = array( 'revision' );
220 $fields = array( 'rev_id', 'rev_text_id' );
221 $revLoadOptions = array();
222 }
223
224 # Don't work with current revisions
225 # Don't lock the page table for update either -- TS 2006-04-04
226 #$tables[] = 'page';
227 #$conds[] = 'page_id=rev_page AND rev_id != page_latest';
228
229 for ( $pageId = $startId; $pageId <= $maxPageId; $pageId++ ) {
230 wfWaitForSlaves();
231
232 # Wake up
233 $dbr->ping();
234
235 # Get the page row
236 $pageRes = $dbr->select( 'page',
237 array('page_id', 'page_namespace', 'page_title','page_latest'),
238 $pageConds + array('page_id' => $pageId), __METHOD__ );
239 if ( $dbr->numRows( $pageRes ) == 0 ) {
240 continue;
241 }
242 $pageRow = $dbr->fetchObject( $pageRes );
243
244 # Display progress
245 $titleObj = Title::makeTitle( $pageRow->page_namespace, $pageRow->page_title );
246 $this->output( "$pageId\t" . $titleObj->getPrefixedDBkey() . " " );
247
248 # Load revisions
249 $revRes = $dbw->select( $tables, $fields,
250 array_merge( array(
251 'rev_page' => $pageRow->page_id,
252 # Don't operate on the current revision
253 # Use < instead of <> in case the current revision has changed
254 # since the page select, which wasn't locking
255 'rev_id < ' . $pageRow->page_latest
256 ), $conds ),
257 __METHOD__,
258 $revLoadOptions
259 );
260 $revs = array();
261 foreach ( $revRes as $revRow ) {
262 $revs[] = $revRow;
263 }
264
265 if ( count( $revs ) < 2) {
266 # No revisions matching, no further processing
267 $this->output( "\n" );
268 continue;
269 }
270
271 # For each chunk
272 $i = 0;
273 while ( $i < count( $revs ) ) {
274 if ( $i < count( $revs ) - $maxChunkSize ) {
275 $thisChunkSize = $maxChunkSize;
276 } else {
277 $thisChunkSize = count( $revs ) - $i;
278 }
279
280 $chunk = new ConcatenatedGzipHistoryBlob();
281 $stubs = array();
282 $dbw->begin();
283 $usedChunk = false;
284 $primaryOldid = $revs[$i]->rev_text_id;
285
286 # Get the text of each revision and add it to the object
287 for ( $j = 0; $j < $thisChunkSize && $chunk->isHappy(); $j++ ) {
288 $oldid = $revs[$i + $j]->rev_text_id;
289
290 # Get text
291 if ( $loadStyle == self::LS_INDIVIDUAL ) {
292 $textRow = $dbw->selectRow( 'text',
293 array( 'old_flags', 'old_text' ),
294 array( 'old_id' => $oldid ),
295 __METHOD__,
296 'FOR UPDATE'
297 );
298 $text = Revision::getRevisionText( $textRow );
299 } else {
300 $text = Revision::getRevisionText( $revs[$i + $j] );
301 }
302
303 if ( $text === false ) {
304 $this->error( "\nError, unable to get text in old_id $oldid" );
305 #$dbw->delete( 'old', array( 'old_id' => $oldid ) );
306 }
307
308 if ( $extdb == "" && $j == 0 ) {
309 $chunk->setText( $text );
310 $this->output( '.' );
311 } else {
312 # Don't make a stub if it's going to be longer than the article
313 # Stubs are typically about 100 bytes
314 if ( strlen( $text ) < 120 ) {
315 $stub = false;
316 $this->output( 'x' );
317 } else {
318 $stub = new HistoryBlobStub( $chunk->addItem( $text ) );
319 $stub->setLocation( $primaryOldid );
320 $stub->setReferrer( $oldid );
321 $this->output( '.' );
322 $usedChunk = true;
323 }
324 $stubs[$j] = $stub;
325 }
326 }
327 $thisChunkSize = $j;
328
329 # If we couldn't actually use any stubs because the pages were too small, do nothing
330 if ( $usedChunk ) {
331 if ( $extdb != "" ) {
332 # Move blob objects to External Storage
333 $stored = $storeObj->store( $extdb, serialize( $chunk ));
334 if ($stored === false) {
335 $this->error( "Unable to store object" );
336 return false;
337 }
338 # Store External Storage URLs instead of Stub placeholders
339 foreach ($stubs as $stub) {
340 if ($stub===false)
341 continue;
342 # $stored should provide base path to a BLOB
343 $url = $stored."/".$stub->getHash();
344 $dbw->update( 'text',
345 array( /* SET */
346 'old_text' => $url,
347 'old_flags' => 'external,utf-8',
348 ), array ( /* WHERE */
349 'old_id' => $stub->getReferrer(),
350 )
351 );
352 }
353 } else {
354 # Store the main object locally
355 $dbw->update( 'text',
356 array( /* SET */
357 'old_text' => serialize( $chunk ),
358 'old_flags' => 'object,utf-8',
359 ), array( /* WHERE */
360 'old_id' => $primaryOldid
361 )
362 );
363
364 # Store the stub objects
365 for ( $j = 1; $j < $thisChunkSize; $j++ ) {
366 # Skip if not compressing and don't overwrite the first revision
367 if ( $stubs[$j] !== false && $revs[$i + $j]->rev_text_id != $primaryOldid ) {
368 $dbw->update( 'text',
369 array( /* SET */
370 'old_text' => serialize($stubs[$j]),
371 'old_flags' => 'object,utf-8',
372 ), array( /* WHERE */
373 'old_id' => $revs[$i + $j]->rev_text_id
374 )
375 );
376 }
377 }
378 }
379 }
380 # Done, next
381 $this->output( "/" );
382 $dbw->commit();
383 $i += $thisChunkSize;
384 wfWaitForSlaves();
385 }
386 $this->output( "\n" );
387 }
388 return true;
389 }
390
391 }
392
393 $maintClass = 'CompressOld';
394 require_once( RUN_MAINTENANCE_IF_MAIN );