Merge "Minor CSS cleanup for Vector and Monobook skins"
[mediawiki.git] / maintenance / storage / compressOld.php
blobb766fe9cde2eaec716ab5c2ee3b2127686eb8b3f
1 <?php
2 /**
3 * Compress the text of a wiki.
5 * Usage:
7 * Non-wikimedia
8 * php compressOld.php [options...]
10 * Wikimedia
11 * php compressOld.php <database> [options...]
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)
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.
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.
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
40 * @file
41 * @ingroup Maintenance ExternalStorage
44 require_once( __DIR__ . '/../Maintenance.php' );
46 /**
47 * Maintenance script that compress the text of a wiki.
49 * @ingroup Maintenance ExternalStorage
51 class CompressOld extends Maintenance {
52 /**
53 * @todo document
55 const LS_INDIVIDUAL = 0;
56 const LS_CHUNKED = 1;
58 public function __construct() {
59 parent::__construct();
60 $this->mDescription = 'Compress the text of a wiki';
61 $this->addOption( 'type', 'Set compression type to either: gzip|concat', false, true, 't' );
62 $this->addOption( 'chunksize', 'Maximum number of revisions in a concat chunk', false, true, 'c' );
63 $this->addOption( 'begin-date', 'Earliest date to check for uncompressed revisions', false, true, 'b' );
64 $this->addOption( 'end-date', 'Latest revision date to compress', false, true, 'e' );
65 $this->addOption( 'startid', 'The id to start from (gzip -> text table, concat -> page table)', false, true, 's' );
66 $this->addOption( 'extdb', 'Store specified revisions in an external cluster (untested)', false, true );
67 $this->addOption( 'endid', 'The page_id to stop at (only when using concat compression type)', false, true, 'n' );
70 public function execute() {
71 global $wgDBname;
72 if ( !function_exists( "gzdeflate" ) ) {
73 $this->error( "You must enable zlib support in PHP to compress old revisions!\n" .
74 "Please see http://www.php.net/manual/en/ref.zlib.php\n", true );
77 $type = $this->getOption( 'type', 'concat' );
78 $chunkSize = $this->getOption( 'chunksize', 20 );
79 $startId = $this->getOption( 'startid', 0 );
80 $beginDate = $this->getOption( 'begin-date', '' );
81 $endDate = $this->getOption( 'end-date', '' );
82 $extDB = $this->getOption( 'extdb', '' );
83 $endId = $this->getOption( 'endid', false );
85 if ( $type != 'concat' && $type != 'gzip' ) {
86 $this->error( "Type \"{$type}\" not supported" );
89 if ( $extDB != '' ) {
90 $this->output( "Compressing database {$wgDBname} to external cluster {$extDB}\n"
91 . str_repeat( '-', 76 ) . "\n\n" );
92 } else {
93 $this->output( "Compressing database {$wgDBname}\n"
94 . str_repeat( '-', 76 ) . "\n\n" );
97 $success = true;
98 if ( $type == 'concat' ) {
99 $success = $this->compressWithConcat( $startId, $chunkSize, $beginDate,
100 $endDate, $extDB, $endId );
101 } else {
102 $this->compressOldPages( $startId, $extDB );
105 if ( $success ) {
106 $this->output( "Done.\n" );
110 /** @todo document */
111 private function compressOldPages( $start = 0, $extdb = '' ) {
112 $chunksize = 50;
113 $this->output( "Starting from old_id $start...\n" );
114 $dbw = wfGetDB( DB_MASTER );
115 do {
116 $res = $dbw->select( 'text', array( 'old_id', 'old_flags', 'old_text' ),
117 "old_id>=$start", __METHOD__, array( 'ORDER BY' => 'old_id', 'LIMIT' => $chunksize, 'FOR UPDATE' ) );
118 if ( $res->numRows() == 0 ) {
119 break;
121 $last = $start;
122 foreach ( $res as $row ) {
123 # print " {$row->old_id} - {$row->old_namespace}:{$row->old_title}\n";
124 $this->compressPage( $row, $extdb );
125 $last = $row->old_id;
127 $start = $last + 1; # Deletion may leave long empty stretches
128 $this->output( "$start...\n" );
129 } while ( true );
133 * @todo document
134 * @param $row
135 * @param $extdb
136 * @return bool
138 private function compressPage( $row, $extdb ) {
139 if ( false !== strpos( $row->old_flags, 'gzip' ) || false !== strpos( $row->old_flags, 'object' ) ) {
140 #print "Already compressed row {$row->old_id}\n";
141 return false;
143 $dbw = wfGetDB( DB_MASTER );
144 $flags = $row->old_flags ? "{$row->old_flags},gzip" : "gzip";
145 $compress = gzdeflate( $row->old_text );
147 # Store in external storage if required
148 if ( $extdb !== '' ) {
149 $storeObj = new ExternalStoreDB;
150 $compress = $storeObj->store( $extdb, $compress );
151 if ( $compress === false ) {
152 $this->error( "Unable to store object" );
153 return false;
157 # Update text row
158 $dbw->update( 'text',
159 array( /* SET */
160 'old_flags' => $flags,
161 'old_text' => $compress
162 ), array( /* WHERE */
163 'old_id' => $row->old_id
164 ), __METHOD__,
165 array( 'LIMIT' => 1 )
167 return true;
171 * @param $startId
172 * @param $maxChunkSize
173 * @param $beginDate
174 * @param $endDate
175 * @param $extdb string
176 * @param $maxPageId bool|int
177 * @return bool
179 private function compressWithConcat( $startId, $maxChunkSize, $beginDate,
180 $endDate, $extdb = "", $maxPageId = false )
182 $loadStyle = self::LS_CHUNKED;
184 $dbr = wfGetDB( DB_SLAVE );
185 $dbw = wfGetDB( DB_MASTER );
187 # Set up external storage
188 if ( $extdb != '' ) {
189 $storeObj = new ExternalStoreDB;
192 # Get all articles by page_id
193 if ( !$maxPageId ) {
194 $maxPageId = $dbr->selectField( 'page', 'max(page_id)', '', __METHOD__ );
196 $this->output( "Starting from $startId of $maxPageId\n" );
197 $pageConds = array();
200 if ( $exclude_ns0 ) {
201 print "Excluding main namespace\n";
202 $pageConds[] = 'page_namespace<>0';
204 if ( $queryExtra ) {
205 $pageConds[] = $queryExtra;
209 # For each article, get a list of revisions which fit the criteria
211 # No recompression, use a condition on old_flags
212 # Don't compress object type entities, because that might produce data loss when
213 # overwriting bulk storage concat rows. Don't compress external references, because
214 # the script doesn't yet delete rows from external storage.
215 $conds = array(
216 'old_flags NOT ' . $dbr->buildLike( $dbr->anyString(), 'object', $dbr->anyString() ) . ' AND old_flags NOT '
217 . $dbr->buildLike( $dbr->anyString(), 'external', $dbr->anyString() ) );
219 if ( $beginDate ) {
220 if ( !preg_match( '/^\d{14}$/', $beginDate ) ) {
221 $this->error( "Invalid begin date \"$beginDate\"\n" );
222 return false;
224 $conds[] = "rev_timestamp>'" . $beginDate . "'";
226 if ( $endDate ) {
227 if ( !preg_match( '/^\d{14}$/', $endDate ) ) {
228 $this->error( "Invalid end date \"$endDate\"\n" );
229 return false;
231 $conds[] = "rev_timestamp<'" . $endDate . "'";
233 if ( $loadStyle == self::LS_CHUNKED ) {
234 $tables = array( 'revision', 'text' );
235 $fields = array( 'rev_id', 'rev_text_id', 'old_flags', 'old_text' );
236 $conds[] = 'rev_text_id=old_id';
237 $revLoadOptions = 'FOR UPDATE';
238 } else {
239 $tables = array( 'revision' );
240 $fields = array( 'rev_id', 'rev_text_id' );
241 $revLoadOptions = array();
244 # Don't work with current revisions
245 # Don't lock the page table for update either -- TS 2006-04-04
246 #$tables[] = 'page';
247 #$conds[] = 'page_id=rev_page AND rev_id != page_latest';
249 for ( $pageId = $startId; $pageId <= $maxPageId; $pageId++ ) {
250 wfWaitForSlaves();
252 # Wake up
253 $dbr->ping();
255 # Get the page row
256 $pageRes = $dbr->select( 'page',
257 array( 'page_id', 'page_namespace', 'page_title', 'page_latest' ),
258 $pageConds + array( 'page_id' => $pageId ), __METHOD__ );
259 if ( $pageRes->numRows() == 0 ) {
260 continue;
262 $pageRow = $dbr->fetchObject( $pageRes );
264 # Display progress
265 $titleObj = Title::makeTitle( $pageRow->page_namespace, $pageRow->page_title );
266 $this->output( "$pageId\t" . $titleObj->getPrefixedDBkey() . " " );
268 # Load revisions
269 $revRes = $dbw->select( $tables, $fields,
270 array_merge( array(
271 'rev_page' => $pageRow->page_id,
272 # Don't operate on the current revision
273 # Use < instead of <> in case the current revision has changed
274 # since the page select, which wasn't locking
275 'rev_id < ' . $pageRow->page_latest
276 ), $conds ),
277 __METHOD__,
278 $revLoadOptions
280 $revs = array();
281 foreach ( $revRes as $revRow ) {
282 $revs[] = $revRow;
285 if ( count( $revs ) < 2) {
286 # No revisions matching, no further processing
287 $this->output( "\n" );
288 continue;
291 # For each chunk
292 $i = 0;
293 while ( $i < count( $revs ) ) {
294 if ( $i < count( $revs ) - $maxChunkSize ) {
295 $thisChunkSize = $maxChunkSize;
296 } else {
297 $thisChunkSize = count( $revs ) - $i;
300 $chunk = new ConcatenatedGzipHistoryBlob();
301 $stubs = array();
302 $dbw->begin( __METHOD__ );
303 $usedChunk = false;
304 $primaryOldid = $revs[$i]->rev_text_id;
306 # Get the text of each revision and add it to the object
307 for ( $j = 0; $j < $thisChunkSize && $chunk->isHappy(); $j++ ) {
308 $oldid = $revs[$i + $j]->rev_text_id;
310 # Get text
311 if ( $loadStyle == self::LS_INDIVIDUAL ) {
312 $textRow = $dbw->selectRow( 'text',
313 array( 'old_flags', 'old_text' ),
314 array( 'old_id' => $oldid ),
315 __METHOD__,
316 'FOR UPDATE'
318 $text = Revision::getRevisionText( $textRow );
319 } else {
320 $text = Revision::getRevisionText( $revs[$i + $j] );
323 if ( $text === false ) {
324 $this->error( "\nError, unable to get text in old_id $oldid" );
325 #$dbw->delete( 'old', array( 'old_id' => $oldid ) );
328 if ( $extdb == "" && $j == 0 ) {
329 $chunk->setText( $text );
330 $this->output( '.' );
331 } else {
332 # Don't make a stub if it's going to be longer than the article
333 # Stubs are typically about 100 bytes
334 if ( strlen( $text ) < 120 ) {
335 $stub = false;
336 $this->output( 'x' );
337 } else {
338 $stub = new HistoryBlobStub( $chunk->addItem( $text ) );
339 $stub->setLocation( $primaryOldid );
340 $stub->setReferrer( $oldid );
341 $this->output( '.' );
342 $usedChunk = true;
344 $stubs[$j] = $stub;
347 $thisChunkSize = $j;
349 # If we couldn't actually use any stubs because the pages were too small, do nothing
350 if ( $usedChunk ) {
351 if ( $extdb != "" ) {
352 # Move blob objects to External Storage
353 $stored = $storeObj->store( $extdb, serialize( $chunk ));
354 if ($stored === false) {
355 $this->error( "Unable to store object" );
356 return false;
358 # Store External Storage URLs instead of Stub placeholders
359 foreach ($stubs as $stub) {
360 if ( $stub === false ) {
361 continue;
363 # $stored should provide base path to a BLOB
364 $url = $stored . "/" . $stub->getHash();
365 $dbw->update( 'text',
366 array( /* SET */
367 'old_text' => $url,
368 'old_flags' => 'external,utf-8',
369 ), array( /* WHERE */
370 'old_id' => $stub->getReferrer(),
374 } else {
375 # Store the main object locally
376 $dbw->update( 'text',
377 array( /* SET */
378 'old_text' => serialize( $chunk ),
379 'old_flags' => 'object,utf-8',
380 ), array( /* WHERE */
381 'old_id' => $primaryOldid
385 # Store the stub objects
386 for ( $j = 1; $j < $thisChunkSize; $j++ ) {
387 # Skip if not compressing and don't overwrite the first revision
388 if ( $stubs[$j] !== false && $revs[$i + $j]->rev_text_id != $primaryOldid ) {
389 $dbw->update( 'text',
390 array( /* SET */
391 'old_text' => serialize($stubs[$j]),
392 'old_flags' => 'object,utf-8',
393 ), array( /* WHERE */
394 'old_id' => $revs[$i + $j]->rev_text_id
401 # Done, next
402 $this->output( "/" );
403 $dbw->commit( __METHOD__ );
404 $i += $thisChunkSize;
405 wfWaitForSlaves();
407 $this->output( "\n" );
409 return true;
414 $maintClass = 'CompressOld';
415 require_once( RUN_MAINTENANCE_IF_MAIN );