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( dirname( __FILE__
) . '/../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 );
45 class RecompressTracked
{
47 var $batchSize = 1000;
48 var $orphanBatchSize = 1000;
49 var $reportingInterval = 10;
51 var $useDiff, $pageBlobClass, $orphanBlobClass;
52 var $slavePipes, $slaveProcs, $prevSlaveId;
53 var $copyOnly = false;
57 var $debugLog, $infoLog, $criticalLog;
60 static $optionsWithArgs = array( 'procs', 'slave-id', 'debug-log', 'info-log', 'critical-log' );
61 static $cmdLineOptionMap = array(
62 'no-count' => 'noCount',
63 'procs' => 'numProcs',
64 'copy-only' => 'copyOnly',
66 'slave-id' => 'slaveId',
67 'debug-log' => 'debugLog',
68 'info-log' => 'infoLog',
69 'critical-log' => 'criticalLog',
72 static function getOptionsWithArgs() {
73 return self
::$optionsWithArgs;
76 static function newFromCommandLine( $args, $options ) {
77 $jobOptions = array( 'destClusters' => $args );
78 foreach ( self
::$cmdLineOptionMap as $cmdOption => $classOption ) {
79 if ( isset( $options[$cmdOption] ) ) {
80 $jobOptions[$classOption] = $options[$cmdOption];
83 return new self( $jobOptions );
86 function __construct( $options ) {
87 foreach ( $options as $name => $value ) {
88 $this->$name = $value;
90 $this->store
= new ExternalStoreDB
;
91 if ( !$this->isChild
) {
92 $GLOBALS['wgDebugLogPrefix'] = "RCT M: ";
93 } elseif ( $this->slaveId
!== false ) {
94 $GLOBALS['wgDebugLogPrefix'] = "RCT {$this->slaveId}: ";
96 $this->useDiff
= function_exists( 'xdiff_string_bdiff' );
97 $this->pageBlobClass
= $this->useDiff ?
'DiffHistoryBlob' : 'ConcatenatedGzipHistoryBlob';
98 $this->orphanBlobClass
= 'ConcatenatedGzipHistoryBlob';
101 function debug( $msg ) {
103 if ( $this->debugLog
) {
104 $this->logToFile( $msg, $this->debugLog
);
109 function info( $msg ) {
111 if ( $this->infoLog
) {
112 $this->logToFile( $msg, $this->infoLog
);
116 function critical( $msg ) {
118 if ( $this->criticalLog
) {
119 $this->logToFile( $msg, $this->criticalLog
);
123 function logToFile( $msg, $file ) {
124 $header = '[' . date( 'd\TH:i:s' ) . '] ' . wfHostname() . ' ' . posix_getpid();
125 if ( $this->slaveId
!== false ) {
126 $header .= "({$this->slaveId})";
128 $header .= ' ' . wfWikiID();
129 wfErrorLog( sprintf( "%-50s %s\n", $header, $msg ), $file );
133 * Wait until the selected slave has caught up to the master.
134 * This allows us to use the slave for things that were committed in a
135 * previous part of this batch process.
138 $dbw = wfGetDB( DB_MASTER
);
139 $dbr = wfGetDB( DB_SLAVE
);
140 $pos = $dbw->getMasterPos();
141 $dbr->masterPosWait( $pos, 100000 );
145 * Execute parent or child depending on the isChild option
148 if ( $this->isChild
) {
149 $this->executeChild();
151 $this->executeParent();
156 * Execute the parent process
158 function executeParent() {
159 if ( !$this->checkTrackingTable() ) {
164 $this->startSlaveProcs();
166 $this->doAllOrphans();
167 $this->killSlaveProcs();
171 * Make sure the tracking table exists and isn't empty
173 function checkTrackingTable() {
174 $dbr = wfGetDB( DB_SLAVE
);
175 if ( !$dbr->tableExists( 'blob_tracking' ) ) {
176 $this->critical( "Error: blob_tracking table does not exist" );
179 $row = $dbr->selectRow( 'blob_tracking', '*', false, __METHOD__
);
181 $this->info( "Warning: blob_tracking table contains no rows, skipping this wiki." );
188 * Start the worker processes.
189 * These processes will listen on stdin for commands.
190 * This necessary because text recompression is slow: loading, compressing and
191 * writing are all slow.
193 function startSlaveProcs() {
194 $cmd = 'php ' . wfEscapeShellArg( __FILE__
);
195 foreach ( self
::$cmdLineOptionMap as $cmdOption => $classOption ) {
196 if ( $cmdOption == 'slave-id' ) {
198 } elseif ( in_array( $cmdOption, self
::$optionsWithArgs ) && isset( $this->$classOption ) ) {
199 $cmd .= " --$cmdOption " . wfEscapeShellArg( $this->$classOption );
200 } elseif ( $this->$classOption ) {
201 $cmd .= " --$cmdOption";
205 ' --wiki ' . wfEscapeShellArg( wfWikiID() ) .
206 ' ' . call_user_func_array( 'wfEscapeShellArg', $this->destClusters
);
208 $this->slavePipes
= $this->slaveProcs
= array();
209 for ( $i = 0; $i < $this->numProcs
; $i++
) {
212 array( 'pipe', 'r' ),
213 array( 'file', 'php://stdout', 'w' ),
214 array( 'file', 'php://stderr', 'w' )
216 wfSuppressWarnings();
217 $proc = proc_open( "$cmd --slave-id $i", $spec, $pipes );
220 $this->critical( "Error opening slave process: $cmd" );
223 $this->slaveProcs
[$i] = $proc;
224 $this->slavePipes
[$i] = $pipes[0];
226 $this->prevSlaveId
= -1;
230 * Gracefully terminate the child processes
232 function killSlaveProcs() {
233 $this->info( "Waiting for slave processes to finish..." );
234 for ( $i = 0; $i < $this->numProcs
; $i++
) {
235 $this->dispatchToSlave( $i, 'quit' );
237 for ( $i = 0; $i < $this->numProcs
; $i++
) {
238 $status = proc_close( $this->slaveProcs
[$i] );
240 $this->critical( "Warning: child #$i exited with status $status" );
243 $this->info( "Done." );
247 * Dispatch a command to the next available slave.
248 * This may block until a slave finishes its work and becomes available.
250 function dispatch( /*...*/ ) {
251 $args = func_get_args();
252 $pipes = $this->slavePipes
;
253 $numPipes = stream_select( $x = array(), $pipes, $y = array(), 3600 );
255 $this->critical( "Error waiting to write to slaves. Aborting" );
258 for ( $i = 0; $i < $this->numProcs
; $i++
) {
259 $slaveId = ( $i +
$this->prevSlaveId +
1 ) %
$this->numProcs
;
260 if ( isset( $pipes[$slaveId] ) ) {
261 $this->prevSlaveId
= $slaveId;
262 $this->dispatchToSlave( $slaveId, $args );
266 $this->critical( "Unreachable" );
271 * Dispatch a command to a specified slave
273 function dispatchToSlave( $slaveId, $args ) {
274 $args = (array)$args;
275 $cmd = implode( ' ', $args );
276 fwrite( $this->slavePipes
[$slaveId], "$cmd\n" );
280 * Move all tracked pages to the new clusters
282 function doAllPages() {
283 $dbr = wfGetDB( DB_SLAVE
);
286 if ( $this->noCount
) {
287 $numPages = '[unknown]';
289 $numPages = $dbr->selectField( 'blob_tracking',
290 'COUNT(DISTINCT bt_page)',
291 # A condition is required so that this query uses the index
292 array( 'bt_moved' => 0 ),
296 if ( $this->copyOnly
) {
297 $this->info( "Copying pages..." );
299 $this->info( "Moving pages..." );
302 $res = $dbr->select( 'blob_tracking',
306 'bt_page > ' . $dbr->addQuotes( $startId )
311 'ORDER BY' => 'bt_page',
312 'LIMIT' => $this->batchSize
,
315 if ( !$res->numRows() ) {
318 foreach ( $res as $row ) {
319 $this->dispatch( 'doPage', $row->bt_page
);
322 $startId = $row->bt_page
;
323 $this->report( 'pages', $i, $numPages );
325 $this->report( 'pages', $i, $numPages );
326 if ( $this->copyOnly
) {
327 $this->info( "All page copies queued." );
329 $this->info( "All page moves queued." );
334 * Display a progress report
336 function report( $label, $current, $end ) {
338 if ( $current == $end ||
$this->numBatches
>= $this->reportingInterval
) {
339 $this->numBatches
= 0;
340 $this->info( "$label: $current / $end" );
341 $this->waitForSlaves();
346 * Move all orphan text to the new clusters
348 function doAllOrphans() {
349 $dbr = wfGetDB( DB_SLAVE
);
352 if ( $this->noCount
) {
353 $numOrphans = '[unknown]';
355 $numOrphans = $dbr->selectField( 'blob_tracking',
356 'COUNT(DISTINCT bt_text_id)',
357 array( 'bt_moved' => 0, 'bt_page' => 0 ),
359 if ( !$numOrphans ) {
363 if ( $this->copyOnly
) {
364 $this->info( "Copying orphans..." );
366 $this->info( "Moving orphans..." );
370 $res = $dbr->select( 'blob_tracking',
371 array( 'bt_text_id' ),
375 'bt_text_id > ' . $dbr->addQuotes( $startId )
380 'ORDER BY' => 'bt_text_id',
381 'LIMIT' => $this->batchSize
384 if ( !$res->numRows() ) {
388 foreach ( $res as $row ) {
389 $ids[] = $row->bt_text_id
;
392 // Need to send enough orphan IDs to the child at a time to fill a blob,
393 // so orphanBatchSize needs to be at least ~100.
394 // batchSize can be smaller or larger.
395 while ( count( $ids ) > $this->orphanBatchSize
) {
396 $args = array_slice( $ids, 0, $this->orphanBatchSize
);
397 $ids = array_slice( $ids, $this->orphanBatchSize
);
398 array_unshift( $args, 'doOrphanList' );
399 call_user_func_array( array( $this, 'dispatch' ), $args );
401 if ( count( $ids ) ) {
403 array_unshift( $args, 'doOrphanList' );
404 call_user_func_array( array( $this, 'dispatch' ), $args );
407 $startId = $row->bt_text_id
;
408 $this->report( 'orphans', $i, $numOrphans );
410 $this->report( 'orphans', $i, $numOrphans );
411 $this->info( "All orphans queued." );
415 * Main entry point for worker processes
417 function executeChild() {
418 $this->debug( 'starting' );
421 while ( !feof( STDIN
) ) {
422 $line = rtrim( fgets( STDIN
) );
426 $this->debug( $line );
427 $args = explode( ' ', $line );
428 $cmd = array_shift( $args );
431 $this->doPage( intval( $args[0] ) );
434 $this->doOrphanList( array_map( 'intval', $args ) );
439 $this->waitForSlaves();
444 * Move tracked text in a given page
446 function doPage( $pageId ) {
447 $title = Title
::newFromId( $pageId );
449 $titleText = $title->getPrefixedText();
451 $titleText = '[deleted]';
453 $dbr = wfGetDB( DB_SLAVE
);
455 // Finish any incomplete transactions
456 if ( !$this->copyOnly
) {
457 $this->finishIncompleteMoves( array( 'bt_page' => $pageId ) );
462 $trx = new CgzCopyTransaction( $this, $this->pageBlobClass
);
466 array( 'blob_tracking', 'text' ),
469 'bt_page' => $pageId,
470 'bt_text_id > ' . $dbr->addQuotes( $startId ),
472 'bt_new_url IS NULL',
477 'ORDER BY' => 'bt_text_id',
478 'LIMIT' => $this->batchSize
481 if ( !$res->numRows() ) {
486 foreach ( $res as $row ) {
487 if ( $lastTextId == $row->bt_text_id
) {
488 // Duplicate (null edit)
491 $lastTextId = $row->bt_text_id
;
493 $text = Revision
::getRevisionText( $row );
494 if ( $text === false ) {
495 $this->critical( "Error loading {$row->bt_rev_id}/{$row->bt_text_id}" );
500 if ( !$trx->addItem( $text, $row->bt_text_id
) ) {
501 $this->debug( "$titleText: committing blob with " . $trx->getSize() . " items" );
503 $trx = new CgzCopyTransaction( $this, $this->pageBlobClass
);
504 $this->waitForSlaves();
507 $startId = $row->bt_text_id
;
510 $this->debug( "$titleText: committing blob with " . $trx->getSize() . " items" );
515 * Atomic move operation.
517 * Write the new URL to the text table and set the bt_moved flag.
519 * This is done in a single transaction to provide restartable behaviour
522 * The transaction is kept short to reduce locking.
524 function moveTextRow( $textId, $url ) {
525 if ( $this->copyOnly
) {
526 $this->critical( "Internal error: can't call moveTextRow() in --copy-only mode" );
529 $dbw = wfGetDB( DB_MASTER
);
531 $dbw->update( 'text',
534 'old_flags' => 'external,utf-8',
541 $dbw->update( 'blob_tracking',
542 array( 'bt_moved' => 1 ),
543 array( 'bt_text_id' => $textId ),
550 * Moves are done in two phases: bt_new_url and then bt_moved.
551 * - bt_new_url indicates that the text has been copied to the new cluster.
552 * - bt_moved indicates that the text table has been updated.
554 * This function completes any moves that only have done bt_new_url. This
555 * can happen when the script is interrupted, or when --copy-only is used.
557 function finishIncompleteMoves( $conds ) {
558 $dbr = wfGetDB( DB_SLAVE
);
561 $conds = array_merge( $conds, array(
563 'bt_new_url IS NOT NULL'
566 $res = $dbr->select( 'blob_tracking',
568 array_merge( $conds, array( 'bt_text_id > ' . $dbr->addQuotes( $startId ) ) ),
571 'ORDER BY' => 'bt_text_id',
572 'LIMIT' => $this->batchSize
,
575 if ( !$res->numRows() ) {
578 $this->debug( 'Incomplete: ' . $res->numRows() . ' rows' );
579 foreach ( $res as $row ) {
580 $this->moveTextRow( $row->bt_text_id
, $row->bt_new_url
);
581 if ( $row->bt_text_id %
10 == 0 ) {
582 $this->waitForSlaves();
585 $startId = $row->bt_text_id
;
590 * Returns the name of the next target cluster
592 function getTargetCluster() {
593 $cluster = next( $this->destClusters
);
594 if ( $cluster === false ) {
595 $cluster = reset( $this->destClusters
);
601 * Gets a DB master connection for the given external cluster name
603 function getExtDB( $cluster ) {
604 $lb = wfGetLBFactory()->getExternalLB( $cluster );
605 return $lb->getConnection( DB_MASTER
);
609 * Move an orphan text_id to the new cluster
611 function doOrphanList( $textIds ) {
612 // Finish incomplete moves
613 if ( !$this->copyOnly
) {
614 $this->finishIncompleteMoves( array( 'bt_text_id' => $textIds ) );
618 $trx = new CgzCopyTransaction( $this, $this->orphanBlobClass
);
620 $res = wfGetDB( DB_SLAVE
)->select(
621 array( 'text', 'blob_tracking' ),
622 array( 'old_id', 'old_text', 'old_flags' ),
624 'old_id' => $textIds,
632 foreach ( $res as $row ) {
633 $text = Revision
::getRevisionText( $row );
634 if ( $text === false ) {
635 $this->critical( "Error: cannot load revision text for old_id={$row->old_id}" );
639 if ( !$trx->addItem( $text, $row->old_id
) ) {
640 $this->debug( "[orphan]: committing blob with " . $trx->getSize() . " rows" );
642 $trx = new CgzCopyTransaction( $this, $this->orphanBlobClass
);
643 $this->waitForSlaves();
646 $this->debug( "[orphan]: committing blob with " . $trx->getSize() . " rows" );
651 * Wait for slaves (quietly)
653 function waitForSlaves() {
656 list( $host, $maxLag ) = $lb->getMaxLag();
666 * Class to represent a recompression operation for a single CGZ blob
668 class CgzCopyTransaction
{
675 * Create a transaction from a RecompressTracked object
677 function __construct( $parent, $blobClass ) {
678 $this->blobClass
= $blobClass;
680 $this->texts
= array();
681 $this->parent
= $parent;
686 * Returns false if it's ready to commit.
688 function addItem( $text, $textId ) {
690 $class = $this->blobClass
;
691 $this->cgz
= new $class;
693 $hash = $this->cgz
->addItem( $text );
694 $this->referrers
[$textId] = $hash;
695 $this->texts
[$textId] = $text;
696 return $this->cgz
->isHappy();
700 return count( $this->texts
);
704 * Recompress text after some aberrant modification
706 function recompress() {
707 $class = $this->blobClass
;
708 $this->cgz
= new $class;
709 $this->referrers
= array();
710 foreach ( $this->texts
as $textId => $text ) {
711 $hash = $this->cgz
->addItem( $text );
712 $this->referrers
[$textId] = $hash;
718 * Does nothing if no text items have been added.
719 * May skip the move if --copy-only is set.
722 $originalCount = count( $this->texts
);
723 if ( !$originalCount ) {
727 // Check to see if the target text_ids have been moved already.
729 // We originally read from the slave, so this can happen when a single
730 // text_id is shared between multiple pages. It's rare, but possible
731 // if a delete/move/undelete cycle splits up a null edit.
733 // We do a locking read to prevent closer-run race conditions.
734 $dbw = wfGetDB( DB_MASTER
);
736 $res = $dbw->select( 'blob_tracking',
737 array( 'bt_text_id', 'bt_moved' ),
738 array( 'bt_text_id' => array_keys( $this->referrers
) ),
739 __METHOD__
, array( 'FOR UPDATE' ) );
741 foreach ( $res as $row ) {
742 if ( $row->bt_moved
) {
743 # This row has already been moved, remove it
744 $this->parent
->debug( "TRX: conflict detected in old_id={$row->bt_text_id}" );
745 unset( $this->texts
[$row->bt_text_id
] );
750 // Recompress the blob if necessary
752 if ( !count( $this->texts
) ) {
753 // All have been moved already
754 if ( $originalCount > 1 ) {
755 // This is suspcious, make noise
756 $this->critical( "Warning: concurrent operation detected, are there two conflicting " .
757 "processes running, doing the same job?" );
764 // Insert the data into the destination cluster
765 $targetCluster = $this->parent
->getTargetCluster();
766 $store = $this->parent
->store
;
767 $targetDB = $store->getMaster( $targetCluster );
768 $targetDB->clearFlag( DBO_TRX
); // we manage the transactions
770 $baseUrl = $this->parent
->store
->store( $targetCluster, serialize( $this->cgz
) );
772 // Write the new URLs to the blob_tracking table
773 foreach ( $this->referrers
as $textId => $hash ) {
774 $url = $baseUrl . '/' . $hash;
775 $dbw->update( 'blob_tracking',
776 array( 'bt_new_url' => $url ),
778 'bt_text_id' => $textId,
779 'bt_moved' => 0, # Check for concurrent conflicting update
786 // Critical section here: interruption at this point causes blob duplication
787 // Reversing the order of the commits would cause data loss instead
790 // Write the new URLs to the text table and set the moved flag
791 if ( !$this->parent
->copyOnly
) {
792 foreach ( $this->referrers
as $textId => $hash ) {
793 $url = $baseUrl . '/' . $hash;
794 $this->parent
->moveTextRow( $textId, $url );