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, and recompresses them in the process. Restartable.
33 --procs <procs> Set the number of child processes (default 1)
34 --copy-only Copy only, do not update the text table. Restart without this option to complete.
35 --debug-log <file> Log debugging data to the specified file
36 --info-log <file> Log progress messages to the specified file
37 --critical-log <file> Log error messages to the specified file
42 $job = RecompressTracked
::newFromCommandLine( $args, $options );
46 * Maintenance script that moves blobs indexed by trackBlobs.php to a specified
47 * list of destination clusters, and recompresses them in the process.
49 * @ingroup Maintenance ExternalStorage
51 class RecompressTracked
{
53 public $batchSize = 1000;
54 public $orphanBatchSize = 1000;
55 public $reportingInterval = 10;
57 public $useDiff, $pageBlobClass, $orphanBlobClass;
58 public $slavePipes, $slaveProcs, $prevSlaveId;
59 public $copyOnly = false;
60 public $isChild = false;
61 public $slaveId = false;
62 public $noCount = false;
63 public $debugLog, $infoLog, $criticalLog;
66 static $optionsWithArgs = array( 'procs', 'slave-id', 'debug-log', 'info-log', 'critical-log' );
67 static $cmdLineOptionMap = array(
68 'no-count' => 'noCount',
69 'procs' => 'numProcs',
70 'copy-only' => 'copyOnly',
72 'slave-id' => 'slaveId',
73 'debug-log' => 'debugLog',
74 'info-log' => 'infoLog',
75 'critical-log' => 'criticalLog',
78 static function getOptionsWithArgs() {
79 return self
::$optionsWithArgs;
82 static function newFromCommandLine( $args, $options ) {
83 $jobOptions = array( 'destClusters' => $args );
84 foreach ( self
::$cmdLineOptionMap as $cmdOption => $classOption ) {
85 if ( isset( $options[$cmdOption] ) ) {
86 $jobOptions[$classOption] = $options[$cmdOption];
89 return new self( $jobOptions );
92 function __construct( $options ) {
93 foreach ( $options as $name => $value ) {
94 $this->$name = $value;
96 $this->store
= new ExternalStoreDB
;
97 if ( !$this->isChild
) {
98 $GLOBALS['wgDebugLogPrefix'] = "RCT M: ";
99 } elseif ( $this->slaveId
!== false ) {
100 $GLOBALS['wgDebugLogPrefix'] = "RCT {$this->slaveId}: ";
102 $this->useDiff
= function_exists( 'xdiff_string_bdiff' );
103 $this->pageBlobClass
= $this->useDiff ?
'DiffHistoryBlob' : 'ConcatenatedGzipHistoryBlob';
104 $this->orphanBlobClass
= 'ConcatenatedGzipHistoryBlob';
107 function debug( $msg ) {
109 if ( $this->debugLog
) {
110 $this->logToFile( $msg, $this->debugLog
);
115 function info( $msg ) {
117 if ( $this->infoLog
) {
118 $this->logToFile( $msg, $this->infoLog
);
122 function critical( $msg ) {
124 if ( $this->criticalLog
) {
125 $this->logToFile( $msg, $this->criticalLog
);
129 function logToFile( $msg, $file ) {
130 $header = '[' . date( 'd\TH:i:s' ) . '] ' . wfHostname() . ' ' . posix_getpid();
131 if ( $this->slaveId
!== false ) {
132 $header .= "({$this->slaveId})";
134 $header .= ' ' . wfWikiID();
135 wfErrorLog( sprintf( "%-50s %s\n", $header, $msg ), $file );
139 * Wait until the selected slave has caught up to the master.
140 * This allows us to use the slave for things that were committed in a
141 * previous part of this batch process.
144 $dbw = wfGetDB( DB_MASTER
);
145 $dbr = wfGetDB( DB_SLAVE
);
146 $pos = $dbw->getMasterPos();
147 $dbr->masterPosWait( $pos, 100000 );
151 * Execute parent or child depending on the isChild option
154 if ( $this->isChild
) {
155 $this->executeChild();
157 $this->executeParent();
162 * Execute the parent process
164 function executeParent() {
165 if ( !$this->checkTrackingTable() ) {
170 $this->startSlaveProcs();
172 $this->doAllOrphans();
173 $this->killSlaveProcs();
177 * Make sure the tracking table exists and isn't empty
180 function checkTrackingTable() {
181 $dbr = wfGetDB( DB_SLAVE
);
182 if ( !$dbr->tableExists( 'blob_tracking' ) ) {
183 $this->critical( "Error: blob_tracking table does not exist" );
186 $row = $dbr->selectRow( 'blob_tracking', '*', false, __METHOD__
);
188 $this->info( "Warning: blob_tracking table contains no rows, skipping this wiki." );
195 * Start the worker processes.
196 * These processes will listen on stdin for commands.
197 * This necessary because text recompression is slow: loading, compressing and
198 * writing are all slow.
200 function startSlaveProcs() {
201 $cmd = 'php ' . wfEscapeShellArg( __FILE__
);
202 foreach ( self
::$cmdLineOptionMap as $cmdOption => $classOption ) {
203 if ( $cmdOption == 'slave-id' ) {
205 } elseif ( in_array( $cmdOption, self
::$optionsWithArgs ) && isset( $this->$classOption ) ) {
206 $cmd .= " --$cmdOption " . wfEscapeShellArg( $this->$classOption );
207 } elseif ( $this->$classOption ) {
208 $cmd .= " --$cmdOption";
212 ' --wiki ' . wfEscapeShellArg( wfWikiID() ) .
213 ' ' . call_user_func_array( 'wfEscapeShellArg', $this->destClusters
);
215 $this->slavePipes
= $this->slaveProcs
= array();
216 for ( $i = 0; $i < $this->numProcs
; $i++
) {
219 array( 'pipe', 'r' ),
220 array( 'file', 'php://stdout', 'w' ),
221 array( 'file', 'php://stderr', 'w' )
223 wfSuppressWarnings();
224 $proc = proc_open( "$cmd --slave-id $i", $spec, $pipes );
227 $this->critical( "Error opening slave process: $cmd" );
230 $this->slaveProcs
[$i] = $proc;
231 $this->slavePipes
[$i] = $pipes[0];
233 $this->prevSlaveId
= -1;
237 * Gracefully terminate the child processes
239 function killSlaveProcs() {
240 $this->info( "Waiting for slave processes to finish..." );
241 for ( $i = 0; $i < $this->numProcs
; $i++
) {
242 $this->dispatchToSlave( $i, 'quit' );
244 for ( $i = 0; $i < $this->numProcs
; $i++
) {
245 $status = proc_close( $this->slaveProcs
[$i] );
247 $this->critical( "Warning: child #$i exited with status $status" );
250 $this->info( "Done." );
254 * Dispatch a command to the next available slave.
255 * This may block until a slave finishes its work and becomes available.
257 function dispatch( /*...*/ ) {
258 $args = func_get_args();
259 $pipes = $this->slavePipes
;
260 $numPipes = stream_select( $x = array(), $pipes, $y = array(), 3600 );
262 $this->critical( "Error waiting to write to slaves. Aborting" );
265 for ( $i = 0; $i < $this->numProcs
; $i++
) {
266 $slaveId = ( $i +
$this->prevSlaveId +
1 ) %
$this->numProcs
;
267 if ( isset( $pipes[$slaveId] ) ) {
268 $this->prevSlaveId
= $slaveId;
269 $this->dispatchToSlave( $slaveId, $args );
273 $this->critical( "Unreachable" );
278 * Dispatch a command to a specified slave
280 function dispatchToSlave( $slaveId, $args ) {
281 $args = (array)$args;
282 $cmd = implode( ' ', $args );
283 fwrite( $this->slavePipes
[$slaveId], "$cmd\n" );
287 * Move all tracked pages to the new clusters
289 function doAllPages() {
290 $dbr = wfGetDB( DB_SLAVE
);
293 if ( $this->noCount
) {
294 $numPages = '[unknown]';
296 $numPages = $dbr->selectField( 'blob_tracking',
297 'COUNT(DISTINCT bt_page)',
298 # A condition is required so that this query uses the index
299 array( 'bt_moved' => 0 ),
303 if ( $this->copyOnly
) {
304 $this->info( "Copying pages..." );
306 $this->info( "Moving pages..." );
309 $res = $dbr->select( 'blob_tracking',
313 'bt_page > ' . $dbr->addQuotes( $startId )
318 'ORDER BY' => 'bt_page',
319 'LIMIT' => $this->batchSize
,
322 if ( !$res->numRows() ) {
325 foreach ( $res as $row ) {
326 $this->dispatch( 'doPage', $row->bt_page
);
329 $startId = $row->bt_page
;
330 $this->report( 'pages', $i, $numPages );
332 $this->report( 'pages', $i, $numPages );
333 if ( $this->copyOnly
) {
334 $this->info( "All page copies queued." );
336 $this->info( "All page moves queued." );
341 * Display a progress report
343 function report( $label, $current, $end ) {
345 if ( $current == $end ||
$this->numBatches
>= $this->reportingInterval
) {
346 $this->numBatches
= 0;
347 $this->info( "$label: $current / $end" );
348 $this->waitForSlaves();
353 * Move all orphan text to the new clusters
355 function doAllOrphans() {
356 $dbr = wfGetDB( DB_SLAVE
);
359 if ( $this->noCount
) {
360 $numOrphans = '[unknown]';
362 $numOrphans = $dbr->selectField( 'blob_tracking',
363 'COUNT(DISTINCT bt_text_id)',
364 array( 'bt_moved' => 0, 'bt_page' => 0 ),
366 if ( !$numOrphans ) {
370 if ( $this->copyOnly
) {
371 $this->info( "Copying orphans..." );
373 $this->info( "Moving orphans..." );
377 $res = $dbr->select( 'blob_tracking',
378 array( 'bt_text_id' ),
382 'bt_text_id > ' . $dbr->addQuotes( $startId )
387 'ORDER BY' => 'bt_text_id',
388 'LIMIT' => $this->batchSize
391 if ( !$res->numRows() ) {
395 foreach ( $res as $row ) {
396 $ids[] = $row->bt_text_id
;
399 // Need to send enough orphan IDs to the child at a time to fill a blob,
400 // so orphanBatchSize needs to be at least ~100.
401 // batchSize can be smaller or larger.
402 while ( count( $ids ) > $this->orphanBatchSize
) {
403 $args = array_slice( $ids, 0, $this->orphanBatchSize
);
404 $ids = array_slice( $ids, $this->orphanBatchSize
);
405 array_unshift( $args, 'doOrphanList' );
406 call_user_func_array( array( $this, 'dispatch' ), $args );
408 if ( count( $ids ) ) {
410 array_unshift( $args, 'doOrphanList' );
411 call_user_func_array( array( $this, 'dispatch' ), $args );
414 $startId = $row->bt_text_id
;
415 $this->report( 'orphans', $i, $numOrphans );
417 $this->report( 'orphans', $i, $numOrphans );
418 $this->info( "All orphans queued." );
422 * Main entry point for worker processes
424 function executeChild() {
425 $this->debug( 'starting' );
428 while ( !feof( STDIN
) ) {
429 $line = rtrim( fgets( STDIN
) );
433 $this->debug( $line );
434 $args = explode( ' ', $line );
435 $cmd = array_shift( $args );
438 $this->doPage( intval( $args[0] ) );
441 $this->doOrphanList( array_map( 'intval', $args ) );
446 $this->waitForSlaves();
451 * Move tracked text in a given page
453 function doPage( $pageId ) {
454 $title = Title
::newFromId( $pageId );
456 $titleText = $title->getPrefixedText();
458 $titleText = '[deleted]';
460 $dbr = wfGetDB( DB_SLAVE
);
462 // Finish any incomplete transactions
463 if ( !$this->copyOnly
) {
464 $this->finishIncompleteMoves( array( 'bt_page' => $pageId ) );
469 $trx = new CgzCopyTransaction( $this, $this->pageBlobClass
);
473 array( 'blob_tracking', 'text' ),
476 'bt_page' => $pageId,
477 'bt_text_id > ' . $dbr->addQuotes( $startId ),
479 'bt_new_url IS NULL',
484 'ORDER BY' => 'bt_text_id',
485 'LIMIT' => $this->batchSize
488 if ( !$res->numRows() ) {
493 foreach ( $res as $row ) {
494 if ( $lastTextId == $row->bt_text_id
) {
495 // Duplicate (null edit)
498 $lastTextId = $row->bt_text_id
;
500 $text = Revision
::getRevisionText( $row );
501 if ( $text === false ) {
502 $this->critical( "Error loading {$row->bt_rev_id}/{$row->bt_text_id}" );
507 if ( !$trx->addItem( $text, $row->bt_text_id
) ) {
508 $this->debug( "$titleText: committing blob with " . $trx->getSize() . " items" );
510 $trx = new CgzCopyTransaction( $this, $this->pageBlobClass
);
511 $this->waitForSlaves();
514 $startId = $row->bt_text_id
;
517 $this->debug( "$titleText: committing blob with " . $trx->getSize() . " items" );
522 * Atomic move operation.
524 * Write the new URL to the text table and set the bt_moved flag.
526 * This is done in a single transaction to provide restartable behavior
529 * The transaction is kept short to reduce locking.
531 function moveTextRow( $textId, $url ) {
532 if ( $this->copyOnly
) {
533 $this->critical( "Internal error: can't call moveTextRow() in --copy-only mode" );
536 $dbw = wfGetDB( DB_MASTER
);
537 $dbw->begin( __METHOD__
);
538 $dbw->update( 'text',
541 'old_flags' => 'external,utf-8',
548 $dbw->update( 'blob_tracking',
549 array( 'bt_moved' => 1 ),
550 array( 'bt_text_id' => $textId ),
553 $dbw->commit( __METHOD__
);
557 * Moves are done in two phases: bt_new_url and then bt_moved.
558 * - bt_new_url indicates that the text has been copied to the new cluster.
559 * - bt_moved indicates that the text table has been updated.
561 * This function completes any moves that only have done bt_new_url. This
562 * can happen when the script is interrupted, or when --copy-only is used.
564 function finishIncompleteMoves( $conds ) {
565 $dbr = wfGetDB( DB_SLAVE
);
568 $conds = array_merge( $conds, array(
570 'bt_new_url IS NOT NULL'
573 $res = $dbr->select( 'blob_tracking',
575 array_merge( $conds, array( 'bt_text_id > ' . $dbr->addQuotes( $startId ) ) ),
578 'ORDER BY' => 'bt_text_id',
579 'LIMIT' => $this->batchSize
,
582 if ( !$res->numRows() ) {
585 $this->debug( 'Incomplete: ' . $res->numRows() . ' rows' );
586 foreach ( $res as $row ) {
587 $this->moveTextRow( $row->bt_text_id
, $row->bt_new_url
);
588 if ( $row->bt_text_id %
10 == 0 ) {
589 $this->waitForSlaves();
592 $startId = $row->bt_text_id
;
597 * Returns the name of the next target cluster
600 function getTargetCluster() {
601 $cluster = next( $this->destClusters
);
602 if ( $cluster === false ) {
603 $cluster = reset( $this->destClusters
);
609 * Gets a DB master connection for the given external cluster name
610 * @param $cluster string
611 * @return DatabaseBase
613 function getExtDB( $cluster ) {
614 $lb = wfGetLBFactory()->getExternalLB( $cluster );
615 return $lb->getConnection( DB_MASTER
);
619 * Move an orphan text_id to the new cluster
621 function doOrphanList( $textIds ) {
622 // Finish incomplete moves
623 if ( !$this->copyOnly
) {
624 $this->finishIncompleteMoves( array( 'bt_text_id' => $textIds ) );
628 $trx = new CgzCopyTransaction( $this, $this->orphanBlobClass
);
630 $res = wfGetDB( DB_SLAVE
)->select(
631 array( 'text', 'blob_tracking' ),
632 array( 'old_id', 'old_text', 'old_flags' ),
634 'old_id' => $textIds,
642 foreach ( $res as $row ) {
643 $text = Revision
::getRevisionText( $row );
644 if ( $text === false ) {
645 $this->critical( "Error: cannot load revision text for old_id={$row->old_id}" );
649 if ( !$trx->addItem( $text, $row->old_id
) ) {
650 $this->debug( "[orphan]: committing blob with " . $trx->getSize() . " rows" );
652 $trx = new CgzCopyTransaction( $this, $this->orphanBlobClass
);
653 $this->waitForSlaves();
656 $this->debug( "[orphan]: committing blob with " . $trx->getSize() . " rows" );
661 * Wait for slaves (quietly)
663 function waitForSlaves() {
666 list( $host, $maxLag ) = $lb->getMaxLag();
676 * Class to represent a recompression operation for a single CGZ blob
678 class CgzCopyTransaction
{
685 * Create a transaction from a RecompressTracked object
687 function __construct( $parent, $blobClass ) {
688 $this->blobClass
= $blobClass;
690 $this->texts
= array();
691 $this->parent
= $parent;
696 * Returns false if it's ready to commit.
697 * @param $text string
701 function addItem( $text, $textId ) {
703 $class = $this->blobClass
;
704 $this->cgz
= new $class;
706 $hash = $this->cgz
->addItem( $text );
707 $this->referrers
[$textId] = $hash;
708 $this->texts
[$textId] = $text;
709 return $this->cgz
->isHappy();
713 return count( $this->texts
);
717 * Recompress text after some aberrant modification
719 function recompress() {
720 $class = $this->blobClass
;
721 $this->cgz
= new $class;
722 $this->referrers
= array();
723 foreach ( $this->texts
as $textId => $text ) {
724 $hash = $this->cgz
->addItem( $text );
725 $this->referrers
[$textId] = $hash;
731 * Does nothing if no text items have been added.
732 * May skip the move if --copy-only is set.
735 $originalCount = count( $this->texts
);
736 if ( !$originalCount ) {
740 // Check to see if the target text_ids have been moved already.
742 // We originally read from the slave, so this can happen when a single
743 // text_id is shared between multiple pages. It's rare, but possible
744 // if a delete/move/undelete cycle splits up a null edit.
746 // We do a locking read to prevent closer-run race conditions.
747 $dbw = wfGetDB( DB_MASTER
);
748 $dbw->begin( __METHOD__
);
749 $res = $dbw->select( 'blob_tracking',
750 array( 'bt_text_id', 'bt_moved' ),
751 array( 'bt_text_id' => array_keys( $this->referrers
) ),
752 __METHOD__
, array( 'FOR UPDATE' ) );
754 foreach ( $res as $row ) {
755 if ( $row->bt_moved
) {
756 # This row has already been moved, remove it
757 $this->parent
->debug( "TRX: conflict detected in old_id={$row->bt_text_id}" );
758 unset( $this->texts
[$row->bt_text_id
] );
763 // Recompress the blob if necessary
765 if ( !count( $this->texts
) ) {
766 // All have been moved already
767 if ( $originalCount > 1 ) {
768 // This is suspcious, make noise
769 $this->critical( "Warning: concurrent operation detected, are there two conflicting " .
770 "processes running, doing the same job?" );
777 // Insert the data into the destination cluster
778 $targetCluster = $this->parent
->getTargetCluster();
779 $store = $this->parent
->store
;
780 $targetDB = $store->getMaster( $targetCluster );
781 $targetDB->clearFlag( DBO_TRX
); // we manage the transactions
782 $targetDB->begin( __METHOD__
);
783 $baseUrl = $this->parent
->store
->store( $targetCluster, serialize( $this->cgz
) );
785 // Write the new URLs to the blob_tracking table
786 foreach ( $this->referrers
as $textId => $hash ) {
787 $url = $baseUrl . '/' . $hash;
788 $dbw->update( 'blob_tracking',
789 array( 'bt_new_url' => $url ),
791 'bt_text_id' => $textId,
792 'bt_moved' => 0, # Check for concurrent conflicting update
798 $targetDB->commit( __METHOD__
);
799 // Critical section here: interruption at this point causes blob duplication
800 // Reversing the order of the commits would cause data loss instead
801 $dbw->commit( __METHOD__
);
803 // Write the new URLs to the text table and set the moved flag
804 if ( !$this->parent
->copyOnly
) {
805 foreach ( $this->referrers
as $textId => $hash ) {
806 $url = $baseUrl . '/' . $hash;
807 $this->parent
->moveTextRow( $textId, $url );