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 Wikimedia\Rdbms\IMaintainableDatabase
;
26 use MediaWiki\Logger\LegacyLogger
;
27 use MediaWiki\MediaWikiServices
;
28 use MediaWiki\Shell\Shell
;
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;
72 /** @var ExternalStoreDB */
75 private static $optionsWithArgs = [
83 private static $cmdLineOptionMap = [
84 'no-count' => 'noCount',
85 'procs' => 'numProcs',
86 'copy-only' => 'copyOnly',
88 'replica-id' => 'replicaId',
89 'debug-log' => 'debugLog',
90 'info-log' => 'infoLog',
91 'critical-log' => 'criticalLog',
94 static function getOptionsWithArgs() {
95 return self
::$optionsWithArgs;
98 static function newFromCommandLine( $args, $options ) {
99 $jobOptions = [ 'destClusters' => $args ];
100 foreach ( self
::$cmdLineOptionMap as $cmdOption => $classOption ) {
101 if ( isset( $options[$cmdOption] ) ) {
102 $jobOptions[$classOption] = $options[$cmdOption];
106 return new self( $jobOptions );
109 function __construct( $options ) {
110 foreach ( $options as $name => $value ) {
111 $this->$name = $value;
113 $esFactory = MediaWikiServices
::getInstance()->getExternalStoreFactory();
114 $this->store
= $esFactory->getStore( 'DB' );
115 if ( !$this->isChild
) {
116 $GLOBALS['wgDebugLogPrefix'] = "RCT M: ";
117 } elseif ( $this->replicaId
!== false ) {
118 $GLOBALS['wgDebugLogPrefix'] = "RCT {$this->replicaId}: ";
120 $this->pageBlobClass
= function_exists( 'xdiff_string_bdiff' ) ?
121 DiffHistoryBlob
::class : ConcatenatedGzipHistoryBlob
::class;
122 $this->orphanBlobClass
= ConcatenatedGzipHistoryBlob
::class;
125 function debug( $msg ) {
127 if ( $this->debugLog
) {
128 $this->logToFile( $msg, $this->debugLog
);
132 function info( $msg ) {
134 if ( $this->infoLog
) {
135 $this->logToFile( $msg, $this->infoLog
);
139 function critical( $msg ) {
141 if ( $this->criticalLog
) {
142 $this->logToFile( $msg, $this->criticalLog
);
146 function logToFile( $msg, $file ) {
147 $header = '[' . date( 'd\TH:i:s' ) . '] ' . wfHostname() . ' ' . posix_getpid();
148 if ( $this->replicaId
!== false ) {
149 $header .= "({$this->replicaId})";
151 $header .= ' ' . WikiMap
::getCurrentWikiDbDomain()->getId();
152 LegacyLogger
::emit( sprintf( "%-50s %s\n", $header, $msg ), $file );
156 * Wait until the selected replica DB has caught up to the master.
157 * This allows us to use the replica DB for things that were committed in a
158 * previous part of this batch process.
161 $dbw = wfGetDB( DB_MASTER
);
162 $dbr = wfGetDB( DB_REPLICA
);
163 $pos = $dbw->getMasterPos();
164 $dbr->masterPosWait( $pos, 100000 );
168 * Execute parent or child depending on the isChild option
171 if ( $this->isChild
) {
172 $this->executeChild();
174 $this->executeParent();
179 * Execute the parent process
181 function executeParent() {
182 if ( !$this->checkTrackingTable() ) {
187 $this->startReplicaProcs();
189 $this->doAllOrphans();
190 $this->killReplicaProcs();
194 * Make sure the tracking table exists and isn't empty
197 function checkTrackingTable() {
198 $dbr = wfGetDB( DB_REPLICA
);
199 if ( !$dbr->tableExists( 'blob_tracking' ) ) {
200 $this->critical( "Error: blob_tracking table does not exist" );
204 $row = $dbr->selectRow( 'blob_tracking', '*', '', __METHOD__
);
206 $this->info( "Warning: blob_tracking table contains no rows, skipping this wiki." );
215 * Start the worker processes.
216 * These processes will listen on stdin for commands.
217 * This necessary because text recompression is slow: loading, compressing and
218 * writing are all slow.
220 function startReplicaProcs() {
221 $wiki = WikiMap
::getWikiIdFromDbDomain( WikiMap
::getCurrentWikiDbDomain() );
223 $cmd = 'php ' . Shell
::escape( __FILE__
);
224 foreach ( self
::$cmdLineOptionMap as $cmdOption => $classOption ) {
225 if ( $cmdOption == 'replica-id' ) {
227 } elseif ( in_array( $cmdOption, self
::$optionsWithArgs ) && isset( $this->$classOption ) ) {
228 $cmd .= " --$cmdOption " . Shell
::escape( $this->$classOption );
229 } elseif ( $this->$classOption ) {
230 $cmd .= " --$cmdOption";
234 ' --wiki ' . Shell
::escape( $wiki ) .
235 ' ' . Shell
::escape( ...$this->destClusters
);
237 $this->replicaPipes
= $this->replicaProcs
= [];
238 for ( $i = 0; $i < $this->numProcs
; $i++
) {
242 [ 'file', 'php://stdout', 'w' ],
243 [ 'file', 'php://stderr', 'w' ]
245 Wikimedia\
suppressWarnings();
246 $proc = proc_open( "$cmd --replica-id $i", $spec, $pipes );
247 Wikimedia\restoreWarnings
();
249 $this->critical( "Error opening replica DB process: $cmd" );
252 $this->replicaProcs
[$i] = $proc;
253 $this->replicaPipes
[$i] = $pipes[0];
255 $this->prevReplicaId
= -1;
259 * Gracefully terminate the child processes
261 function killReplicaProcs() {
262 $this->info( "Waiting for replica DB processes to finish..." );
263 for ( $i = 0; $i < $this->numProcs
; $i++
) {
264 $this->dispatchToReplica( $i, 'quit' );
266 for ( $i = 0; $i < $this->numProcs
; $i++
) {
267 $status = proc_close( $this->replicaProcs
[$i] );
269 $this->critical( "Warning: child #$i exited with status $status" );
272 $this->info( "Done." );
276 * Dispatch a command to the next available replica DB.
277 * This may block until a replica DB finishes its work and becomes available.
278 * @param array|string ...$args
280 function dispatch( ...$args ) {
281 $pipes = $this->replicaPipes
;
284 $numPipes = stream_select( $x, $pipes, $y, 3600 );
286 $this->critical( "Error waiting to write to replica DBs. Aborting" );
289 for ( $i = 0; $i < $this->numProcs
; $i++
) {
290 $replicaId = ( $i +
$this->prevReplicaId +
1 ) %
$this->numProcs
;
291 if ( isset( $pipes[$replicaId] ) ) {
292 $this->prevReplicaId
= $replicaId;
293 $this->dispatchToReplica( $replicaId, $args );
298 $this->critical( "Unreachable" );
303 * Dispatch a command to a specified replica DB
304 * @param int $replicaId
305 * @param array|string $args
307 function dispatchToReplica( $replicaId, $args ) {
308 $args = (array)$args;
309 $cmd = implode( ' ', $args );
310 fwrite( $this->replicaPipes
[$replicaId], "$cmd\n" );
314 * Move all tracked pages to the new clusters
316 function doAllPages() {
317 $dbr = wfGetDB( DB_REPLICA
);
320 if ( $this->noCount
) {
321 $numPages = '[unknown]';
323 $numPages = $dbr->selectField( 'blob_tracking',
324 'COUNT(DISTINCT bt_page)',
325 # A condition is required so that this query uses the index
330 if ( $this->copyOnly
) {
331 $this->info( "Copying pages..." );
333 $this->info( "Moving pages..." );
336 $res = $dbr->select( 'blob_tracking',
340 'bt_page > ' . $dbr->addQuotes( $startId )
345 'ORDER BY' => 'bt_page',
346 'LIMIT' => $this->batchSize
,
349 if ( !$res->numRows() ) {
352 foreach ( $res as $row ) {
353 $startId = $row->bt_page
;
354 $this->dispatch( 'doPage', $row->bt_page
);
357 $this->report( 'pages', $i, $numPages );
359 $this->report( 'pages', $i, $numPages );
360 if ( $this->copyOnly
) {
361 $this->info( "All page copies queued." );
363 $this->info( "All page moves queued." );
368 * Display a progress report
369 * @param string $label
370 * @param int $current
373 function report( $label, $current, $end ) {
375 if ( $current == $end ||
$this->numBatches
>= $this->reportingInterval
) {
376 $this->numBatches
= 0;
377 $this->info( "$label: $current / $end" );
378 MediaWikiServices
::getInstance()->getDBLoadBalancerFactory()->waitForReplication();
383 * Move all orphan text to the new clusters
385 function doAllOrphans() {
386 $dbr = wfGetDB( DB_REPLICA
);
389 if ( $this->noCount
) {
390 $numOrphans = '[unknown]';
392 $numOrphans = $dbr->selectField( 'blob_tracking',
393 'COUNT(DISTINCT bt_text_id)',
394 [ 'bt_moved' => 0, 'bt_page' => 0 ],
396 if ( !$numOrphans ) {
400 if ( $this->copyOnly
) {
401 $this->info( "Copying orphans..." );
403 $this->info( "Moving orphans..." );
407 $res = $dbr->select( 'blob_tracking',
412 'bt_text_id > ' . $dbr->addQuotes( $startId )
417 'ORDER BY' => 'bt_text_id',
418 'LIMIT' => $this->batchSize
421 if ( !$res->numRows() ) {
425 foreach ( $res as $row ) {
426 $startId = $row->bt_text_id
;
427 $ids[] = $row->bt_text_id
;
430 // Need to send enough orphan IDs to the child at a time to fill a blob,
431 // so orphanBatchSize needs to be at least ~100.
432 // batchSize can be smaller or larger.
433 while ( count( $ids ) > $this->orphanBatchSize
) {
434 $args = array_slice( $ids, 0, $this->orphanBatchSize
);
435 $ids = array_slice( $ids, $this->orphanBatchSize
);
436 array_unshift( $args, 'doOrphanList' );
437 $this->dispatch( ...$args );
439 if ( count( $ids ) ) {
441 array_unshift( $args, 'doOrphanList' );
442 $this->dispatch( ...$args );
445 $this->report( 'orphans', $i, $numOrphans );
447 $this->report( 'orphans', $i, $numOrphans );
448 $this->info( "All orphans queued." );
452 * Main entry point for worker processes
454 function executeChild() {
455 $this->debug( 'starting' );
458 while ( !feof( STDIN
) ) {
459 $line = rtrim( fgets( STDIN
) );
463 $this->debug( $line );
464 $args = explode( ' ', $line );
465 $cmd = array_shift( $args );
468 $this->doPage( intval( $args[0] ) );
471 $this->doOrphanList( array_map( 'intval', $args ) );
476 MediaWikiServices
::getInstance()->getDBLoadBalancerFactory()->waitForReplication();
481 * Move tracked text in a given page
485 function doPage( $pageId ) {
486 $title = Title
::newFromID( $pageId );
488 $titleText = $title->getPrefixedText();
490 $titleText = '[deleted]';
492 $dbr = wfGetDB( DB_REPLICA
);
494 // Finish any incomplete transactions
495 if ( !$this->copyOnly
) {
496 $this->finishIncompleteMoves( [ 'bt_page' => $pageId ] );
501 $trx = new CgzCopyTransaction( $this, $this->pageBlobClass
);
503 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
506 [ 'blob_tracking', 'text' ],
509 'bt_page' => $pageId,
510 'bt_text_id > ' . $dbr->addQuotes( $startId ),
512 'bt_new_url IS NULL',
517 'ORDER BY' => 'bt_text_id',
518 'LIMIT' => $this->batchSize
521 if ( !$res->numRows() ) {
526 foreach ( $res as $row ) {
527 $startId = $row->bt_text_id
;
528 if ( $lastTextId == $row->bt_text_id
) {
529 // Duplicate (null edit)
532 $lastTextId = $row->bt_text_id
;
534 $text = Revision
::getRevisionText( $row );
535 if ( $text === false ) {
536 $this->critical( "Error loading {$row->bt_rev_id}/{$row->bt_text_id}" );
541 if ( !$trx->addItem( $text, $row->bt_text_id
) ) {
542 $this->debug( "$titleText: committing blob with " . $trx->getSize() . " items" );
544 $trx = new CgzCopyTransaction( $this, $this->pageBlobClass
);
545 $lbFactory->waitForReplication();
550 $this->debug( "$titleText: committing blob with " . $trx->getSize() . " items" );
555 * Atomic move operation.
557 * Write the new URL to the text table and set the bt_moved flag.
559 * This is done in a single transaction to provide restartable behavior
562 * The transaction is kept short to reduce locking.
567 function moveTextRow( $textId, $url ) {
568 if ( $this->copyOnly
) {
569 $this->critical( "Internal error: can't call moveTextRow() in --copy-only mode" );
572 $dbw = wfGetDB( DB_MASTER
);
573 $dbw->begin( __METHOD__
);
574 $dbw->update( 'text',
577 'old_flags' => 'external,utf-8',
584 $dbw->update( 'blob_tracking',
586 [ 'bt_text_id' => $textId ],
589 $dbw->commit( __METHOD__
);
593 * Moves are done in two phases: bt_new_url and then bt_moved.
594 * - bt_new_url indicates that the text has been copied to the new cluster.
595 * - bt_moved indicates that the text table has been updated.
597 * This function completes any moves that only have done bt_new_url. This
598 * can happen when the script is interrupted, or when --copy-only is used.
600 * @param array $conds
602 function finishIncompleteMoves( $conds ) {
603 $dbr = wfGetDB( DB_REPLICA
);
604 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
607 $conds = array_merge( $conds, [
609 'bt_new_url IS NOT NULL'
612 $res = $dbr->select( 'blob_tracking',
614 array_merge( $conds, [ 'bt_text_id > ' . $dbr->addQuotes( $startId ) ] ),
617 'ORDER BY' => 'bt_text_id',
618 'LIMIT' => $this->batchSize
,
621 if ( !$res->numRows() ) {
624 $this->debug( 'Incomplete: ' . $res->numRows() . ' rows' );
625 foreach ( $res as $row ) {
626 $startId = $row->bt_text_id
;
627 $this->moveTextRow( $row->bt_text_id
, $row->bt_new_url
);
628 if ( $row->bt_text_id %
10 == 0 ) {
629 $lbFactory->waitForReplication();
636 * Returns the name of the next target cluster
639 function getTargetCluster() {
640 $cluster = next( $this->destClusters
);
641 if ( $cluster === false ) {
642 $cluster = reset( $this->destClusters
);
649 * Gets a DB master connection for the given external cluster name
650 * @param string $cluster
651 * @return IMaintainableDatabase
653 function getExtDB( $cluster ) {
654 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
655 $lb = $lbFactory->getExternalLB( $cluster );
657 return $lb->getMaintenanceConnectionRef( DB_MASTER
);
661 * Move an orphan text_id to the new cluster
663 * @param array $textIds
665 function doOrphanList( $textIds ) {
666 // Finish incomplete moves
667 if ( !$this->copyOnly
) {
668 $this->finishIncompleteMoves( [ 'bt_text_id' => $textIds ] );
672 $trx = new CgzCopyTransaction( $this, $this->orphanBlobClass
);
674 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
675 $res = wfGetDB( DB_REPLICA
)->select(
676 [ 'text', 'blob_tracking' ],
677 [ 'old_id', 'old_text', 'old_flags' ],
679 'old_id' => $textIds,
687 foreach ( $res as $row ) {
688 $text = Revision
::getRevisionText( $row );
689 if ( $text === false ) {
690 $this->critical( "Error: cannot load revision text for old_id={$row->old_id}" );
694 if ( !$trx->addItem( $text, $row->old_id
) ) {
695 $this->debug( "[orphan]: committing blob with " . $trx->getSize() . " rows" );
697 $trx = new CgzCopyTransaction( $this, $this->orphanBlobClass
);
698 $lbFactory->waitForReplication();
701 $this->debug( "[orphan]: committing blob with " . $trx->getSize() . " rows" );
707 * Class to represent a recompression operation for a single CGZ blob
709 class CgzCopyTransaction
{
710 /** @var RecompressTracked */
713 /** @var ConcatenatedGzipHistoryBlob|false */
718 * Create a transaction from a RecompressTracked object
719 * @param RecompressTracked $parent
720 * @param string $blobClass
722 function __construct( $parent, $blobClass ) {
723 $this->blobClass
= $blobClass;
726 $this->parent
= $parent;
731 * Returns false if it's ready to commit.
732 * @param string $text
736 function addItem( $text, $textId ) {
738 $class = $this->blobClass
;
739 $this->cgz
= new $class;
741 $hash = $this->cgz
->addItem( $text );
742 $this->referrers
[$textId] = $hash;
743 $this->texts
[$textId] = $text;
745 return $this->cgz
->isHappy();
749 return count( $this->texts
);
753 * Recompress text after some aberrant modification
755 function recompress() {
756 $class = $this->blobClass
;
757 $this->cgz
= new $class;
758 $this->referrers
= [];
759 foreach ( $this->texts
as $textId => $text ) {
760 $hash = $this->cgz
->addItem( $text );
761 $this->referrers
[$textId] = $hash;
767 * Does nothing if no text items have been added.
768 * May skip the move if --copy-only is set.
771 $originalCount = count( $this->texts
);
772 if ( !$originalCount ) {
776 /* Check to see if the target text_ids have been moved already.
778 * We originally read from the replica DB, so this can happen when a single
779 * text_id is shared between multiple pages. It's rare, but possible
780 * if a delete/move/undelete cycle splits up a null edit.
782 * We do a locking read to prevent closer-run race conditions.
784 $dbw = wfGetDB( DB_MASTER
);
785 $dbw->begin( __METHOD__
);
786 $res = $dbw->select( 'blob_tracking',
787 [ 'bt_text_id', 'bt_moved' ],
788 [ 'bt_text_id' => array_keys( $this->referrers
) ],
789 __METHOD__
, [ 'FOR UPDATE' ] );
791 foreach ( $res as $row ) {
792 if ( $row->bt_moved
) {
793 # This row has already been moved, remove it
794 $this->parent
->debug( "TRX: conflict detected in old_id={$row->bt_text_id}" );
795 unset( $this->texts
[$row->bt_text_id
] );
800 // Recompress the blob if necessary
802 if ( !count( $this->texts
) ) {
803 // All have been moved already
804 if ( $originalCount > 1 ) {
805 // This is suspcious, make noise
806 $this->parent
->critical(
807 "Warning: concurrent operation detected, are there two conflicting " .
808 "processes running, doing the same job?" );
816 // Insert the data into the destination cluster
817 $targetCluster = $this->parent
->getTargetCluster();
818 $store = $this->parent
->store
;
819 $targetDB = $store->getMaster( $targetCluster );
820 $targetDB->clearFlag( DBO_TRX
); // we manage the transactions
821 $targetDB->begin( __METHOD__
);
822 $baseUrl = $this->parent
->store
->store( $targetCluster, serialize( $this->cgz
) );
824 // Write the new URLs to the blob_tracking table
825 foreach ( $this->referrers
as $textId => $hash ) {
826 $url = $baseUrl . '/' . $hash;
827 $dbw->update( 'blob_tracking',
828 [ 'bt_new_url' => $url ],
830 'bt_text_id' => $textId,
831 'bt_moved' => 0, # Check for concurrent conflicting update
837 $targetDB->commit( __METHOD__
);
838 // Critical section here: interruption at this point causes blob duplication
839 // Reversing the order of the commits would cause data loss instead
840 $dbw->commit( __METHOD__
);
842 // Write the new URLs to the text table and set the moved flag
843 if ( !$this->parent
->copyOnly
) {
844 foreach ( $this->referrers
as $textId => $hash ) {
845 $url = $baseUrl . '/' . $hash;
846 $this->parent
->moveTextRow( $textId, $url );