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