Merge "Selenium: replace UserLoginPage with BlankPage where possible"
[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 use MediaWiki\MediaWikiServices;
44 use MediaWiki\Revision\SlotRecord;
45
46 require_once __DIR__ . '/../Maintenance.php';
47
48 /**
49 * Maintenance script that compress the text of a wiki.
50 *
51 * @ingroup Maintenance ExternalStorage
52 */
53 class CompressOld extends Maintenance {
54 public function __construct() {
55 parent::__construct();
56 $this->addDescription( 'Compress the text of a wiki' );
57 $this->addOption( 'type', 'Set compression type to either: gzip|concat', false, true, 't' );
58 $this->addOption(
59 'chunksize',
60 'Maximum number of revisions in a concat chunk',
61 false,
62 true,
63 'c'
64 );
65 $this->addOption(
66 'begin-date',
67 'Earliest date to check for uncompressed revisions',
68 false,
69 true,
70 'b'
71 );
72 $this->addOption( 'end-date', 'Latest revision date to compress', false, true, 'e' );
73 $this->addOption(
74 'startid',
75 'The id to start from (gzip -> text table, concat -> page table)',
76 false,
77 true,
78 's'
79 );
80 $this->addOption(
81 'extdb',
82 'Store specified revisions in an external cluster (untested)',
83 false,
84 true
85 );
86 $this->addOption(
87 'endid',
88 'The page_id to stop at (only when using concat compression type)',
89 false,
90 true,
91 'n'
92 );
93 }
94
95 public function execute() {
96 global $wgDBname;
97 if ( !function_exists( "gzdeflate" ) ) {
98 $this->fatalError( "You must enable zlib support in PHP to compress old revisions!\n" .
99 "Please see https://www.php.net/manual/en/ref.zlib.php\n" );
100 }
101
102 $type = $this->getOption( 'type', 'concat' );
103 $chunkSize = $this->getOption( 'chunksize', 20 );
104 $startId = $this->getOption( 'startid', 0 );
105 $beginDate = $this->getOption( 'begin-date', '' );
106 $endDate = $this->getOption( 'end-date', '' );
107 $extDB = $this->getOption( 'extdb', '' );
108 $endId = $this->getOption( 'endid', false );
109
110 if ( $type != 'concat' && $type != 'gzip' ) {
111 $this->error( "Type \"{$type}\" not supported" );
112 }
113
114 if ( $extDB != '' ) {
115 $this->output( "Compressing database {$wgDBname} to external cluster {$extDB}\n"
116 . str_repeat( '-', 76 ) . "\n\n" );
117 } else {
118 $this->output( "Compressing database {$wgDBname}\n"
119 . str_repeat( '-', 76 ) . "\n\n" );
120 }
121
122 $success = true;
123 if ( $type == 'concat' ) {
124 $success = $this->compressWithConcat( $startId, $chunkSize, $beginDate,
125 $endDate, $extDB, $endId );
126 } else {
127 $this->compressOldPages( $startId, $extDB );
128 }
129
130 if ( $success ) {
131 $this->output( "Done.\n" );
132 }
133 }
134
135 /**
136 * Fetch the text row-by-row to 'compressPage' function for compression.
137 *
138 * @param int $start
139 * @param string $extdb
140 */
141 private function compressOldPages( $start = 0, $extdb = '' ) {
142 $chunksize = 50;
143 $this->output( "Starting from old_id $start...\n" );
144 $dbw = $this->getDB( DB_MASTER );
145 do {
146 $res = $dbw->select(
147 'text',
148 [ 'old_id', 'old_flags', 'old_text' ],
149 "old_id>=$start",
150 __METHOD__,
151 [ 'ORDER BY' => 'old_id', 'LIMIT' => $chunksize, 'FOR UPDATE' ]
152 );
153
154 if ( $res->numRows() == 0 ) {
155 break;
156 }
157
158 $last = $start;
159
160 foreach ( $res as $row ) {
161 # print " {$row->old_id} - {$row->old_namespace}:{$row->old_title}\n";
162 $this->compressPage( $row, $extdb );
163 $last = $row->old_id;
164 }
165
166 $start = $last + 1; # Deletion may leave long empty stretches
167 $this->output( "$start...\n" );
168 } while ( true );
169 }
170
171 /**
172 * Compress the text in gzip format.
173 *
174 * @param stdClass $row
175 * @param string $extdb
176 * @return bool
177 */
178 private function compressPage( $row, $extdb ) {
179 if ( strpos( $row->old_flags, 'gzip' ) !== false
180 || strpos( $row->old_flags, 'object' ) !== false
181 ) {
182 # print "Already compressed row {$row->old_id}\n";
183 return false;
184 }
185 $dbw = $this->getDB( DB_MASTER );
186 $flags = $row->old_flags ? "{$row->old_flags},gzip" : "gzip";
187 $compress = gzdeflate( $row->old_text );
188
189 # Store in external storage if required
190 if ( $extdb !== '' ) {
191 $esFactory = MediaWikiServices::getInstance()->getExternalStoreFactory();
192 /** @var ExternalStoreDB $storeObj */
193 $storeObj = $esFactory->getStore( 'DB' );
194 $compress = $storeObj->store( $extdb, $compress );
195 if ( $compress === false ) {
196 $this->error( "Unable to store object" );
197
198 return false;
199 }
200 }
201
202 # Update text row
203 $dbw->update( 'text',
204 [ /* SET */
205 'old_flags' => $flags,
206 'old_text' => $compress
207 ], [ /* WHERE */
208 'old_id' => $row->old_id
209 ], __METHOD__,
210 [ 'LIMIT' => 1 ]
211 );
212
213 return true;
214 }
215
216 /**
217 * Compress the text in chunks after concatenating the revisions.
218 *
219 * @param int $startId
220 * @param int $maxChunkSize
221 * @param string $beginDate
222 * @param string $endDate
223 * @param string $extdb
224 * @param bool|int $maxPageId
225 * @return bool
226 */
227 private function compressWithConcat( $startId, $maxChunkSize, $beginDate,
228 $endDate, $extdb = "", $maxPageId = false
229 ) {
230 global $wgMultiContentRevisionSchemaMigrationStage;
231
232 $dbr = $this->getDB( DB_REPLICA );
233 $dbw = $this->getDB( DB_MASTER );
234
235 # Set up external storage
236 if ( $extdb != '' ) {
237 $esFactory = MediaWikiServices::getInstance()->getExternalStoreFactory();
238 /** @var ExternalStoreDB $storeObj */
239 $storeObj = $esFactory->getStore( 'DB' );
240 }
241
242 # Get all articles by page_id
243 if ( !$maxPageId ) {
244 $maxPageId = $dbr->selectField( 'page', 'max(page_id)', '', __METHOD__ );
245 }
246 $this->output( "Starting from $startId of $maxPageId\n" );
247 $pageConds = [];
248
249 /*
250 if ( $exclude_ns0 ) {
251 print "Excluding main namespace\n";
252 $pageConds[] = 'page_namespace<>0';
253 }
254 if ( $queryExtra ) {
255 $pageConds[] = $queryExtra;
256 }
257 */
258
259 # For each article, get a list of revisions which fit the criteria
260
261 # No recompression, use a condition on old_flags
262 # Don't compress object type entities, because that might produce data loss when
263 # overwriting bulk storage concat rows. Don't compress external references, because
264 # the script doesn't yet delete rows from external storage.
265 $conds = [
266 'old_flags NOT ' . $dbr->buildLike( $dbr->anyString(), 'object', $dbr->anyString() )
267 . ' AND old_flags NOT '
268 . $dbr->buildLike( $dbr->anyString(), 'external', $dbr->anyString() )
269 ];
270
271 if ( $beginDate ) {
272 if ( !preg_match( '/^\d{14}$/', $beginDate ) ) {
273 $this->error( "Invalid begin date \"$beginDate\"\n" );
274
275 return false;
276 }
277 $conds[] = "rev_timestamp>'" . $beginDate . "'";
278 }
279 if ( $endDate ) {
280 if ( !preg_match( '/^\d{14}$/', $endDate ) ) {
281 $this->error( "Invalid end date \"$endDate\"\n" );
282
283 return false;
284 }
285 $conds[] = "rev_timestamp<'" . $endDate . "'";
286 }
287
288 if ( $wgMultiContentRevisionSchemaMigrationStage & SCHEMA_COMPAT_READ_OLD ) {
289 $tables = [ 'revision', 'text' ];
290 $conds[] = 'rev_text_id=old_id';
291 } else {
292 $slotRoleStore = MediaWikiServices::getInstance()->getSlotRoleStore();
293 $tables = [ 'revision', 'slots', 'content', 'text' ];
294 $conds = array_merge( [
295 'rev_id=slot_revision_id',
296 'slot_role_id=' . $slotRoleStore->getId( SlotRecord::MAIN ),
297 'content_id=slot_content_id',
298 'SUBSTRING(content_address, 1, 3)=' . $dbr->addQuotes( 'tt:' ),
299 'SUBSTRING(content_address, 4)=old_id',
300 ], $conds );
301 }
302
303 $fields = [ 'rev_id', 'old_id', 'old_flags', 'old_text' ];
304 $revLoadOptions = 'FOR UPDATE';
305
306 # Don't work with current revisions
307 # Don't lock the page table for update either -- TS 2006-04-04
308 # $tables[] = 'page';
309 # $conds[] = 'page_id=rev_page AND rev_id != page_latest';
310
311 for ( $pageId = $startId; $pageId <= $maxPageId; $pageId++ ) {
312 wfWaitForSlaves();
313
314 # Wake up
315 $dbr->ping();
316
317 # Get the page row
318 $pageRes = $dbr->select( 'page',
319 [ 'page_id', 'page_namespace', 'page_title', 'page_latest' ],
320 $pageConds + [ 'page_id' => $pageId ], __METHOD__ );
321 if ( $pageRes->numRows() == 0 ) {
322 continue;
323 }
324 $pageRow = $dbr->fetchObject( $pageRes );
325
326 # Display progress
327 $titleObj = Title::makeTitle( $pageRow->page_namespace, $pageRow->page_title );
328 $this->output( "$pageId\t" . $titleObj->getPrefixedDBkey() . " " );
329
330 # Load revisions
331 $revRes = $dbw->select( $tables, $fields,
332 array_merge( [
333 'rev_page' => $pageRow->page_id,
334 # Don't operate on the current revision
335 # Use < instead of <> in case the current revision has changed
336 # since the page select, which wasn't locking
337 'rev_id < ' . $pageRow->page_latest
338 ], $conds ),
339 __METHOD__,
340 $revLoadOptions
341 );
342 $revs = [];
343 foreach ( $revRes as $revRow ) {
344 $revs[] = $revRow;
345 }
346
347 if ( count( $revs ) < 2 ) {
348 # No revisions matching, no further processing
349 $this->output( "\n" );
350 continue;
351 }
352
353 # For each chunk
354 $i = 0;
355 while ( $i < count( $revs ) ) {
356 if ( $i < count( $revs ) - $maxChunkSize ) {
357 $thisChunkSize = $maxChunkSize;
358 } else {
359 $thisChunkSize = count( $revs ) - $i;
360 }
361
362 $chunk = new ConcatenatedGzipHistoryBlob();
363 $stubs = [];
364 $this->beginTransaction( $dbw, __METHOD__ );
365 $usedChunk = false;
366 $primaryOldid = $revs[$i]->old_id;
367
368 # Get the text of each revision and add it to the object
369 for ( $j = 0; $j < $thisChunkSize && $chunk->isHappy(); $j++ ) {
370 $oldid = $revs[$i + $j]->old_id;
371
372 # Get text
373 $text = Revision::getRevisionText( $revs[$i + $j] );
374
375 if ( $text === false ) {
376 $this->error( "\nError, unable to get text in old_id $oldid" );
377 # $dbw->delete( 'old', [ 'old_id' => $oldid ] );
378 }
379
380 if ( $extdb == "" && $j == 0 ) {
381 $chunk->setText( $text );
382 $this->output( '.' );
383 } else {
384 # Don't make a stub if it's going to be longer than the article
385 # Stubs are typically about 100 bytes
386 if ( strlen( $text ) < 120 ) {
387 $stub = false;
388 $this->output( 'x' );
389 } else {
390 $stub = new HistoryBlobStub( $chunk->addItem( $text ) );
391 $stub->setLocation( $primaryOldid );
392 $stub->setReferrer( $oldid );
393 $this->output( '.' );
394 $usedChunk = true;
395 }
396 $stubs[$j] = $stub;
397 }
398 }
399 $thisChunkSize = $j;
400
401 # If we couldn't actually use any stubs because the pages were too small, do nothing
402 if ( $usedChunk ) {
403 if ( $extdb != "" ) {
404 # Move blob objects to External Storage
405 $stored = $storeObj->store( $extdb, serialize( $chunk ) );
406 if ( $stored === false ) {
407 $this->error( "Unable to store object" );
408
409 return false;
410 }
411 # Store External Storage URLs instead of Stub placeholders
412 foreach ( $stubs as $stub ) {
413 if ( $stub === false ) {
414 continue;
415 }
416 # $stored should provide base path to a BLOB
417 $url = $stored . "/" . $stub->getHash();
418 $dbw->update( 'text',
419 [ /* SET */
420 'old_text' => $url,
421 'old_flags' => 'external,utf-8',
422 ], [ /* WHERE */
423 'old_id' => $stub->getReferrer(),
424 ]
425 );
426 }
427 } else {
428 # Store the main object locally
429 $dbw->update( 'text',
430 [ /* SET */
431 'old_text' => serialize( $chunk ),
432 'old_flags' => 'object,utf-8',
433 ], [ /* WHERE */
434 'old_id' => $primaryOldid
435 ]
436 );
437
438 # Store the stub objects
439 for ( $j = 1; $j < $thisChunkSize; $j++ ) {
440 # Skip if not compressing and don't overwrite the first revision
441 if ( $stubs[$j] !== false && $revs[$i + $j]->old_id != $primaryOldid ) {
442 $dbw->update( 'text',
443 [ /* SET */
444 'old_text' => serialize( $stubs[$j] ),
445 'old_flags' => 'object,utf-8',
446 ], [ /* WHERE */
447 'old_id' => $revs[$i + $j]->old_id
448 ]
449 );
450 }
451 }
452 }
453 }
454 # Done, next
455 $this->output( "/" );
456 $this->commitTransaction( $dbw, __METHOD__ );
457 $i += $thisChunkSize;
458 }
459 $this->output( "\n" );
460 }
461
462 return true;
463 }
464 }
465
466 $maintClass = CompressOld::class;
467 require_once RUN_MAINTENANCE_IF_MAIN;