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
174 function checkTrackingTable() {
175 $dbr = wfGetDB( DB_SLAVE
);
176 if ( !$dbr->tableExists( 'blob_tracking' ) ) {
177 $this->critical( "Error: blob_tracking table does not exist" );
180 $row = $dbr->selectRow( 'blob_tracking', '*', false, __METHOD__
);
182 $this->info( "Warning: blob_tracking table contains no rows, skipping this wiki." );
189 * Start the worker processes.
190 * These processes will listen on stdin for commands.
191 * This necessary because text recompression is slow: loading, compressing and
192 * writing are all slow.
194 function startSlaveProcs() {
195 $cmd = 'php ' . wfEscapeShellArg( __FILE__
);
196 foreach ( self
::$cmdLineOptionMap as $cmdOption => $classOption ) {
197 if ( $cmdOption == 'slave-id' ) {
199 } elseif ( in_array( $cmdOption, self
::$optionsWithArgs ) && isset( $this->$classOption ) ) {
200 $cmd .= " --$cmdOption " . wfEscapeShellArg( $this->$classOption );
201 } elseif ( $this->$classOption ) {
202 $cmd .= " --$cmdOption";
206 ' --wiki ' . wfEscapeShellArg( wfWikiID() ) .
207 ' ' . call_user_func_array( 'wfEscapeShellArg', $this->destClusters
);
209 $this->slavePipes
= $this->slaveProcs
= array();
210 for ( $i = 0; $i < $this->numProcs
; $i++
) {
213 array( 'pipe', 'r' ),
214 array( 'file', 'php://stdout', 'w' ),
215 array( 'file', 'php://stderr', 'w' )
217 wfSuppressWarnings();
218 $proc = proc_open( "$cmd --slave-id $i", $spec, $pipes );
221 $this->critical( "Error opening slave process: $cmd" );
224 $this->slaveProcs
[$i] = $proc;
225 $this->slavePipes
[$i] = $pipes[0];
227 $this->prevSlaveId
= -1;
231 * Gracefully terminate the child processes
233 function killSlaveProcs() {
234 $this->info( "Waiting for slave processes to finish..." );
235 for ( $i = 0; $i < $this->numProcs
; $i++
) {
236 $this->dispatchToSlave( $i, 'quit' );
238 for ( $i = 0; $i < $this->numProcs
; $i++
) {
239 $status = proc_close( $this->slaveProcs
[$i] );
241 $this->critical( "Warning: child #$i exited with status $status" );
244 $this->info( "Done." );
248 * Dispatch a command to the next available slave.
249 * This may block until a slave finishes its work and becomes available.
251 function dispatch( /*...*/ ) {
252 $args = func_get_args();
253 $pipes = $this->slavePipes
;
254 $numPipes = stream_select( $x = array(), $pipes, $y = array(), 3600 );
256 $this->critical( "Error waiting to write to slaves. Aborting" );
259 for ( $i = 0; $i < $this->numProcs
; $i++
) {
260 $slaveId = ( $i +
$this->prevSlaveId +
1 ) %
$this->numProcs
;
261 if ( isset( $pipes[$slaveId] ) ) {
262 $this->prevSlaveId
= $slaveId;
263 $this->dispatchToSlave( $slaveId, $args );
267 $this->critical( "Unreachable" );
272 * Dispatch a command to a specified slave
274 function dispatchToSlave( $slaveId, $args ) {
275 $args = (array)$args;
276 $cmd = implode( ' ', $args );
277 fwrite( $this->slavePipes
[$slaveId], "$cmd\n" );
281 * Move all tracked pages to the new clusters
283 function doAllPages() {
284 $dbr = wfGetDB( DB_SLAVE
);
287 if ( $this->noCount
) {
288 $numPages = '[unknown]';
290 $numPages = $dbr->selectField( 'blob_tracking',
291 'COUNT(DISTINCT bt_page)',
292 # A condition is required so that this query uses the index
293 array( 'bt_moved' => 0 ),
297 if ( $this->copyOnly
) {
298 $this->info( "Copying pages..." );
300 $this->info( "Moving pages..." );
303 $res = $dbr->select( 'blob_tracking',
307 'bt_page > ' . $dbr->addQuotes( $startId )
312 'ORDER BY' => 'bt_page',
313 'LIMIT' => $this->batchSize
,
316 if ( !$res->numRows() ) {
319 foreach ( $res as $row ) {
320 $this->dispatch( 'doPage', $row->bt_page
);
323 $startId = $row->bt_page
;
324 $this->report( 'pages', $i, $numPages );
326 $this->report( 'pages', $i, $numPages );
327 if ( $this->copyOnly
) {
328 $this->info( "All page copies queued." );
330 $this->info( "All page moves queued." );
335 * Display a progress report
337 function report( $label, $current, $end ) {
339 if ( $current == $end ||
$this->numBatches
>= $this->reportingInterval
) {
340 $this->numBatches
= 0;
341 $this->info( "$label: $current / $end" );
342 $this->waitForSlaves();
347 * Move all orphan text to the new clusters
349 function doAllOrphans() {
350 $dbr = wfGetDB( DB_SLAVE
);
353 if ( $this->noCount
) {
354 $numOrphans = '[unknown]';
356 $numOrphans = $dbr->selectField( 'blob_tracking',
357 'COUNT(DISTINCT bt_text_id)',
358 array( 'bt_moved' => 0, 'bt_page' => 0 ),
360 if ( !$numOrphans ) {
364 if ( $this->copyOnly
) {
365 $this->info( "Copying orphans..." );
367 $this->info( "Moving orphans..." );
371 $res = $dbr->select( 'blob_tracking',
372 array( 'bt_text_id' ),
376 'bt_text_id > ' . $dbr->addQuotes( $startId )
381 'ORDER BY' => 'bt_text_id',
382 'LIMIT' => $this->batchSize
385 if ( !$res->numRows() ) {
389 foreach ( $res as $row ) {
390 $ids[] = $row->bt_text_id
;
393 // Need to send enough orphan IDs to the child at a time to fill a blob,
394 // so orphanBatchSize needs to be at least ~100.
395 // batchSize can be smaller or larger.
396 while ( count( $ids ) > $this->orphanBatchSize
) {
397 $args = array_slice( $ids, 0, $this->orphanBatchSize
);
398 $ids = array_slice( $ids, $this->orphanBatchSize
);
399 array_unshift( $args, 'doOrphanList' );
400 call_user_func_array( array( $this, 'dispatch' ), $args );
402 if ( count( $ids ) ) {
404 array_unshift( $args, 'doOrphanList' );
405 call_user_func_array( array( $this, 'dispatch' ), $args );
408 $startId = $row->bt_text_id
;
409 $this->report( 'orphans', $i, $numOrphans );
411 $this->report( 'orphans', $i, $numOrphans );
412 $this->info( "All orphans queued." );
416 * Main entry point for worker processes
418 function executeChild() {
419 $this->debug( 'starting' );
422 while ( !feof( STDIN
) ) {
423 $line = rtrim( fgets( STDIN
) );
427 $this->debug( $line );
428 $args = explode( ' ', $line );
429 $cmd = array_shift( $args );
432 $this->doPage( intval( $args[0] ) );
435 $this->doOrphanList( array_map( 'intval', $args ) );
440 $this->waitForSlaves();
445 * Move tracked text in a given page
447 function doPage( $pageId ) {
448 $title = Title
::newFromId( $pageId );
450 $titleText = $title->getPrefixedText();
452 $titleText = '[deleted]';
454 $dbr = wfGetDB( DB_SLAVE
);
456 // Finish any incomplete transactions
457 if ( !$this->copyOnly
) {
458 $this->finishIncompleteMoves( array( 'bt_page' => $pageId ) );
463 $trx = new CgzCopyTransaction( $this, $this->pageBlobClass
);
467 array( 'blob_tracking', 'text' ),
470 'bt_page' => $pageId,
471 'bt_text_id > ' . $dbr->addQuotes( $startId ),
473 'bt_new_url IS NULL',
478 'ORDER BY' => 'bt_text_id',
479 'LIMIT' => $this->batchSize
482 if ( !$res->numRows() ) {
487 foreach ( $res as $row ) {
488 if ( $lastTextId == $row->bt_text_id
) {
489 // Duplicate (null edit)
492 $lastTextId = $row->bt_text_id
;
494 $text = Revision
::getRevisionText( $row );
495 if ( $text === false ) {
496 $this->critical( "Error loading {$row->bt_rev_id}/{$row->bt_text_id}" );
501 if ( !$trx->addItem( $text, $row->bt_text_id
) ) {
502 $this->debug( "$titleText: committing blob with " . $trx->getSize() . " items" );
504 $trx = new CgzCopyTransaction( $this, $this->pageBlobClass
);
505 $this->waitForSlaves();
508 $startId = $row->bt_text_id
;
511 $this->debug( "$titleText: committing blob with " . $trx->getSize() . " items" );
516 * Atomic move operation.
518 * Write the new URL to the text table and set the bt_moved flag.
520 * This is done in a single transaction to provide restartable behaviour
523 * The transaction is kept short to reduce locking.
525 function moveTextRow( $textId, $url ) {
526 if ( $this->copyOnly
) {
527 $this->critical( "Internal error: can't call moveTextRow() in --copy-only mode" );
530 $dbw = wfGetDB( DB_MASTER
);
531 $dbw->begin( __METHOD__
);
532 $dbw->update( 'text',
535 'old_flags' => 'external,utf-8',
542 $dbw->update( 'blob_tracking',
543 array( 'bt_moved' => 1 ),
544 array( 'bt_text_id' => $textId ),
547 $dbw->commit( __METHOD__
);
551 * Moves are done in two phases: bt_new_url and then bt_moved.
552 * - bt_new_url indicates that the text has been copied to the new cluster.
553 * - bt_moved indicates that the text table has been updated.
555 * This function completes any moves that only have done bt_new_url. This
556 * can happen when the script is interrupted, or when --copy-only is used.
558 function finishIncompleteMoves( $conds ) {
559 $dbr = wfGetDB( DB_SLAVE
);
562 $conds = array_merge( $conds, array(
564 'bt_new_url IS NOT NULL'
567 $res = $dbr->select( 'blob_tracking',
569 array_merge( $conds, array( 'bt_text_id > ' . $dbr->addQuotes( $startId ) ) ),
572 'ORDER BY' => 'bt_text_id',
573 'LIMIT' => $this->batchSize
,
576 if ( !$res->numRows() ) {
579 $this->debug( 'Incomplete: ' . $res->numRows() . ' rows' );
580 foreach ( $res as $row ) {
581 $this->moveTextRow( $row->bt_text_id
, $row->bt_new_url
);
582 if ( $row->bt_text_id %
10 == 0 ) {
583 $this->waitForSlaves();
586 $startId = $row->bt_text_id
;
591 * Returns the name of the next target cluster
594 function getTargetCluster() {
595 $cluster = next( $this->destClusters
);
596 if ( $cluster === false ) {
597 $cluster = reset( $this->destClusters
);
603 * Gets a DB master connection for the given external cluster name
604 * @param $cluster string
605 * @return DatabaseBase
607 function getExtDB( $cluster ) {
608 $lb = wfGetLBFactory()->getExternalLB( $cluster );
609 return $lb->getConnection( DB_MASTER
);
613 * Move an orphan text_id to the new cluster
615 function doOrphanList( $textIds ) {
616 // Finish incomplete moves
617 if ( !$this->copyOnly
) {
618 $this->finishIncompleteMoves( array( 'bt_text_id' => $textIds ) );
622 $trx = new CgzCopyTransaction( $this, $this->orphanBlobClass
);
624 $res = wfGetDB( DB_SLAVE
)->select(
625 array( 'text', 'blob_tracking' ),
626 array( 'old_id', 'old_text', 'old_flags' ),
628 'old_id' => $textIds,
636 foreach ( $res as $row ) {
637 $text = Revision
::getRevisionText( $row );
638 if ( $text === false ) {
639 $this->critical( "Error: cannot load revision text for old_id={$row->old_id}" );
643 if ( !$trx->addItem( $text, $row->old_id
) ) {
644 $this->debug( "[orphan]: committing blob with " . $trx->getSize() . " rows" );
646 $trx = new CgzCopyTransaction( $this, $this->orphanBlobClass
);
647 $this->waitForSlaves();
650 $this->debug( "[orphan]: committing blob with " . $trx->getSize() . " rows" );
655 * Wait for slaves (quietly)
657 function waitForSlaves() {
660 list( $host, $maxLag ) = $lb->getMaxLag();
670 * Class to represent a recompression operation for a single CGZ blob
672 class CgzCopyTransaction
{
679 * Create a transaction from a RecompressTracked object
681 function __construct( $parent, $blobClass ) {
682 $this->blobClass
= $blobClass;
684 $this->texts
= array();
685 $this->parent
= $parent;
690 * Returns false if it's ready to commit.
691 * @param $text string
695 function addItem( $text, $textId ) {
697 $class = $this->blobClass
;
698 $this->cgz
= new $class;
700 $hash = $this->cgz
->addItem( $text );
701 $this->referrers
[$textId] = $hash;
702 $this->texts
[$textId] = $text;
703 return $this->cgz
->isHappy();
707 return count( $this->texts
);
711 * Recompress text after some aberrant modification
713 function recompress() {
714 $class = $this->blobClass
;
715 $this->cgz
= new $class;
716 $this->referrers
= array();
717 foreach ( $this->texts
as $textId => $text ) {
718 $hash = $this->cgz
->addItem( $text );
719 $this->referrers
[$textId] = $hash;
725 * Does nothing if no text items have been added.
726 * May skip the move if --copy-only is set.
729 $originalCount = count( $this->texts
);
730 if ( !$originalCount ) {
734 // Check to see if the target text_ids have been moved already.
736 // We originally read from the slave, so this can happen when a single
737 // text_id is shared between multiple pages. It's rare, but possible
738 // if a delete/move/undelete cycle splits up a null edit.
740 // We do a locking read to prevent closer-run race conditions.
741 $dbw = wfGetDB( DB_MASTER
);
742 $dbw->begin( __METHOD__
);
743 $res = $dbw->select( 'blob_tracking',
744 array( 'bt_text_id', 'bt_moved' ),
745 array( 'bt_text_id' => array_keys( $this->referrers
) ),
746 __METHOD__
, array( 'FOR UPDATE' ) );
748 foreach ( $res as $row ) {
749 if ( $row->bt_moved
) {
750 # This row has already been moved, remove it
751 $this->parent
->debug( "TRX: conflict detected in old_id={$row->bt_text_id}" );
752 unset( $this->texts
[$row->bt_text_id
] );
757 // Recompress the blob if necessary
759 if ( !count( $this->texts
) ) {
760 // All have been moved already
761 if ( $originalCount > 1 ) {
762 // This is suspcious, make noise
763 $this->critical( "Warning: concurrent operation detected, are there two conflicting " .
764 "processes running, doing the same job?" );
771 // Insert the data into the destination cluster
772 $targetCluster = $this->parent
->getTargetCluster();
773 $store = $this->parent
->store
;
774 $targetDB = $store->getMaster( $targetCluster );
775 $targetDB->clearFlag( DBO_TRX
); // we manage the transactions
776 $targetDB->begin( __METHOD__
);
777 $baseUrl = $this->parent
->store
->store( $targetCluster, serialize( $this->cgz
) );
779 // Write the new URLs to the blob_tracking table
780 foreach ( $this->referrers
as $textId => $hash ) {
781 $url = $baseUrl . '/' . $hash;
782 $dbw->update( 'blob_tracking',
783 array( 'bt_new_url' => $url ),
785 'bt_text_id' => $textId,
786 'bt_moved' => 0, # Check for concurrent conflicting update
792 $targetDB->commit( __METHOD__
);
793 // Critical section here: interruption at this point causes blob duplication
794 // Reversing the order of the commits would cause data loss instead
795 $dbw->commit( __METHOD__
);
797 // Write the new URLs to the text table and set the moved flag
798 if ( !$this->parent
->copyOnly
) {
799 foreach ( $this->referrers
as $textId => $hash ) {
800 $url = $baseUrl . '/' . $hash;
801 $this->parent
->moveTextRow( $textId, $url );