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 $optionsWithArgs = RecompressTracked
::getOptionsWithArgs();
26 require __DIR__
. '/../commandLine.inc';
28 if ( count( $args ) < 1 ) {
29 echo "Usage: php recompressTracked.php [options] <cluster> [... <cluster>...]
30 Moves blobs indexed by trackBlobs.php to a specified list of destination clusters,
31 and recompresses them in the process. Restartable.
34 --procs <procs> Set the number of child processes (default 1)
35 --copy-only Copy only, do not update the text table. Restart
36 without this option to complete.
37 --debug-log <file> Log debugging data to the specified file
38 --info-log <file> Log progress messages to the specified file
39 --critical-log <file> Log error messages to the specified file
44 $job = RecompressTracked
::newFromCommandLine( $args, $options );
48 * Maintenance script that moves blobs indexed by trackBlobs.php to a specified
49 * list of destination clusters, and recompresses them in the process.
51 * @ingroup Maintenance ExternalStorage
53 class RecompressTracked
{
55 public $batchSize = 1000;
56 public $orphanBatchSize = 1000;
57 public $reportingInterval = 10;
59 public $useDiff, $pageBlobClass, $orphanBlobClass;
60 public $slavePipes, $slaveProcs, $prevSlaveId;
61 public $copyOnly = false;
62 public $isChild = false;
63 public $slaveId = false;
64 public $noCount = false;
65 public $debugLog, $infoLog, $criticalLog;
68 private static $optionsWithArgs = array(
76 private static $cmdLineOptionMap = array(
77 'no-count' => 'noCount',
78 'procs' => 'numProcs',
79 'copy-only' => 'copyOnly',
81 'slave-id' => 'slaveId',
82 'debug-log' => 'debugLog',
83 'info-log' => 'infoLog',
84 'critical-log' => 'criticalLog',
87 static function getOptionsWithArgs() {
88 return self
::$optionsWithArgs;
91 static function newFromCommandLine( $args, $options ) {
92 $jobOptions = array( 'destClusters' => $args );
93 foreach ( self
::$cmdLineOptionMap as $cmdOption => $classOption ) {
94 if ( isset( $options[$cmdOption] ) ) {
95 $jobOptions[$classOption] = $options[$cmdOption];
99 return new self( $jobOptions );
102 function __construct( $options ) {
103 foreach ( $options as $name => $value ) {
104 $this->$name = $value;
106 $this->store
= new ExternalStoreDB
;
107 if ( !$this->isChild
) {
108 $GLOBALS['wgDebugLogPrefix'] = "RCT M: ";
109 } elseif ( $this->slaveId
!== false ) {
110 $GLOBALS['wgDebugLogPrefix'] = "RCT {$this->slaveId}: ";
112 $this->useDiff
= function_exists( 'xdiff_string_bdiff' );
113 $this->pageBlobClass
= $this->useDiff ?
'DiffHistoryBlob' : 'ConcatenatedGzipHistoryBlob';
114 $this->orphanBlobClass
= 'ConcatenatedGzipHistoryBlob';
117 function debug( $msg ) {
119 if ( $this->debugLog
) {
120 $this->logToFile( $msg, $this->debugLog
);
124 function info( $msg ) {
126 if ( $this->infoLog
) {
127 $this->logToFile( $msg, $this->infoLog
);
131 function critical( $msg ) {
133 if ( $this->criticalLog
) {
134 $this->logToFile( $msg, $this->criticalLog
);
138 function logToFile( $msg, $file ) {
139 $header = '[' . date( 'd\TH:i:s' ) . '] ' . wfHostname() . ' ' . posix_getpid();
140 if ( $this->slaveId
!== false ) {
141 $header .= "({$this->slaveId})";
143 $header .= ' ' . wfWikiID();
144 MWLoggerLegacyLogger
::emit( sprintf( "%-50s %s\n", $header, $msg ), $file );
148 * Wait until the selected slave has caught up to the master.
149 * This allows us to use the slave for things that were committed in a
150 * previous part of this batch process.
153 $dbw = wfGetDB( DB_MASTER
);
154 $dbr = wfGetDB( DB_SLAVE
);
155 $pos = $dbw->getMasterPos();
156 $dbr->masterPosWait( $pos, 100000 );
160 * Execute parent or child depending on the isChild option
163 if ( $this->isChild
) {
164 $this->executeChild();
166 $this->executeParent();
171 * Execute the parent process
173 function executeParent() {
174 if ( !$this->checkTrackingTable() ) {
179 $this->startSlaveProcs();
181 $this->doAllOrphans();
182 $this->killSlaveProcs();
186 * Make sure the tracking table exists and isn't empty
189 function checkTrackingTable() {
190 $dbr = wfGetDB( DB_SLAVE
);
191 if ( !$dbr->tableExists( 'blob_tracking' ) ) {
192 $this->critical( "Error: blob_tracking table does not exist" );
196 $row = $dbr->selectRow( 'blob_tracking', '*', false, __METHOD__
);
198 $this->info( "Warning: blob_tracking table contains no rows, skipping this wiki." );
207 * Start the worker processes.
208 * These processes will listen on stdin for commands.
209 * This necessary because text recompression is slow: loading, compressing and
210 * writing are all slow.
212 function startSlaveProcs() {
213 $cmd = 'php ' . wfEscapeShellArg( __FILE__
);
214 foreach ( self
::$cmdLineOptionMap as $cmdOption => $classOption ) {
215 if ( $cmdOption == 'slave-id' ) {
217 } elseif ( in_array( $cmdOption, self
::$optionsWithArgs ) && isset( $this->$classOption ) ) {
218 $cmd .= " --$cmdOption " . wfEscapeShellArg( $this->$classOption );
219 } elseif ( $this->$classOption ) {
220 $cmd .= " --$cmdOption";
224 ' --wiki ' . wfEscapeShellArg( wfWikiID() ) .
225 ' ' . call_user_func_array( 'wfEscapeShellArg', $this->destClusters
);
227 $this->slavePipes
= $this->slaveProcs
= array();
228 for ( $i = 0; $i < $this->numProcs
; $i++
) {
231 array( 'pipe', 'r' ),
232 array( 'file', 'php://stdout', 'w' ),
233 array( 'file', 'php://stderr', 'w' )
235 wfSuppressWarnings();
236 $proc = proc_open( "$cmd --slave-id $i", $spec, $pipes );
239 $this->critical( "Error opening slave process: $cmd" );
242 $this->slaveProcs
[$i] = $proc;
243 $this->slavePipes
[$i] = $pipes[0];
245 $this->prevSlaveId
= -1;
249 * Gracefully terminate the child processes
251 function killSlaveProcs() {
252 $this->info( "Waiting for slave processes to finish..." );
253 for ( $i = 0; $i < $this->numProcs
; $i++
) {
254 $this->dispatchToSlave( $i, 'quit' );
256 for ( $i = 0; $i < $this->numProcs
; $i++
) {
257 $status = proc_close( $this->slaveProcs
[$i] );
259 $this->critical( "Warning: child #$i exited with status $status" );
262 $this->info( "Done." );
266 * Dispatch a command to the next available slave.
267 * This may block until a slave finishes its work and becomes available.
269 function dispatch( /*...*/ ) {
270 $args = func_get_args();
271 $pipes = $this->slavePipes
;
272 $numPipes = stream_select( $x = array(), $pipes, $y = array(), 3600 );
274 $this->critical( "Error waiting to write to slaves. Aborting" );
277 for ( $i = 0; $i < $this->numProcs
; $i++
) {
278 $slaveId = ( $i +
$this->prevSlaveId +
1 ) %
$this->numProcs
;
279 if ( isset( $pipes[$slaveId] ) ) {
280 $this->prevSlaveId
= $slaveId;
281 $this->dispatchToSlave( $slaveId, $args );
286 $this->critical( "Unreachable" );
291 * Dispatch a command to a specified slave
292 * @param int $slaveId
293 * @param array|string $args
295 function dispatchToSlave( $slaveId, $args ) {
296 $args = (array)$args;
297 $cmd = implode( ' ', $args );
298 fwrite( $this->slavePipes
[$slaveId], "$cmd\n" );
302 * Move all tracked pages to the new clusters
304 function doAllPages() {
305 $dbr = wfGetDB( DB_SLAVE
);
308 if ( $this->noCount
) {
309 $numPages = '[unknown]';
311 $numPages = $dbr->selectField( 'blob_tracking',
312 'COUNT(DISTINCT bt_page)',
313 # A condition is required so that this query uses the index
314 array( 'bt_moved' => 0 ),
318 if ( $this->copyOnly
) {
319 $this->info( "Copying pages..." );
321 $this->info( "Moving pages..." );
324 $res = $dbr->select( 'blob_tracking',
328 'bt_page > ' . $dbr->addQuotes( $startId )
333 'ORDER BY' => 'bt_page',
334 'LIMIT' => $this->batchSize
,
337 if ( !$res->numRows() ) {
340 foreach ( $res as $row ) {
341 $this->dispatch( 'doPage', $row->bt_page
);
344 $startId = $row->bt_page
;
345 $this->report( 'pages', $i, $numPages );
347 $this->report( 'pages', $i, $numPages );
348 if ( $this->copyOnly
) {
349 $this->info( "All page copies queued." );
351 $this->info( "All page moves queued." );
356 * Display a progress report
357 * @param string $label
358 * @param int $current
361 function report( $label, $current, $end ) {
363 if ( $current == $end ||
$this->numBatches
>= $this->reportingInterval
) {
364 $this->numBatches
= 0;
365 $this->info( "$label: $current / $end" );
366 $this->waitForSlaves();
371 * Move all orphan text to the new clusters
373 function doAllOrphans() {
374 $dbr = wfGetDB( DB_SLAVE
);
377 if ( $this->noCount
) {
378 $numOrphans = '[unknown]';
380 $numOrphans = $dbr->selectField( 'blob_tracking',
381 'COUNT(DISTINCT bt_text_id)',
382 array( 'bt_moved' => 0, 'bt_page' => 0 ),
384 if ( !$numOrphans ) {
388 if ( $this->copyOnly
) {
389 $this->info( "Copying orphans..." );
391 $this->info( "Moving orphans..." );
395 $res = $dbr->select( 'blob_tracking',
396 array( 'bt_text_id' ),
400 'bt_text_id > ' . $dbr->addQuotes( $startId )
405 'ORDER BY' => 'bt_text_id',
406 'LIMIT' => $this->batchSize
409 if ( !$res->numRows() ) {
413 foreach ( $res as $row ) {
414 $ids[] = $row->bt_text_id
;
417 // Need to send enough orphan IDs to the child at a time to fill a blob,
418 // so orphanBatchSize needs to be at least ~100.
419 // batchSize can be smaller or larger.
420 while ( count( $ids ) > $this->orphanBatchSize
) {
421 $args = array_slice( $ids, 0, $this->orphanBatchSize
);
422 $ids = array_slice( $ids, $this->orphanBatchSize
);
423 array_unshift( $args, 'doOrphanList' );
424 call_user_func_array( array( $this, 'dispatch' ), $args );
426 if ( count( $ids ) ) {
428 array_unshift( $args, 'doOrphanList' );
429 call_user_func_array( array( $this, 'dispatch' ), $args );
432 $startId = $row->bt_text_id
;
433 $this->report( 'orphans', $i, $numOrphans );
435 $this->report( 'orphans', $i, $numOrphans );
436 $this->info( "All orphans queued." );
440 * Main entry point for worker processes
442 function executeChild() {
443 $this->debug( 'starting' );
446 while ( !feof( STDIN
) ) {
447 $line = rtrim( fgets( STDIN
) );
451 $this->debug( $line );
452 $args = explode( ' ', $line );
453 $cmd = array_shift( $args );
456 $this->doPage( intval( $args[0] ) );
459 $this->doOrphanList( array_map( 'intval', $args ) );
464 $this->waitForSlaves();
469 * Move tracked text in a given page
473 function doPage( $pageId ) {
474 $title = Title
::newFromID( $pageId );
476 $titleText = $title->getPrefixedText();
478 $titleText = '[deleted]';
480 $dbr = wfGetDB( DB_SLAVE
);
482 // Finish any incomplete transactions
483 if ( !$this->copyOnly
) {
484 $this->finishIncompleteMoves( array( 'bt_page' => $pageId ) );
489 $trx = new CgzCopyTransaction( $this, $this->pageBlobClass
);
493 array( 'blob_tracking', 'text' ),
496 'bt_page' => $pageId,
497 'bt_text_id > ' . $dbr->addQuotes( $startId ),
499 'bt_new_url IS NULL',
504 'ORDER BY' => 'bt_text_id',
505 'LIMIT' => $this->batchSize
508 if ( !$res->numRows() ) {
513 foreach ( $res as $row ) {
514 if ( $lastTextId == $row->bt_text_id
) {
515 // Duplicate (null edit)
518 $lastTextId = $row->bt_text_id
;
520 $text = Revision
::getRevisionText( $row );
521 if ( $text === false ) {
522 $this->critical( "Error loading {$row->bt_rev_id}/{$row->bt_text_id}" );
527 if ( !$trx->addItem( $text, $row->bt_text_id
) ) {
528 $this->debug( "$titleText: committing blob with " . $trx->getSize() . " items" );
530 $trx = new CgzCopyTransaction( $this, $this->pageBlobClass
);
531 $this->waitForSlaves();
534 $startId = $row->bt_text_id
;
537 $this->debug( "$titleText: committing blob with " . $trx->getSize() . " items" );
542 * Atomic move operation.
544 * Write the new URL to the text table and set the bt_moved flag.
546 * This is done in a single transaction to provide restartable behavior
549 * The transaction is kept short to reduce locking.
554 function moveTextRow( $textId, $url ) {
555 if ( $this->copyOnly
) {
556 $this->critical( "Internal error: can't call moveTextRow() in --copy-only mode" );
559 $dbw = wfGetDB( DB_MASTER
);
560 $dbw->begin( __METHOD__
);
561 $dbw->update( 'text',
564 'old_flags' => 'external,utf-8',
571 $dbw->update( 'blob_tracking',
572 array( 'bt_moved' => 1 ),
573 array( 'bt_text_id' => $textId ),
576 $dbw->commit( __METHOD__
);
580 * Moves are done in two phases: bt_new_url and then bt_moved.
581 * - bt_new_url indicates that the text has been copied to the new cluster.
582 * - bt_moved indicates that the text table has been updated.
584 * This function completes any moves that only have done bt_new_url. This
585 * can happen when the script is interrupted, or when --copy-only is used.
587 * @param array $conds
589 function finishIncompleteMoves( $conds ) {
590 $dbr = wfGetDB( DB_SLAVE
);
593 $conds = array_merge( $conds, array(
595 'bt_new_url IS NOT NULL'
598 $res = $dbr->select( 'blob_tracking',
600 array_merge( $conds, array( 'bt_text_id > ' . $dbr->addQuotes( $startId ) ) ),
603 'ORDER BY' => 'bt_text_id',
604 'LIMIT' => $this->batchSize
,
607 if ( !$res->numRows() ) {
610 $this->debug( 'Incomplete: ' . $res->numRows() . ' rows' );
611 foreach ( $res as $row ) {
612 $this->moveTextRow( $row->bt_text_id
, $row->bt_new_url
);
613 if ( $row->bt_text_id %
10 == 0 ) {
614 $this->waitForSlaves();
617 $startId = $row->bt_text_id
;
622 * Returns the name of the next target cluster
625 function getTargetCluster() {
626 $cluster = next( $this->destClusters
);
627 if ( $cluster === false ) {
628 $cluster = reset( $this->destClusters
);
635 * Gets a DB master connection for the given external cluster name
636 * @param string $cluster
637 * @return DatabaseBase
639 function getExtDB( $cluster ) {
640 $lb = wfGetLBFactory()->getExternalLB( $cluster );
642 return $lb->getConnection( DB_MASTER
);
646 * Move an orphan text_id to the new cluster
648 * @param array $textIds
650 function doOrphanList( $textIds ) {
651 // Finish incomplete moves
652 if ( !$this->copyOnly
) {
653 $this->finishIncompleteMoves( array( 'bt_text_id' => $textIds ) );
657 $trx = new CgzCopyTransaction( $this, $this->orphanBlobClass
);
659 $res = wfGetDB( DB_SLAVE
)->select(
660 array( 'text', 'blob_tracking' ),
661 array( 'old_id', 'old_text', 'old_flags' ),
663 'old_id' => $textIds,
671 foreach ( $res as $row ) {
672 $text = Revision
::getRevisionText( $row );
673 if ( $text === false ) {
674 $this->critical( "Error: cannot load revision text for old_id={$row->old_id}" );
678 if ( !$trx->addItem( $text, $row->old_id
) ) {
679 $this->debug( "[orphan]: committing blob with " . $trx->getSize() . " rows" );
681 $trx = new CgzCopyTransaction( $this, $this->orphanBlobClass
);
682 $this->waitForSlaves();
685 $this->debug( "[orphan]: committing blob with " . $trx->getSize() . " rows" );
690 * Wait for slaves (quietly)
692 function waitForSlaves() {
695 list( $host, $maxLag ) = $lb->getMaxLag();
705 * Class to represent a recompression operation for a single CGZ blob
707 class CgzCopyTransaction
{
714 * Create a transaction from a RecompressTracked object
715 * @param RecompressTracked $parent
716 * @param string $blobClass
718 function __construct( $parent, $blobClass ) {
719 $this->blobClass
= $blobClass;
721 $this->texts
= array();
722 $this->parent
= $parent;
727 * Returns false if it's ready to commit.
728 * @param string $text
732 function addItem( $text, $textId ) {
734 $class = $this->blobClass
;
735 $this->cgz
= new $class;
737 $hash = $this->cgz
->addItem( $text );
738 $this->referrers
[$textId] = $hash;
739 $this->texts
[$textId] = $text;
741 return $this->cgz
->isHappy();
745 return count( $this->texts
);
749 * Recompress text after some aberrant modification
751 function recompress() {
752 $class = $this->blobClass
;
753 $this->cgz
= new $class;
754 $this->referrers
= array();
755 foreach ( $this->texts
as $textId => $text ) {
756 $hash = $this->cgz
->addItem( $text );
757 $this->referrers
[$textId] = $hash;
763 * Does nothing if no text items have been added.
764 * May skip the move if --copy-only is set.
767 $originalCount = count( $this->texts
);
768 if ( !$originalCount ) {
772 // Check to see if the target text_ids have been moved already.
774 // We originally read from the slave, so this can happen when a single
775 // text_id is shared between multiple pages. It's rare, but possible
776 // if a delete/move/undelete cycle splits up a null edit.
778 // 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 array( 'bt_text_id', 'bt_moved' ),
783 array( 'bt_text_id' => array_keys( $this->referrers
) ),
784 __METHOD__
, array( '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->critical( "Warning: concurrent operation detected, are there two conflicting " .
802 "processes running, doing the same job?" );
810 // Insert the data into the destination cluster
811 $targetCluster = $this->parent
->getTargetCluster();
812 $store = $this->parent
->store
;
813 $targetDB = $store->getMaster( $targetCluster );
814 $targetDB->clearFlag( DBO_TRX
); // we manage the transactions
815 $targetDB->begin( __METHOD__
);
816 $baseUrl = $this->parent
->store
->store( $targetCluster, serialize( $this->cgz
) );
818 // Write the new URLs to the blob_tracking table
819 foreach ( $this->referrers
as $textId => $hash ) {
820 $url = $baseUrl . '/' . $hash;
821 $dbw->update( 'blob_tracking',
822 array( 'bt_new_url' => $url ),
824 'bt_text_id' => $textId,
825 'bt_moved' => 0, # Check for concurrent conflicting update
831 $targetDB->commit( __METHOD__
);
832 // Critical section here: interruption at this point causes blob duplication
833 // Reversing the order of the commits would cause data loss instead
834 $dbw->commit( __METHOD__
);
836 // Write the new URLs to the text table and set the moved flag
837 if ( !$this->parent
->copyOnly
) {
838 foreach ( $this->referrers
as $textId => $hash ) {
839 $url = $baseUrl . '/' . $hash;
840 $this->parent
->moveTextRow( $textId, $url );