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