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 Wikimedia\Rdbms\IDatabase
;
29 $optionsWithArgs = RecompressTracked
::getOptionsWithArgs();
30 require __DIR__
. '/../commandLine.inc';
32 if ( count( $args ) < 1 ) {
33 echo "Usage: php recompressTracked.php [options] <cluster> [... <cluster>...]
34 Moves blobs indexed by trackBlobs.php to a specified list of destination clusters,
35 and recompresses them in the process. Restartable.
38 --procs <procs> Set the number of child processes (default 1)
39 --copy-only Copy only, do not update the text table. Restart
40 without this option to complete.
41 --debug-log <file> Log debugging data to the specified file
42 --info-log <file> Log progress messages to the specified file
43 --critical-log <file> Log error messages to the specified file
48 $job = RecompressTracked
::newFromCommandLine( $args, $options );
52 * Maintenance script that moves blobs indexed by trackBlobs.php to a specified
53 * list of destination clusters, and recompresses them in the process.
55 * @ingroup Maintenance ExternalStorage
57 class RecompressTracked
{
59 public $batchSize = 1000;
60 public $orphanBatchSize = 1000;
61 public $reportingInterval = 10;
63 public $numBatches = 0;
64 public $pageBlobClass, $orphanBlobClass;
65 public $replicaPipes, $replicaProcs, $prevReplicaId;
66 public $copyOnly = false;
67 public $isChild = false;
68 public $replicaId = false;
69 public $noCount = false;
70 public $debugLog, $infoLog, $criticalLog;
73 private static $optionsWithArgs = [
81 private static $cmdLineOptionMap = [
82 'no-count' => 'noCount',
83 'procs' => 'numProcs',
84 'copy-only' => 'copyOnly',
86 'replica-id' => 'replicaId',
87 'debug-log' => 'debugLog',
88 'info-log' => 'infoLog',
89 'critical-log' => 'criticalLog',
92 static function getOptionsWithArgs() {
93 return self
::$optionsWithArgs;
96 static function newFromCommandLine( $args, $options ) {
97 $jobOptions = [ 'destClusters' => $args ];
98 foreach ( self
::$cmdLineOptionMap as $cmdOption => $classOption ) {
99 if ( isset( $options[$cmdOption] ) ) {
100 $jobOptions[$classOption] = $options[$cmdOption];
104 return new self( $jobOptions );
107 function __construct( $options ) {
108 foreach ( $options as $name => $value ) {
109 $this->$name = $value;
111 $this->store
= new ExternalStoreDB
;
112 if ( !$this->isChild
) {
113 $GLOBALS['wgDebugLogPrefix'] = "RCT M: ";
114 } elseif ( $this->replicaId
!== false ) {
115 $GLOBALS['wgDebugLogPrefix'] = "RCT {$this->replicaId}: ";
117 $this->pageBlobClass
= function_exists( 'xdiff_string_bdiff' ) ?
118 DiffHistoryBlob
::class : ConcatenatedGzipHistoryBlob
::class;
119 $this->orphanBlobClass
= ConcatenatedGzipHistoryBlob
::class;
122 function debug( $msg ) {
124 if ( $this->debugLog
) {
125 $this->logToFile( $msg, $this->debugLog
);
129 function info( $msg ) {
131 if ( $this->infoLog
) {
132 $this->logToFile( $msg, $this->infoLog
);
136 function critical( $msg ) {
138 if ( $this->criticalLog
) {
139 $this->logToFile( $msg, $this->criticalLog
);
143 function logToFile( $msg, $file ) {
144 $header = '[' . date( 'd\TH:i:s' ) . '] ' . wfHostname() . ' ' . posix_getpid();
145 if ( $this->replicaId
!== false ) {
146 $header .= "({$this->replicaId})";
148 $header .= ' ' . wfWikiID();
149 LegacyLogger
::emit( sprintf( "%-50s %s\n", $header, $msg ), $file );
153 * Wait until the selected replica DB has caught up to the master.
154 * This allows us to use the replica DB for things that were committed in a
155 * previous part of this batch process.
158 $dbw = wfGetDB( DB_MASTER
);
159 $dbr = wfGetDB( DB_REPLICA
);
160 $pos = $dbw->getMasterPos();
161 $dbr->masterPosWait( $pos, 100000 );
165 * Execute parent or child depending on the isChild option
168 if ( $this->isChild
) {
169 $this->executeChild();
171 $this->executeParent();
176 * Execute the parent process
178 function executeParent() {
179 if ( !$this->checkTrackingTable() ) {
184 $this->startReplicaProcs();
186 $this->doAllOrphans();
187 $this->killReplicaProcs();
191 * Make sure the tracking table exists and isn't empty
194 function checkTrackingTable() {
195 $dbr = wfGetDB( DB_REPLICA
);
196 if ( !$dbr->tableExists( 'blob_tracking' ) ) {
197 $this->critical( "Error: blob_tracking table does not exist" );
201 $row = $dbr->selectRow( 'blob_tracking', '*', '', __METHOD__
);
203 $this->info( "Warning: blob_tracking table contains no rows, skipping this wiki." );
212 * Start the worker processes.
213 * These processes will listen on stdin for commands.
214 * This necessary because text recompression is slow: loading, compressing and
215 * writing are all slow.
217 function startReplicaProcs() {
218 $cmd = 'php ' . wfEscapeShellArg( __FILE__
);
219 foreach ( self
::$cmdLineOptionMap as $cmdOption => $classOption ) {
220 if ( $cmdOption == 'replica-id' ) {
222 } elseif ( in_array( $cmdOption, self
::$optionsWithArgs ) && isset( $this->$classOption ) ) {
223 $cmd .= " --$cmdOption " . wfEscapeShellArg( $this->$classOption );
224 } elseif ( $this->$classOption ) {
225 $cmd .= " --$cmdOption";
229 ' --wiki ' . wfEscapeShellArg( wfWikiID() ) .
230 ' ' . wfEscapeShellArg( ...$this->destClusters
);
232 $this->replicaPipes
= $this->replicaProcs
= [];
233 for ( $i = 0; $i < $this->numProcs
; $i++
) {
237 [ 'file', 'php://stdout', 'w' ],
238 [ 'file', 'php://stderr', 'w' ]
240 Wikimedia\
suppressWarnings();
241 $proc = proc_open( "$cmd --replica-id $i", $spec, $pipes );
242 Wikimedia\restoreWarnings
();
244 $this->critical( "Error opening replica DB process: $cmd" );
247 $this->replicaProcs
[$i] = $proc;
248 $this->replicaPipes
[$i] = $pipes[0];
250 $this->prevReplicaId
= -1;
254 * Gracefully terminate the child processes
256 function killReplicaProcs() {
257 $this->info( "Waiting for replica DB processes to finish..." );
258 for ( $i = 0; $i < $this->numProcs
; $i++
) {
259 $this->dispatchToReplica( $i, 'quit' );
261 for ( $i = 0; $i < $this->numProcs
; $i++
) {
262 $status = proc_close( $this->replicaProcs
[$i] );
264 $this->critical( "Warning: child #$i exited with status $status" );
267 $this->info( "Done." );
271 * Dispatch a command to the next available replica DB.
272 * This may block until a replica DB finishes its work and becomes available.
274 function dispatch( /*...*/ ) {
275 $args = func_get_args();
276 $pipes = $this->replicaPipes
;
277 $numPipes = stream_select( $x = [], $pipes, $y = [], 3600 );
279 $this->critical( "Error waiting to write to replica DBs. Aborting" );
282 for ( $i = 0; $i < $this->numProcs
; $i++
) {
283 $replicaId = ( $i +
$this->prevReplicaId +
1 ) %
$this->numProcs
;
284 if ( isset( $pipes[$replicaId] ) ) {
285 $this->prevReplicaId
= $replicaId;
286 $this->dispatchToReplica( $replicaId, $args );
291 $this->critical( "Unreachable" );
296 * Dispatch a command to a specified replica DB
297 * @param int $replicaId
298 * @param array|string $args
300 function dispatchToReplica( $replicaId, $args ) {
301 $args = (array)$args;
302 $cmd = implode( ' ', $args );
303 fwrite( $this->replicaPipes
[$replicaId], "$cmd\n" );
307 * Move all tracked pages to the new clusters
309 function doAllPages() {
310 $dbr = wfGetDB( DB_REPLICA
);
313 if ( $this->noCount
) {
314 $numPages = '[unknown]';
316 $numPages = $dbr->selectField( 'blob_tracking',
317 'COUNT(DISTINCT bt_page)',
318 # A condition is required so that this query uses the index
323 if ( $this->copyOnly
) {
324 $this->info( "Copying pages..." );
326 $this->info( "Moving pages..." );
329 $res = $dbr->select( 'blob_tracking',
333 'bt_page > ' . $dbr->addQuotes( $startId )
338 'ORDER BY' => 'bt_page',
339 'LIMIT' => $this->batchSize
,
342 if ( !$res->numRows() ) {
345 foreach ( $res as $row ) {
346 $startId = $row->bt_page
;
347 $this->dispatch( 'doPage', $row->bt_page
);
350 $this->report( 'pages', $i, $numPages );
352 $this->report( 'pages', $i, $numPages );
353 if ( $this->copyOnly
) {
354 $this->info( "All page copies queued." );
356 $this->info( "All page moves queued." );
361 * Display a progress report
362 * @param string $label
363 * @param int $current
366 function report( $label, $current, $end ) {
368 if ( $current == $end ||
$this->numBatches
>= $this->reportingInterval
) {
369 $this->numBatches
= 0;
370 $this->info( "$label: $current / $end" );
371 MediaWikiServices
::getInstance()->getDBLoadBalancerFactory()->waitForReplication();
376 * Move all orphan text to the new clusters
378 function doAllOrphans() {
379 $dbr = wfGetDB( DB_REPLICA
);
382 if ( $this->noCount
) {
383 $numOrphans = '[unknown]';
385 $numOrphans = $dbr->selectField( 'blob_tracking',
386 'COUNT(DISTINCT bt_text_id)',
387 [ 'bt_moved' => 0, 'bt_page' => 0 ],
389 if ( !$numOrphans ) {
393 if ( $this->copyOnly
) {
394 $this->info( "Copying orphans..." );
396 $this->info( "Moving orphans..." );
400 $res = $dbr->select( 'blob_tracking',
405 'bt_text_id > ' . $dbr->addQuotes( $startId )
410 'ORDER BY' => 'bt_text_id',
411 'LIMIT' => $this->batchSize
414 if ( !$res->numRows() ) {
418 foreach ( $res as $row ) {
419 $startId = $row->bt_text_id
;
420 $ids[] = $row->bt_text_id
;
423 // Need to send enough orphan IDs to the child at a time to fill a blob,
424 // so orphanBatchSize needs to be at least ~100.
425 // batchSize can be smaller or larger.
426 while ( count( $ids ) > $this->orphanBatchSize
) {
427 $args = array_slice( $ids, 0, $this->orphanBatchSize
);
428 $ids = array_slice( $ids, $this->orphanBatchSize
);
429 array_unshift( $args, 'doOrphanList' );
430 $this->dispatch( ...$args );
432 if ( count( $ids ) ) {
434 array_unshift( $args, 'doOrphanList' );
435 $this->dispatch( ...$args );
438 $this->report( 'orphans', $i, $numOrphans );
440 $this->report( 'orphans', $i, $numOrphans );
441 $this->info( "All orphans queued." );
445 * Main entry point for worker processes
447 function executeChild() {
448 $this->debug( 'starting' );
451 while ( !feof( STDIN
) ) {
452 $line = rtrim( fgets( STDIN
) );
456 $this->debug( $line );
457 $args = explode( ' ', $line );
458 $cmd = array_shift( $args );
461 $this->doPage( intval( $args[0] ) );
464 $this->doOrphanList( array_map( 'intval', $args ) );
469 MediaWikiServices
::getInstance()->getDBLoadBalancerFactory()->waitForReplication();
474 * Move tracked text in a given page
478 function doPage( $pageId ) {
479 $title = Title
::newFromID( $pageId );
481 $titleText = $title->getPrefixedText();
483 $titleText = '[deleted]';
485 $dbr = wfGetDB( DB_REPLICA
);
487 // Finish any incomplete transactions
488 if ( !$this->copyOnly
) {
489 $this->finishIncompleteMoves( [ 'bt_page' => $pageId ] );
494 $trx = new CgzCopyTransaction( $this, $this->pageBlobClass
);
496 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
499 [ 'blob_tracking', 'text' ],
502 'bt_page' => $pageId,
503 'bt_text_id > ' . $dbr->addQuotes( $startId ),
505 'bt_new_url IS NULL',
510 'ORDER BY' => 'bt_text_id',
511 'LIMIT' => $this->batchSize
514 if ( !$res->numRows() ) {
519 foreach ( $res as $row ) {
520 $startId = $row->bt_text_id
;
521 if ( $lastTextId == $row->bt_text_id
) {
522 // Duplicate (null edit)
525 $lastTextId = $row->bt_text_id
;
527 $text = Revision
::getRevisionText( $row );
528 if ( $text === false ) {
529 $this->critical( "Error loading {$row->bt_rev_id}/{$row->bt_text_id}" );
534 if ( !$trx->addItem( $text, $row->bt_text_id
) ) {
535 $this->debug( "$titleText: committing blob with " . $trx->getSize() . " items" );
537 $trx = new CgzCopyTransaction( $this, $this->pageBlobClass
);
538 $lbFactory->waitForReplication();
543 $this->debug( "$titleText: committing blob with " . $trx->getSize() . " items" );
548 * Atomic move operation.
550 * Write the new URL to the text table and set the bt_moved flag.
552 * This is done in a single transaction to provide restartable behavior
555 * The transaction is kept short to reduce locking.
560 function moveTextRow( $textId, $url ) {
561 if ( $this->copyOnly
) {
562 $this->critical( "Internal error: can't call moveTextRow() in --copy-only mode" );
565 $dbw = wfGetDB( DB_MASTER
);
566 $dbw->begin( __METHOD__
);
567 $dbw->update( 'text',
570 'old_flags' => 'external,utf-8',
577 $dbw->update( 'blob_tracking',
579 [ 'bt_text_id' => $textId ],
582 $dbw->commit( __METHOD__
);
586 * Moves are done in two phases: bt_new_url and then bt_moved.
587 * - bt_new_url indicates that the text has been copied to the new cluster.
588 * - bt_moved indicates that the text table has been updated.
590 * This function completes any moves that only have done bt_new_url. This
591 * can happen when the script is interrupted, or when --copy-only is used.
593 * @param array $conds
595 function finishIncompleteMoves( $conds ) {
596 $dbr = wfGetDB( DB_REPLICA
);
597 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
600 $conds = array_merge( $conds, [
602 'bt_new_url IS NOT NULL'
605 $res = $dbr->select( 'blob_tracking',
607 array_merge( $conds, [ 'bt_text_id > ' . $dbr->addQuotes( $startId ) ] ),
610 'ORDER BY' => 'bt_text_id',
611 'LIMIT' => $this->batchSize
,
614 if ( !$res->numRows() ) {
617 $this->debug( 'Incomplete: ' . $res->numRows() . ' rows' );
618 foreach ( $res as $row ) {
619 $startId = $row->bt_text_id
;
620 $this->moveTextRow( $row->bt_text_id
, $row->bt_new_url
);
621 if ( $row->bt_text_id %
10 == 0 ) {
622 $lbFactory->waitForReplication();
629 * Returns the name of the next target cluster
632 function getTargetCluster() {
633 $cluster = next( $this->destClusters
);
634 if ( $cluster === false ) {
635 $cluster = reset( $this->destClusters
);
642 * Gets a DB master connection for the given external cluster name
643 * @param string $cluster
646 function getExtDB( $cluster ) {
647 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
648 $lb = $lbFactory->getExternalLB( $cluster );
650 return $lb->getConnection( DB_MASTER
);
654 * Move an orphan text_id to the new cluster
656 * @param array $textIds
658 function doOrphanList( $textIds ) {
659 // Finish incomplete moves
660 if ( !$this->copyOnly
) {
661 $this->finishIncompleteMoves( [ 'bt_text_id' => $textIds ] );
665 $trx = new CgzCopyTransaction( $this, $this->orphanBlobClass
);
667 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
668 $res = wfGetDB( DB_REPLICA
)->select(
669 [ 'text', 'blob_tracking' ],
670 [ 'old_id', 'old_text', 'old_flags' ],
672 'old_id' => $textIds,
680 foreach ( $res as $row ) {
681 $text = Revision
::getRevisionText( $row );
682 if ( $text === false ) {
683 $this->critical( "Error: cannot load revision text for old_id={$row->old_id}" );
687 if ( !$trx->addItem( $text, $row->old_id
) ) {
688 $this->debug( "[orphan]: committing blob with " . $trx->getSize() . " rows" );
690 $trx = new CgzCopyTransaction( $this, $this->orphanBlobClass
);
691 $lbFactory->waitForReplication();
694 $this->debug( "[orphan]: committing blob with " . $trx->getSize() . " rows" );
700 * Class to represent a recompression operation for a single CGZ blob
702 class CgzCopyTransaction
{
703 /** @var RecompressTracked */
706 /** @var ConcatenatedGzipHistoryBlob */
711 * Create a transaction from a RecompressTracked object
712 * @param RecompressTracked $parent
713 * @param string $blobClass
715 function __construct( $parent, $blobClass ) {
716 $this->blobClass
= $blobClass;
719 $this->parent
= $parent;
724 * Returns false if it's ready to commit.
725 * @param string $text
729 function addItem( $text, $textId ) {
731 $class = $this->blobClass
;
732 $this->cgz
= new $class;
734 $hash = $this->cgz
->addItem( $text );
735 $this->referrers
[$textId] = $hash;
736 $this->texts
[$textId] = $text;
738 return $this->cgz
->isHappy();
742 return count( $this->texts
);
746 * Recompress text after some aberrant modification
748 function recompress() {
749 $class = $this->blobClass
;
750 $this->cgz
= new $class;
751 $this->referrers
= [];
752 foreach ( $this->texts
as $textId => $text ) {
753 $hash = $this->cgz
->addItem( $text );
754 $this->referrers
[$textId] = $hash;
760 * Does nothing if no text items have been added.
761 * May skip the move if --copy-only is set.
764 $originalCount = count( $this->texts
);
765 if ( !$originalCount ) {
769 /* Check to see if the target text_ids have been moved already.
771 * We originally read from the replica DB, so this can happen when a single
772 * text_id is shared between multiple pages. It's rare, but possible
773 * if a delete/move/undelete cycle splits up a null edit.
775 * We do a locking read to prevent closer-run race conditions.
777 $dbw = wfGetDB( DB_MASTER
);
778 $dbw->begin( __METHOD__
);
779 $res = $dbw->select( 'blob_tracking',
780 [ 'bt_text_id', 'bt_moved' ],
781 [ 'bt_text_id' => array_keys( $this->referrers
) ],
782 __METHOD__
, [ 'FOR UPDATE' ] );
784 foreach ( $res as $row ) {
785 if ( $row->bt_moved
) {
786 # This row has already been moved, remove it
787 $this->parent
->debug( "TRX: conflict detected in old_id={$row->bt_text_id}" );
788 unset( $this->texts
[$row->bt_text_id
] );
793 // Recompress the blob if necessary
795 if ( !count( $this->texts
) ) {
796 // All have been moved already
797 if ( $originalCount > 1 ) {
798 // This is suspcious, make noise
799 $this->parent
->critical(
800 "Warning: concurrent operation detected, are there two conflicting " .
801 "processes running, doing the same job?" );
809 // Insert the data into the destination cluster
810 $targetCluster = $this->parent
->getTargetCluster();
811 $store = $this->parent
->store
;
812 $targetDB = $store->getMaster( $targetCluster );
813 $targetDB->clearFlag( DBO_TRX
); // we manage the transactions
814 $targetDB->begin( __METHOD__
);
815 $baseUrl = $this->parent
->store
->store( $targetCluster, serialize( $this->cgz
) );
817 // Write the new URLs to the blob_tracking table
818 foreach ( $this->referrers
as $textId => $hash ) {
819 $url = $baseUrl . '/' . $hash;
820 $dbw->update( 'blob_tracking',
821 [ 'bt_new_url' => $url ],
823 'bt_text_id' => $textId,
824 'bt_moved' => 0, # Check for concurrent conflicting update
830 $targetDB->commit( __METHOD__
);
831 // Critical section here: interruption at this point causes blob duplication
832 // Reversing the order of the commits would cause data loss instead
833 $dbw->commit( __METHOD__
);
835 // Write the new URLs to the text table and set the moved flag
836 if ( !$this->parent
->copyOnly
) {
837 foreach ( $this->referrers
as $textId => $hash ) {
838 $url = $baseUrl . '/' . $hash;
839 $this->parent
->moveTextRow( $textId, $url );