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 wfErrorLog( 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
293 function dispatchToSlave( $slaveId, $args ) {
294 $args = (array)$args;
295 $cmd = implode( ' ', $args );
296 fwrite( $this->slavePipes
[$slaveId], "$cmd\n" );
300 * Move all tracked pages to the new clusters
302 function doAllPages() {
303 $dbr = wfGetDB( DB_SLAVE
);
306 if ( $this->noCount
) {
307 $numPages = '[unknown]';
309 $numPages = $dbr->selectField( 'blob_tracking',
310 'COUNT(DISTINCT bt_page)',
311 # A condition is required so that this query uses the index
312 array( 'bt_moved' => 0 ),
316 if ( $this->copyOnly
) {
317 $this->info( "Copying pages..." );
319 $this->info( "Moving pages..." );
322 $res = $dbr->select( 'blob_tracking',
326 'bt_page > ' . $dbr->addQuotes( $startId )
331 'ORDER BY' => 'bt_page',
332 'LIMIT' => $this->batchSize
,
335 if ( !$res->numRows() ) {
338 foreach ( $res as $row ) {
339 $this->dispatch( 'doPage', $row->bt_page
);
342 $startId = $row->bt_page
;
343 $this->report( 'pages', $i, $numPages );
345 $this->report( 'pages', $i, $numPages );
346 if ( $this->copyOnly
) {
347 $this->info( "All page copies queued." );
349 $this->info( "All page moves queued." );
354 * Display a progress report
356 function report( $label, $current, $end ) {
358 if ( $current == $end ||
$this->numBatches
>= $this->reportingInterval
) {
359 $this->numBatches
= 0;
360 $this->info( "$label: $current / $end" );
361 $this->waitForSlaves();
366 * Move all orphan text to the new clusters
368 function doAllOrphans() {
369 $dbr = wfGetDB( DB_SLAVE
);
372 if ( $this->noCount
) {
373 $numOrphans = '[unknown]';
375 $numOrphans = $dbr->selectField( 'blob_tracking',
376 'COUNT(DISTINCT bt_text_id)',
377 array( 'bt_moved' => 0, 'bt_page' => 0 ),
379 if ( !$numOrphans ) {
383 if ( $this->copyOnly
) {
384 $this->info( "Copying orphans..." );
386 $this->info( "Moving orphans..." );
390 $res = $dbr->select( 'blob_tracking',
391 array( 'bt_text_id' ),
395 'bt_text_id > ' . $dbr->addQuotes( $startId )
400 'ORDER BY' => 'bt_text_id',
401 'LIMIT' => $this->batchSize
404 if ( !$res->numRows() ) {
408 foreach ( $res as $row ) {
409 $ids[] = $row->bt_text_id
;
412 // Need to send enough orphan IDs to the child at a time to fill a blob,
413 // so orphanBatchSize needs to be at least ~100.
414 // batchSize can be smaller or larger.
415 while ( count( $ids ) > $this->orphanBatchSize
) {
416 $args = array_slice( $ids, 0, $this->orphanBatchSize
);
417 $ids = array_slice( $ids, $this->orphanBatchSize
);
418 array_unshift( $args, 'doOrphanList' );
419 call_user_func_array( array( $this, 'dispatch' ), $args );
421 if ( count( $ids ) ) {
423 array_unshift( $args, 'doOrphanList' );
424 call_user_func_array( array( $this, 'dispatch' ), $args );
427 $startId = $row->bt_text_id
;
428 $this->report( 'orphans', $i, $numOrphans );
430 $this->report( 'orphans', $i, $numOrphans );
431 $this->info( "All orphans queued." );
435 * Main entry point for worker processes
437 function executeChild() {
438 $this->debug( 'starting' );
441 while ( !feof( STDIN
) ) {
442 $line = rtrim( fgets( STDIN
) );
446 $this->debug( $line );
447 $args = explode( ' ', $line );
448 $cmd = array_shift( $args );
451 $this->doPage( intval( $args[0] ) );
454 $this->doOrphanList( array_map( 'intval', $args ) );
459 $this->waitForSlaves();
464 * Move tracked text in a given page
468 function doPage( $pageId ) {
469 $title = Title
::newFromId( $pageId );
471 $titleText = $title->getPrefixedText();
473 $titleText = '[deleted]';
475 $dbr = wfGetDB( DB_SLAVE
);
477 // Finish any incomplete transactions
478 if ( !$this->copyOnly
) {
479 $this->finishIncompleteMoves( array( 'bt_page' => $pageId ) );
484 $trx = new CgzCopyTransaction( $this, $this->pageBlobClass
);
488 array( 'blob_tracking', 'text' ),
491 'bt_page' => $pageId,
492 'bt_text_id > ' . $dbr->addQuotes( $startId ),
494 'bt_new_url IS NULL',
499 'ORDER BY' => 'bt_text_id',
500 'LIMIT' => $this->batchSize
503 if ( !$res->numRows() ) {
508 foreach ( $res as $row ) {
509 if ( $lastTextId == $row->bt_text_id
) {
510 // Duplicate (null edit)
513 $lastTextId = $row->bt_text_id
;
515 $text = Revision
::getRevisionText( $row );
516 if ( $text === false ) {
517 $this->critical( "Error loading {$row->bt_rev_id}/{$row->bt_text_id}" );
522 if ( !$trx->addItem( $text, $row->bt_text_id
) ) {
523 $this->debug( "$titleText: committing blob with " . $trx->getSize() . " items" );
525 $trx = new CgzCopyTransaction( $this, $this->pageBlobClass
);
526 $this->waitForSlaves();
529 $startId = $row->bt_text_id
;
532 $this->debug( "$titleText: committing blob with " . $trx->getSize() . " items" );
537 * Atomic move operation.
539 * Write the new URL to the text table and set the bt_moved flag.
541 * This is done in a single transaction to provide restartable behavior
544 * The transaction is kept short to reduce locking.
549 function moveTextRow( $textId, $url ) {
550 if ( $this->copyOnly
) {
551 $this->critical( "Internal error: can't call moveTextRow() in --copy-only mode" );
554 $dbw = wfGetDB( DB_MASTER
);
555 $dbw->begin( __METHOD__
);
556 $dbw->update( 'text',
559 'old_flags' => 'external,utf-8',
566 $dbw->update( 'blob_tracking',
567 array( 'bt_moved' => 1 ),
568 array( 'bt_text_id' => $textId ),
571 $dbw->commit( __METHOD__
);
575 * Moves are done in two phases: bt_new_url and then bt_moved.
576 * - bt_new_url indicates that the text has been copied to the new cluster.
577 * - bt_moved indicates that the text table has been updated.
579 * This function completes any moves that only have done bt_new_url. This
580 * can happen when the script is interrupted, or when --copy-only is used.
582 * @param array $conds
584 function finishIncompleteMoves( $conds ) {
585 $dbr = wfGetDB( DB_SLAVE
);
588 $conds = array_merge( $conds, array(
590 'bt_new_url IS NOT NULL'
593 $res = $dbr->select( 'blob_tracking',
595 array_merge( $conds, array( 'bt_text_id > ' . $dbr->addQuotes( $startId ) ) ),
598 'ORDER BY' => 'bt_text_id',
599 'LIMIT' => $this->batchSize
,
602 if ( !$res->numRows() ) {
605 $this->debug( 'Incomplete: ' . $res->numRows() . ' rows' );
606 foreach ( $res as $row ) {
607 $this->moveTextRow( $row->bt_text_id
, $row->bt_new_url
);
608 if ( $row->bt_text_id %
10 == 0 ) {
609 $this->waitForSlaves();
612 $startId = $row->bt_text_id
;
617 * Returns the name of the next target cluster
620 function getTargetCluster() {
621 $cluster = next( $this->destClusters
);
622 if ( $cluster === false ) {
623 $cluster = reset( $this->destClusters
);
630 * Gets a DB master connection for the given external cluster name
631 * @param string $cluster
632 * @return DatabaseBase
634 function getExtDB( $cluster ) {
635 $lb = wfGetLBFactory()->getExternalLB( $cluster );
637 return $lb->getConnection( DB_MASTER
);
641 * Move an orphan text_id to the new cluster
643 * @param array $textIds
645 function doOrphanList( $textIds ) {
646 // Finish incomplete moves
647 if ( !$this->copyOnly
) {
648 $this->finishIncompleteMoves( array( 'bt_text_id' => $textIds ) );
652 $trx = new CgzCopyTransaction( $this, $this->orphanBlobClass
);
654 $res = wfGetDB( DB_SLAVE
)->select(
655 array( 'text', 'blob_tracking' ),
656 array( 'old_id', 'old_text', 'old_flags' ),
658 'old_id' => $textIds,
666 foreach ( $res as $row ) {
667 $text = Revision
::getRevisionText( $row );
668 if ( $text === false ) {
669 $this->critical( "Error: cannot load revision text for old_id={$row->old_id}" );
673 if ( !$trx->addItem( $text, $row->old_id
) ) {
674 $this->debug( "[orphan]: committing blob with " . $trx->getSize() . " rows" );
676 $trx = new CgzCopyTransaction( $this, $this->orphanBlobClass
);
677 $this->waitForSlaves();
680 $this->debug( "[orphan]: committing blob with " . $trx->getSize() . " rows" );
685 * Wait for slaves (quietly)
687 function waitForSlaves() {
690 list( $host, $maxLag ) = $lb->getMaxLag();
700 * Class to represent a recompression operation for a single CGZ blob
702 class CgzCopyTransaction
{
709 * Create a transaction from a RecompressTracked object
711 function __construct( $parent, $blobClass ) {
712 $this->blobClass
= $blobClass;
714 $this->texts
= array();
715 $this->parent
= $parent;
720 * Returns false if it's ready to commit.
721 * @param string $text
725 function addItem( $text, $textId ) {
727 $class = $this->blobClass
;
728 $this->cgz
= new $class;
730 $hash = $this->cgz
->addItem( $text );
731 $this->referrers
[$textId] = $hash;
732 $this->texts
[$textId] = $text;
734 return $this->cgz
->isHappy();
738 return count( $this->texts
);
742 * Recompress text after some aberrant modification
744 function recompress() {
745 $class = $this->blobClass
;
746 $this->cgz
= new $class;
747 $this->referrers
= array();
748 foreach ( $this->texts
as $textId => $text ) {
749 $hash = $this->cgz
->addItem( $text );
750 $this->referrers
[$textId] = $hash;
756 * Does nothing if no text items have been added.
757 * May skip the move if --copy-only is set.
760 $originalCount = count( $this->texts
);
761 if ( !$originalCount ) {
765 // Check to see if the target text_ids have been moved already.
767 // We originally read from the slave, so this can happen when a single
768 // text_id is shared between multiple pages. It's rare, but possible
769 // if a delete/move/undelete cycle splits up a null edit.
771 // We do a locking read to prevent closer-run race conditions.
772 $dbw = wfGetDB( DB_MASTER
);
773 $dbw->begin( __METHOD__
);
774 $res = $dbw->select( 'blob_tracking',
775 array( 'bt_text_id', 'bt_moved' ),
776 array( 'bt_text_id' => array_keys( $this->referrers
) ),
777 __METHOD__
, array( 'FOR UPDATE' ) );
779 foreach ( $res as $row ) {
780 if ( $row->bt_moved
) {
781 # This row has already been moved, remove it
782 $this->parent
->debug( "TRX: conflict detected in old_id={$row->bt_text_id}" );
783 unset( $this->texts
[$row->bt_text_id
] );
788 // Recompress the blob if necessary
790 if ( !count( $this->texts
) ) {
791 // All have been moved already
792 if ( $originalCount > 1 ) {
793 // This is suspcious, make noise
794 $this->critical( "Warning: concurrent operation detected, are there two conflicting " .
795 "processes running, doing the same job?" );
803 // Insert the data into the destination cluster
804 $targetCluster = $this->parent
->getTargetCluster();
805 $store = $this->parent
->store
;
806 $targetDB = $store->getMaster( $targetCluster );
807 $targetDB->clearFlag( DBO_TRX
); // we manage the transactions
808 $targetDB->begin( __METHOD__
);
809 $baseUrl = $this->parent
->store
->store( $targetCluster, serialize( $this->cgz
) );
811 // Write the new URLs to the blob_tracking table
812 foreach ( $this->referrers
as $textId => $hash ) {
813 $url = $baseUrl . '/' . $hash;
814 $dbw->update( 'blob_tracking',
815 array( 'bt_new_url' => $url ),
817 'bt_text_id' => $textId,
818 'bt_moved' => 0, # Check for concurrent conflicting update
824 $targetDB->commit( __METHOD__
);
825 // Critical section here: interruption at this point causes blob duplication
826 // Reversing the order of the commits would cause data loss instead
827 $dbw->commit( __METHOD__
);
829 // Write the new URLs to the text table and set the moved flag
830 if ( !$this->parent
->copyOnly
) {
831 foreach ( $this->referrers
as $textId => $hash ) {
832 $url = $baseUrl . '/' . $hash;
833 $this->parent
->moveTextRow( $textId, $url );