3 * Moves blobs indexed by trackBlobs.php to a specified list of destination
4 * clusters, and recompresses them in the process.
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 * http://www.gnu.org/copyleft/gpl.html
22 * @ingroup Maintenance ExternalStorage
25 use MediaWiki\Logger\LegacyLogger
;
26 use MediaWiki\MediaWikiServices
;
27 use MediaWiki\Shell\Shell
;
28 use Wikimedia\Rdbms\IDatabase
;
30 $optionsWithArgs = RecompressTracked
::getOptionsWithArgs();
31 require __DIR__
. '/../commandLine.inc';
33 if ( count( $args ) < 1 ) {
34 echo "Usage: php recompressTracked.php [options] <cluster> [... <cluster>...]
35 Moves blobs indexed by trackBlobs.php to a specified list of destination clusters,
36 and recompresses them in the process. Restartable.
39 --procs <procs> Set the number of child processes (default 1)
40 --copy-only Copy only, do not update the text table. Restart
41 without this option to complete.
42 --debug-log <file> Log debugging data to the specified file
43 --info-log <file> Log progress messages to the specified file
44 --critical-log <file> Log error messages to the specified file
49 $job = RecompressTracked
::newFromCommandLine( $args, $options );
53 * Maintenance script that moves blobs indexed by trackBlobs.php to a specified
54 * list of destination clusters, and recompresses them in the process.
56 * @ingroup Maintenance ExternalStorage
58 class RecompressTracked
{
60 public $batchSize = 1000;
61 public $orphanBatchSize = 1000;
62 public $reportingInterval = 10;
64 public $numBatches = 0;
65 public $pageBlobClass, $orphanBlobClass;
66 public $replicaPipes, $replicaProcs, $prevReplicaId;
67 public $copyOnly = false;
68 public $isChild = false;
69 public $replicaId = false;
70 public $noCount = false;
71 public $debugLog, $infoLog, $criticalLog;
74 private static $optionsWithArgs = [
82 private static $cmdLineOptionMap = [
83 'no-count' => 'noCount',
84 'procs' => 'numProcs',
85 'copy-only' => 'copyOnly',
87 'replica-id' => 'replicaId',
88 'debug-log' => 'debugLog',
89 'info-log' => 'infoLog',
90 'critical-log' => 'criticalLog',
93 static function getOptionsWithArgs() {
94 return self
::$optionsWithArgs;
97 static function newFromCommandLine( $args, $options ) {
98 $jobOptions = [ 'destClusters' => $args ];
99 foreach ( self
::$cmdLineOptionMap as $cmdOption => $classOption ) {
100 if ( isset( $options[$cmdOption] ) ) {
101 $jobOptions[$classOption] = $options[$cmdOption];
105 return new self( $jobOptions );
108 function __construct( $options ) {
109 foreach ( $options as $name => $value ) {
110 $this->$name = $value;
112 $this->store
= new ExternalStoreDB
;
113 if ( !$this->isChild
) {
114 $GLOBALS['wgDebugLogPrefix'] = "RCT M: ";
115 } elseif ( $this->replicaId
!== false ) {
116 $GLOBALS['wgDebugLogPrefix'] = "RCT {$this->replicaId}: ";
118 $this->pageBlobClass
= function_exists( 'xdiff_string_bdiff' ) ?
119 DiffHistoryBlob
::class : ConcatenatedGzipHistoryBlob
::class;
120 $this->orphanBlobClass
= ConcatenatedGzipHistoryBlob
::class;
123 function debug( $msg ) {
125 if ( $this->debugLog
) {
126 $this->logToFile( $msg, $this->debugLog
);
130 function info( $msg ) {
132 if ( $this->infoLog
) {
133 $this->logToFile( $msg, $this->infoLog
);
137 function critical( $msg ) {
139 if ( $this->criticalLog
) {
140 $this->logToFile( $msg, $this->criticalLog
);
144 function logToFile( $msg, $file ) {
145 $header = '[' . date( 'd\TH:i:s' ) . '] ' . wfHostname() . ' ' . posix_getpid();
146 if ( $this->replicaId
!== false ) {
147 $header .= "({$this->replicaId})";
149 $header .= ' ' . wfWikiID();
150 LegacyLogger
::emit( sprintf( "%-50s %s\n", $header, $msg ), $file );
154 * Wait until the selected replica DB has caught up to the master.
155 * This allows us to use the replica DB for things that were committed in a
156 * previous part of this batch process.
159 $dbw = wfGetDB( DB_MASTER
);
160 $dbr = wfGetDB( DB_REPLICA
);
161 $pos = $dbw->getMasterPos();
162 $dbr->masterPosWait( $pos, 100000 );
166 * Execute parent or child depending on the isChild option
169 if ( $this->isChild
) {
170 $this->executeChild();
172 $this->executeParent();
177 * Execute the parent process
179 function executeParent() {
180 if ( !$this->checkTrackingTable() ) {
185 $this->startReplicaProcs();
187 $this->doAllOrphans();
188 $this->killReplicaProcs();
192 * Make sure the tracking table exists and isn't empty
195 function checkTrackingTable() {
196 $dbr = wfGetDB( DB_REPLICA
);
197 if ( !$dbr->tableExists( 'blob_tracking' ) ) {
198 $this->critical( "Error: blob_tracking table does not exist" );
202 $row = $dbr->selectRow( 'blob_tracking', '*', '', __METHOD__
);
204 $this->info( "Warning: blob_tracking table contains no rows, skipping this wiki." );
213 * Start the worker processes.
214 * These processes will listen on stdin for commands.
215 * This necessary because text recompression is slow: loading, compressing and
216 * writing are all slow.
218 function startReplicaProcs() {
219 $cmd = 'php ' . Shell
::escape( __FILE__
);
220 foreach ( self
::$cmdLineOptionMap as $cmdOption => $classOption ) {
221 if ( $cmdOption == 'replica-id' ) {
223 } elseif ( in_array( $cmdOption, self
::$optionsWithArgs ) && isset( $this->$classOption ) ) {
224 $cmd .= " --$cmdOption " . Shell
::escape( $this->$classOption );
225 } elseif ( $this->$classOption ) {
226 $cmd .= " --$cmdOption";
230 ' --wiki ' . Shell
::escape( wfWikiID() ) .
231 ' ' . Shell
::escape( ...$this->destClusters
);
233 $this->replicaPipes
= $this->replicaProcs
= [];
234 for ( $i = 0; $i < $this->numProcs
; $i++
) {
238 [ 'file', 'php://stdout', 'w' ],
239 [ 'file', 'php://stderr', 'w' ]
241 Wikimedia\
suppressWarnings();
242 $proc = proc_open( "$cmd --replica-id $i", $spec, $pipes );
243 Wikimedia\restoreWarnings
();
245 $this->critical( "Error opening replica DB process: $cmd" );
248 $this->replicaProcs
[$i] = $proc;
249 $this->replicaPipes
[$i] = $pipes[0];
251 $this->prevReplicaId
= -1;
255 * Gracefully terminate the child processes
257 function killReplicaProcs() {
258 $this->info( "Waiting for replica DB processes to finish..." );
259 for ( $i = 0; $i < $this->numProcs
; $i++
) {
260 $this->dispatchToReplica( $i, 'quit' );
262 for ( $i = 0; $i < $this->numProcs
; $i++
) {
263 $status = proc_close( $this->replicaProcs
[$i] );
265 $this->critical( "Warning: child #$i exited with status $status" );
268 $this->info( "Done." );
272 * Dispatch a command to the next available replica DB.
273 * This may block until a replica DB finishes its work and becomes available.
275 function dispatch( ...$args ) {
276 $pipes = $this->replicaPipes
;
279 $numPipes = stream_select( $x, $pipes, $y, 3600 );
281 $this->critical( "Error waiting to write to replica DBs. Aborting" );
284 for ( $i = 0; $i < $this->numProcs
; $i++
) {
285 $replicaId = ( $i +
$this->prevReplicaId +
1 ) %
$this->numProcs
;
286 if ( isset( $pipes[$replicaId] ) ) {
287 $this->prevReplicaId
= $replicaId;
288 $this->dispatchToReplica( $replicaId, $args );
293 $this->critical( "Unreachable" );
298 * Dispatch a command to a specified replica DB
299 * @param int $replicaId
300 * @param array|string $args
302 function dispatchToReplica( $replicaId, $args ) {
303 $args = (array)$args;
304 $cmd = implode( ' ', $args );
305 fwrite( $this->replicaPipes
[$replicaId], "$cmd\n" );
309 * Move all tracked pages to the new clusters
311 function doAllPages() {
312 $dbr = wfGetDB( DB_REPLICA
);
315 if ( $this->noCount
) {
316 $numPages = '[unknown]';
318 $numPages = $dbr->selectField( 'blob_tracking',
319 'COUNT(DISTINCT bt_page)',
320 # A condition is required so that this query uses the index
325 if ( $this->copyOnly
) {
326 $this->info( "Copying pages..." );
328 $this->info( "Moving pages..." );
331 $res = $dbr->select( 'blob_tracking',
335 'bt_page > ' . $dbr->addQuotes( $startId )
340 'ORDER BY' => 'bt_page',
341 'LIMIT' => $this->batchSize
,
344 if ( !$res->numRows() ) {
347 foreach ( $res as $row ) {
348 $startId = $row->bt_page
;
349 $this->dispatch( 'doPage', $row->bt_page
);
352 $this->report( 'pages', $i, $numPages );
354 $this->report( 'pages', $i, $numPages );
355 if ( $this->copyOnly
) {
356 $this->info( "All page copies queued." );
358 $this->info( "All page moves queued." );
363 * Display a progress report
364 * @param string $label
365 * @param int $current
368 function report( $label, $current, $end ) {
370 if ( $current == $end ||
$this->numBatches
>= $this->reportingInterval
) {
371 $this->numBatches
= 0;
372 $this->info( "$label: $current / $end" );
373 MediaWikiServices
::getInstance()->getDBLoadBalancerFactory()->waitForReplication();
378 * Move all orphan text to the new clusters
380 function doAllOrphans() {
381 $dbr = wfGetDB( DB_REPLICA
);
384 if ( $this->noCount
) {
385 $numOrphans = '[unknown]';
387 $numOrphans = $dbr->selectField( 'blob_tracking',
388 'COUNT(DISTINCT bt_text_id)',
389 [ 'bt_moved' => 0, 'bt_page' => 0 ],
391 if ( !$numOrphans ) {
395 if ( $this->copyOnly
) {
396 $this->info( "Copying orphans..." );
398 $this->info( "Moving orphans..." );
402 $res = $dbr->select( 'blob_tracking',
407 'bt_text_id > ' . $dbr->addQuotes( $startId )
412 'ORDER BY' => 'bt_text_id',
413 'LIMIT' => $this->batchSize
416 if ( !$res->numRows() ) {
420 foreach ( $res as $row ) {
421 $startId = $row->bt_text_id
;
422 $ids[] = $row->bt_text_id
;
425 // Need to send enough orphan IDs to the child at a time to fill a blob,
426 // so orphanBatchSize needs to be at least ~100.
427 // batchSize can be smaller or larger.
428 while ( count( $ids ) > $this->orphanBatchSize
) {
429 $args = array_slice( $ids, 0, $this->orphanBatchSize
);
430 $ids = array_slice( $ids, $this->orphanBatchSize
);
431 array_unshift( $args, 'doOrphanList' );
432 $this->dispatch( ...$args );
434 if ( count( $ids ) ) {
436 array_unshift( $args, 'doOrphanList' );
437 $this->dispatch( ...$args );
440 $this->report( 'orphans', $i, $numOrphans );
442 $this->report( 'orphans', $i, $numOrphans );
443 $this->info( "All orphans queued." );
447 * Main entry point for worker processes
449 function executeChild() {
450 $this->debug( 'starting' );
453 while ( !feof( STDIN
) ) {
454 $line = rtrim( fgets( STDIN
) );
458 $this->debug( $line );
459 $args = explode( ' ', $line );
460 $cmd = array_shift( $args );
463 $this->doPage( intval( $args[0] ) );
466 $this->doOrphanList( array_map( 'intval', $args ) );
471 MediaWikiServices
::getInstance()->getDBLoadBalancerFactory()->waitForReplication();
476 * Move tracked text in a given page
480 function doPage( $pageId ) {
481 $title = Title
::newFromID( $pageId );
483 $titleText = $title->getPrefixedText();
485 $titleText = '[deleted]';
487 $dbr = wfGetDB( DB_REPLICA
);
489 // Finish any incomplete transactions
490 if ( !$this->copyOnly
) {
491 $this->finishIncompleteMoves( [ 'bt_page' => $pageId ] );
496 $trx = new CgzCopyTransaction( $this, $this->pageBlobClass
);
498 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
501 [ 'blob_tracking', 'text' ],
504 'bt_page' => $pageId,
505 'bt_text_id > ' . $dbr->addQuotes( $startId ),
507 'bt_new_url IS NULL',
512 'ORDER BY' => 'bt_text_id',
513 'LIMIT' => $this->batchSize
516 if ( !$res->numRows() ) {
521 foreach ( $res as $row ) {
522 $startId = $row->bt_text_id
;
523 if ( $lastTextId == $row->bt_text_id
) {
524 // Duplicate (null edit)
527 $lastTextId = $row->bt_text_id
;
529 $text = Revision
::getRevisionText( $row );
530 if ( $text === false ) {
531 $this->critical( "Error loading {$row->bt_rev_id}/{$row->bt_text_id}" );
536 if ( !$trx->addItem( $text, $row->bt_text_id
) ) {
537 $this->debug( "$titleText: committing blob with " . $trx->getSize() . " items" );
539 $trx = new CgzCopyTransaction( $this, $this->pageBlobClass
);
540 $lbFactory->waitForReplication();
545 $this->debug( "$titleText: committing blob with " . $trx->getSize() . " items" );
550 * Atomic move operation.
552 * Write the new URL to the text table and set the bt_moved flag.
554 * This is done in a single transaction to provide restartable behavior
557 * The transaction is kept short to reduce locking.
562 function moveTextRow( $textId, $url ) {
563 if ( $this->copyOnly
) {
564 $this->critical( "Internal error: can't call moveTextRow() in --copy-only mode" );
567 $dbw = wfGetDB( DB_MASTER
);
568 $dbw->begin( __METHOD__
);
569 $dbw->update( 'text',
572 'old_flags' => 'external,utf-8',
579 $dbw->update( 'blob_tracking',
581 [ 'bt_text_id' => $textId ],
584 $dbw->commit( __METHOD__
);
588 * Moves are done in two phases: bt_new_url and then bt_moved.
589 * - bt_new_url indicates that the text has been copied to the new cluster.
590 * - bt_moved indicates that the text table has been updated.
592 * This function completes any moves that only have done bt_new_url. This
593 * can happen when the script is interrupted, or when --copy-only is used.
595 * @param array $conds
597 function finishIncompleteMoves( $conds ) {
598 $dbr = wfGetDB( DB_REPLICA
);
599 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
602 $conds = array_merge( $conds, [
604 'bt_new_url IS NOT NULL'
607 $res = $dbr->select( 'blob_tracking',
609 array_merge( $conds, [ 'bt_text_id > ' . $dbr->addQuotes( $startId ) ] ),
612 'ORDER BY' => 'bt_text_id',
613 'LIMIT' => $this->batchSize
,
616 if ( !$res->numRows() ) {
619 $this->debug( 'Incomplete: ' . $res->numRows() . ' rows' );
620 foreach ( $res as $row ) {
621 $startId = $row->bt_text_id
;
622 $this->moveTextRow( $row->bt_text_id
, $row->bt_new_url
);
623 if ( $row->bt_text_id %
10 == 0 ) {
624 $lbFactory->waitForReplication();
631 * Returns the name of the next target cluster
634 function getTargetCluster() {
635 $cluster = next( $this->destClusters
);
636 if ( $cluster === false ) {
637 $cluster = reset( $this->destClusters
);
644 * Gets a DB master connection for the given external cluster name
645 * @param string $cluster
648 function getExtDB( $cluster ) {
649 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
650 $lb = $lbFactory->getExternalLB( $cluster );
652 return $lb->getConnection( DB_MASTER
);
656 * Move an orphan text_id to the new cluster
658 * @param array $textIds
660 function doOrphanList( $textIds ) {
661 // Finish incomplete moves
662 if ( !$this->copyOnly
) {
663 $this->finishIncompleteMoves( [ 'bt_text_id' => $textIds ] );
667 $trx = new CgzCopyTransaction( $this, $this->orphanBlobClass
);
669 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
670 $res = wfGetDB( DB_REPLICA
)->select(
671 [ 'text', 'blob_tracking' ],
672 [ 'old_id', 'old_text', 'old_flags' ],
674 'old_id' => $textIds,
682 foreach ( $res as $row ) {
683 $text = Revision
::getRevisionText( $row );
684 if ( $text === false ) {
685 $this->critical( "Error: cannot load revision text for old_id={$row->old_id}" );
689 if ( !$trx->addItem( $text, $row->old_id
) ) {
690 $this->debug( "[orphan]: committing blob with " . $trx->getSize() . " rows" );
692 $trx = new CgzCopyTransaction( $this, $this->orphanBlobClass
);
693 $lbFactory->waitForReplication();
696 $this->debug( "[orphan]: committing blob with " . $trx->getSize() . " rows" );
702 * Class to represent a recompression operation for a single CGZ blob
704 class CgzCopyTransaction
{
705 /** @var RecompressTracked */
708 /** @var ConcatenatedGzipHistoryBlob */
713 * Create a transaction from a RecompressTracked object
714 * @param RecompressTracked $parent
715 * @param string $blobClass
717 function __construct( $parent, $blobClass ) {
718 $this->blobClass
= $blobClass;
721 $this->parent
= $parent;
726 * Returns false if it's ready to commit.
727 * @param string $text
731 function addItem( $text, $textId ) {
733 $class = $this->blobClass
;
734 $this->cgz
= new $class;
736 $hash = $this->cgz
->addItem( $text );
737 $this->referrers
[$textId] = $hash;
738 $this->texts
[$textId] = $text;
740 return $this->cgz
->isHappy();
744 return count( $this->texts
);
748 * Recompress text after some aberrant modification
750 function recompress() {
751 $class = $this->blobClass
;
752 $this->cgz
= new $class;
753 $this->referrers
= [];
754 foreach ( $this->texts
as $textId => $text ) {
755 $hash = $this->cgz
->addItem( $text );
756 $this->referrers
[$textId] = $hash;
762 * Does nothing if no text items have been added.
763 * May skip the move if --copy-only is set.
766 $originalCount = count( $this->texts
);
767 if ( !$originalCount ) {
771 /* Check to see if the target text_ids have been moved already.
773 * We originally read from the replica DB, so this can happen when a single
774 * text_id is shared between multiple pages. It's rare, but possible
775 * if a delete/move/undelete cycle splits up a null edit.
777 * We do a locking read to prevent closer-run race conditions.
779 $dbw = wfGetDB( DB_MASTER
);
780 $dbw->begin( __METHOD__
);
781 $res = $dbw->select( 'blob_tracking',
782 [ 'bt_text_id', 'bt_moved' ],
783 [ 'bt_text_id' => array_keys( $this->referrers
) ],
784 __METHOD__
, [ 'FOR UPDATE' ] );
786 foreach ( $res as $row ) {
787 if ( $row->bt_moved
) {
788 # This row has already been moved, remove it
789 $this->parent
->debug( "TRX: conflict detected in old_id={$row->bt_text_id}" );
790 unset( $this->texts
[$row->bt_text_id
] );
795 // Recompress the blob if necessary
797 if ( !count( $this->texts
) ) {
798 // All have been moved already
799 if ( $originalCount > 1 ) {
800 // This is suspcious, make noise
801 $this->parent
->critical(
802 "Warning: concurrent operation detected, are there two conflicting " .
803 "processes running, doing the same job?" );
811 // Insert the data into the destination cluster
812 $targetCluster = $this->parent
->getTargetCluster();
813 $store = $this->parent
->store
;
814 $targetDB = $store->getMaster( $targetCluster );
815 $targetDB->clearFlag( DBO_TRX
); // we manage the transactions
816 $targetDB->begin( __METHOD__
);
817 $baseUrl = $this->parent
->store
->store( $targetCluster, serialize( $this->cgz
) );
819 // Write the new URLs to the blob_tracking table
820 foreach ( $this->referrers
as $textId => $hash ) {
821 $url = $baseUrl . '/' . $hash;
822 $dbw->update( 'blob_tracking',
823 [ 'bt_new_url' => $url ],
825 'bt_text_id' => $textId,
826 'bt_moved' => 0, # Check for concurrent conflicting update
832 $targetDB->commit( __METHOD__
);
833 // Critical section here: interruption at this point causes blob duplication
834 // Reversing the order of the commits would cause data loss instead
835 $dbw->commit( __METHOD__
);
837 // Write the new URLs to the text table and set the moved flag
838 if ( !$this->parent
->copyOnly
) {
839 foreach ( $this->referrers
as $textId => $hash ) {
840 $url = $baseUrl . '/' . $hash;
841 $this->parent
->moveTextRow( $textId, $url );