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;
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 .= ' ' . wfWikiID();
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 $cmd = 'php ' . Shell
::escape( __FILE__
);
222 foreach ( self
::$cmdLineOptionMap as $cmdOption => $classOption ) {
223 if ( $cmdOption == 'replica-id' ) {
225 } elseif ( in_array( $cmdOption, self
::$optionsWithArgs ) && isset( $this->$classOption ) ) {
226 $cmd .= " --$cmdOption " . Shell
::escape( $this->$classOption );
227 } elseif ( $this->$classOption ) {
228 $cmd .= " --$cmdOption";
232 ' --wiki ' . Shell
::escape( wfWikiID() ) .
233 ' ' . Shell
::escape( ...$this->destClusters
);
235 $this->replicaPipes
= $this->replicaProcs
= [];
236 for ( $i = 0; $i < $this->numProcs
; $i++
) {
240 [ 'file', 'php://stdout', 'w' ],
241 [ 'file', 'php://stderr', 'w' ]
243 Wikimedia\
suppressWarnings();
244 $proc = proc_open( "$cmd --replica-id $i", $spec, $pipes );
245 Wikimedia\restoreWarnings
();
247 $this->critical( "Error opening replica DB process: $cmd" );
250 $this->replicaProcs
[$i] = $proc;
251 $this->replicaPipes
[$i] = $pipes[0];
253 $this->prevReplicaId
= -1;
257 * Gracefully terminate the child processes
259 function killReplicaProcs() {
260 $this->info( "Waiting for replica DB processes to finish..." );
261 for ( $i = 0; $i < $this->numProcs
; $i++
) {
262 $this->dispatchToReplica( $i, 'quit' );
264 for ( $i = 0; $i < $this->numProcs
; $i++
) {
265 $status = proc_close( $this->replicaProcs
[$i] );
267 $this->critical( "Warning: child #$i exited with status $status" );
270 $this->info( "Done." );
274 * Dispatch a command to the next available replica DB.
275 * This may block until a replica DB finishes its work and becomes available.
277 function dispatch( ...$args ) {
278 $pipes = $this->replicaPipes
;
281 $numPipes = stream_select( $x, $pipes, $y, 3600 );
283 $this->critical( "Error waiting to write to replica DBs. Aborting" );
286 for ( $i = 0; $i < $this->numProcs
; $i++
) {
287 $replicaId = ( $i +
$this->prevReplicaId +
1 ) %
$this->numProcs
;
288 if ( isset( $pipes[$replicaId] ) ) {
289 $this->prevReplicaId
= $replicaId;
290 $this->dispatchToReplica( $replicaId, $args );
295 $this->critical( "Unreachable" );
300 * Dispatch a command to a specified replica DB
301 * @param int $replicaId
302 * @param array|string $args
304 function dispatchToReplica( $replicaId, $args ) {
305 $args = (array)$args;
306 $cmd = implode( ' ', $args );
307 fwrite( $this->replicaPipes
[$replicaId], "$cmd\n" );
311 * Move all tracked pages to the new clusters
313 function doAllPages() {
314 $dbr = wfGetDB( DB_REPLICA
);
317 if ( $this->noCount
) {
318 $numPages = '[unknown]';
320 $numPages = $dbr->selectField( 'blob_tracking',
321 'COUNT(DISTINCT bt_page)',
322 # A condition is required so that this query uses the index
327 if ( $this->copyOnly
) {
328 $this->info( "Copying pages..." );
330 $this->info( "Moving pages..." );
333 $res = $dbr->select( 'blob_tracking',
337 'bt_page > ' . $dbr->addQuotes( $startId )
342 'ORDER BY' => 'bt_page',
343 'LIMIT' => $this->batchSize
,
346 if ( !$res->numRows() ) {
349 foreach ( $res as $row ) {
350 $startId = $row->bt_page
;
351 $this->dispatch( 'doPage', $row->bt_page
);
354 $this->report( 'pages', $i, $numPages );
356 $this->report( 'pages', $i, $numPages );
357 if ( $this->copyOnly
) {
358 $this->info( "All page copies queued." );
360 $this->info( "All page moves queued." );
365 * Display a progress report
366 * @param string $label
367 * @param int $current
370 function report( $label, $current, $end ) {
372 if ( $current == $end ||
$this->numBatches
>= $this->reportingInterval
) {
373 $this->numBatches
= 0;
374 $this->info( "$label: $current / $end" );
375 MediaWikiServices
::getInstance()->getDBLoadBalancerFactory()->waitForReplication();
380 * Move all orphan text to the new clusters
382 function doAllOrphans() {
383 $dbr = wfGetDB( DB_REPLICA
);
386 if ( $this->noCount
) {
387 $numOrphans = '[unknown]';
389 $numOrphans = $dbr->selectField( 'blob_tracking',
390 'COUNT(DISTINCT bt_text_id)',
391 [ 'bt_moved' => 0, 'bt_page' => 0 ],
393 if ( !$numOrphans ) {
397 if ( $this->copyOnly
) {
398 $this->info( "Copying orphans..." );
400 $this->info( "Moving orphans..." );
404 $res = $dbr->select( 'blob_tracking',
409 'bt_text_id > ' . $dbr->addQuotes( $startId )
414 'ORDER BY' => 'bt_text_id',
415 'LIMIT' => $this->batchSize
418 if ( !$res->numRows() ) {
422 foreach ( $res as $row ) {
423 $startId = $row->bt_text_id
;
424 $ids[] = $row->bt_text_id
;
427 // Need to send enough orphan IDs to the child at a time to fill a blob,
428 // so orphanBatchSize needs to be at least ~100.
429 // batchSize can be smaller or larger.
430 while ( count( $ids ) > $this->orphanBatchSize
) {
431 $args = array_slice( $ids, 0, $this->orphanBatchSize
);
432 $ids = array_slice( $ids, $this->orphanBatchSize
);
433 array_unshift( $args, 'doOrphanList' );
434 $this->dispatch( ...$args );
436 if ( count( $ids ) ) {
438 array_unshift( $args, 'doOrphanList' );
439 $this->dispatch( ...$args );
442 $this->report( 'orphans', $i, $numOrphans );
444 $this->report( 'orphans', $i, $numOrphans );
445 $this->info( "All orphans queued." );
449 * Main entry point for worker processes
451 function executeChild() {
452 $this->debug( 'starting' );
455 while ( !feof( STDIN
) ) {
456 $line = rtrim( fgets( STDIN
) );
460 $this->debug( $line );
461 $args = explode( ' ', $line );
462 $cmd = array_shift( $args );
465 $this->doPage( intval( $args[0] ) );
468 $this->doOrphanList( array_map( 'intval', $args ) );
473 MediaWikiServices
::getInstance()->getDBLoadBalancerFactory()->waitForReplication();
478 * Move tracked text in a given page
482 function doPage( $pageId ) {
483 $title = Title
::newFromID( $pageId );
485 $titleText = $title->getPrefixedText();
487 $titleText = '[deleted]';
489 $dbr = wfGetDB( DB_REPLICA
);
491 // Finish any incomplete transactions
492 if ( !$this->copyOnly
) {
493 $this->finishIncompleteMoves( [ 'bt_page' => $pageId ] );
498 $trx = new CgzCopyTransaction( $this, $this->pageBlobClass
);
500 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
503 [ 'blob_tracking', 'text' ],
506 'bt_page' => $pageId,
507 'bt_text_id > ' . $dbr->addQuotes( $startId ),
509 'bt_new_url IS NULL',
514 'ORDER BY' => 'bt_text_id',
515 'LIMIT' => $this->batchSize
518 if ( !$res->numRows() ) {
523 foreach ( $res as $row ) {
524 $startId = $row->bt_text_id
;
525 if ( $lastTextId == $row->bt_text_id
) {
526 // Duplicate (null edit)
529 $lastTextId = $row->bt_text_id
;
531 $text = Revision
::getRevisionText( $row );
532 if ( $text === false ) {
533 $this->critical( "Error loading {$row->bt_rev_id}/{$row->bt_text_id}" );
538 if ( !$trx->addItem( $text, $row->bt_text_id
) ) {
539 $this->debug( "$titleText: committing blob with " . $trx->getSize() . " items" );
541 $trx = new CgzCopyTransaction( $this, $this->pageBlobClass
);
542 $lbFactory->waitForReplication();
547 $this->debug( "$titleText: committing blob with " . $trx->getSize() . " items" );
552 * Atomic move operation.
554 * Write the new URL to the text table and set the bt_moved flag.
556 * This is done in a single transaction to provide restartable behavior
559 * The transaction is kept short to reduce locking.
564 function moveTextRow( $textId, $url ) {
565 if ( $this->copyOnly
) {
566 $this->critical( "Internal error: can't call moveTextRow() in --copy-only mode" );
569 $dbw = wfGetDB( DB_MASTER
);
570 $dbw->begin( __METHOD__
);
571 $dbw->update( 'text',
574 'old_flags' => 'external,utf-8',
581 $dbw->update( 'blob_tracking',
583 [ 'bt_text_id' => $textId ],
586 $dbw->commit( __METHOD__
);
590 * Moves are done in two phases: bt_new_url and then bt_moved.
591 * - bt_new_url indicates that the text has been copied to the new cluster.
592 * - bt_moved indicates that the text table has been updated.
594 * This function completes any moves that only have done bt_new_url. This
595 * can happen when the script is interrupted, or when --copy-only is used.
597 * @param array $conds
599 function finishIncompleteMoves( $conds ) {
600 $dbr = wfGetDB( DB_REPLICA
);
601 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
604 $conds = array_merge( $conds, [
606 'bt_new_url IS NOT NULL'
609 $res = $dbr->select( 'blob_tracking',
611 array_merge( $conds, [ 'bt_text_id > ' . $dbr->addQuotes( $startId ) ] ),
614 'ORDER BY' => 'bt_text_id',
615 'LIMIT' => $this->batchSize
,
618 if ( !$res->numRows() ) {
621 $this->debug( 'Incomplete: ' . $res->numRows() . ' rows' );
622 foreach ( $res as $row ) {
623 $startId = $row->bt_text_id
;
624 $this->moveTextRow( $row->bt_text_id
, $row->bt_new_url
);
625 if ( $row->bt_text_id %
10 == 0 ) {
626 $lbFactory->waitForReplication();
633 * Returns the name of the next target cluster
636 function getTargetCluster() {
637 $cluster = next( $this->destClusters
);
638 if ( $cluster === false ) {
639 $cluster = reset( $this->destClusters
);
646 * Gets a DB master connection for the given external cluster name
647 * @param string $cluster
650 function getExtDB( $cluster ) {
651 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
652 $lb = $lbFactory->getExternalLB( $cluster );
654 return $lb->getConnection( DB_MASTER
);
658 * Move an orphan text_id to the new cluster
660 * @param array $textIds
662 function doOrphanList( $textIds ) {
663 // Finish incomplete moves
664 if ( !$this->copyOnly
) {
665 $this->finishIncompleteMoves( [ 'bt_text_id' => $textIds ] );
669 $trx = new CgzCopyTransaction( $this, $this->orphanBlobClass
);
671 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
672 $res = wfGetDB( DB_REPLICA
)->select(
673 [ 'text', 'blob_tracking' ],
674 [ 'old_id', 'old_text', 'old_flags' ],
676 'old_id' => $textIds,
684 foreach ( $res as $row ) {
685 $text = Revision
::getRevisionText( $row );
686 if ( $text === false ) {
687 $this->critical( "Error: cannot load revision text for old_id={$row->old_id}" );
691 if ( !$trx->addItem( $text, $row->old_id
) ) {
692 $this->debug( "[orphan]: committing blob with " . $trx->getSize() . " rows" );
694 $trx = new CgzCopyTransaction( $this, $this->orphanBlobClass
);
695 $lbFactory->waitForReplication();
698 $this->debug( "[orphan]: committing blob with " . $trx->getSize() . " rows" );
704 * Class to represent a recompression operation for a single CGZ blob
706 class CgzCopyTransaction
{
707 /** @var RecompressTracked */
710 /** @var ConcatenatedGzipHistoryBlob */
715 * Create a transaction from a RecompressTracked object
716 * @param RecompressTracked $parent
717 * @param string $blobClass
719 function __construct( $parent, $blobClass ) {
720 $this->blobClass
= $blobClass;
723 $this->parent
= $parent;
728 * Returns false if it's ready to commit.
729 * @param string $text
733 function addItem( $text, $textId ) {
735 $class = $this->blobClass
;
736 $this->cgz
= new $class;
738 $hash = $this->cgz
->addItem( $text );
739 $this->referrers
[$textId] = $hash;
740 $this->texts
[$textId] = $text;
742 return $this->cgz
->isHappy();
746 return count( $this->texts
);
750 * Recompress text after some aberrant modification
752 function recompress() {
753 $class = $this->blobClass
;
754 $this->cgz
= new $class;
755 $this->referrers
= [];
756 foreach ( $this->texts
as $textId => $text ) {
757 $hash = $this->cgz
->addItem( $text );
758 $this->referrers
[$textId] = $hash;
764 * Does nothing if no text items have been added.
765 * May skip the move if --copy-only is set.
768 $originalCount = count( $this->texts
);
769 if ( !$originalCount ) {
773 /* Check to see if the target text_ids have been moved already.
775 * We originally read from the replica DB, so this can happen when a single
776 * text_id is shared between multiple pages. It's rare, but possible
777 * if a delete/move/undelete cycle splits up a null edit.
779 * We do a locking read to prevent closer-run race conditions.
781 $dbw = wfGetDB( DB_MASTER
);
782 $dbw->begin( __METHOD__
);
783 $res = $dbw->select( 'blob_tracking',
784 [ 'bt_text_id', 'bt_moved' ],
785 [ 'bt_text_id' => array_keys( $this->referrers
) ],
786 __METHOD__
, [ 'FOR UPDATE' ] );
788 foreach ( $res as $row ) {
789 if ( $row->bt_moved
) {
790 # This row has already been moved, remove it
791 $this->parent
->debug( "TRX: conflict detected in old_id={$row->bt_text_id}" );
792 unset( $this->texts
[$row->bt_text_id
] );
797 // Recompress the blob if necessary
799 if ( !count( $this->texts
) ) {
800 // All have been moved already
801 if ( $originalCount > 1 ) {
802 // This is suspcious, make noise
803 $this->parent
->critical(
804 "Warning: concurrent operation detected, are there two conflicting " .
805 "processes running, doing the same job?" );
813 // Insert the data into the destination cluster
814 $targetCluster = $this->parent
->getTargetCluster();
815 $store = $this->parent
->store
;
816 $targetDB = $store->getMaster( $targetCluster );
817 $targetDB->clearFlag( DBO_TRX
); // we manage the transactions
818 $targetDB->begin( __METHOD__
);
819 $baseUrl = $this->parent
->store
->store( $targetCluster, serialize( $this->cgz
) );
821 // Write the new URLs to the blob_tracking table
822 foreach ( $this->referrers
as $textId => $hash ) {
823 $url = $baseUrl . '/' . $hash;
824 $dbw->update( 'blob_tracking',
825 [ 'bt_new_url' => $url ],
827 'bt_text_id' => $textId,
828 'bt_moved' => 0, # Check for concurrent conflicting update
834 $targetDB->commit( __METHOD__
);
835 // Critical section here: interruption at this point causes blob duplication
836 // Reversing the order of the commits would cause data loss instead
837 $dbw->commit( __METHOD__
);
839 // Write the new URLs to the text table and set the moved flag
840 if ( !$this->parent
->copyOnly
) {
841 foreach ( $this->referrers
as $textId => $hash ) {
842 $url = $baseUrl . '/' . $hash;
843 $this->parent
->moveTextRow( $textId, $url );