3 $optionsWithArgs = RecompressTracked
::getOptionsWithArgs();
4 require( dirname( __FILE__
) . '/../commandLine.inc' );
6 if ( count( $args ) < 1 ) {
7 echo "Usage: php recompressTracked.php [options] <cluster> [... <cluster>...]
8 Moves blobs indexed by trackBlobs.php to a specified list of destination clusters, and recompresses them in the process. Restartable.
11 --procs <procs> Set the number of child processes (default 1)
12 --copy-only Copy only, do not update the text table. Restart without this option to complete.
13 --debug-log <file> Log debugging data to the specified file
14 --info-log <file> Log progress messages to the specified file
15 --critical-log <file> Log error messages to the specified file
20 $job = RecompressTracked
::newFromCommandLine( $args, $options );
23 class RecompressTracked
{
25 var $batchSize = 1000;
26 var $orphanBatchSize = 1000;
27 var $reportingInterval = 10;
29 var $useDiff, $pageBlobClass, $orphanBlobClass;
30 var $slavePipes, $slaveProcs, $prevSlaveId;
31 var $copyOnly = false;
35 var $debugLog, $infoLog, $criticalLog;
38 static $optionsWithArgs = array( 'procs', 'slave-id', 'debug-log', 'info-log', 'critical-log' );
39 static $cmdLineOptionMap = array(
40 'no-count' => 'noCount',
41 'procs' => 'numProcs',
42 'copy-only' => 'copyOnly',
44 'slave-id' => 'slaveId',
45 'debug-log' => 'debugLog',
46 'info-log' => 'infoLog',
47 'critical-log' => 'criticalLog',
50 static function getOptionsWithArgs() {
51 return self
::$optionsWithArgs;
54 static function newFromCommandLine( $args, $options ) {
55 $jobOptions = array( 'destClusters' => $args );
56 foreach ( self
::$cmdLineOptionMap as $cmdOption => $classOption ) {
57 if ( isset( $options[$cmdOption] ) ) {
58 $jobOptions[$classOption] = $options[$cmdOption];
61 return new self( $jobOptions );
64 function __construct( $options ) {
65 foreach ( $options as $name => $value ) {
66 $this->$name = $value;
68 $this->store
= new ExternalStoreDB
;
69 if ( !$this->isChild
) {
70 $GLOBALS['wgDebugLogPrefix'] = "RCT M: ";
71 } elseif ( $this->slaveId
!== false ) {
72 $GLOBALS['wgDebugLogPrefix'] = "RCT {$this->slaveId}: ";
74 $this->useDiff
= function_exists( 'xdiff_string_bdiff' );
75 $this->pageBlobClass
= $this->useDiff ?
'DiffHistoryBlob' : 'ConcatenatedGzipHistoryBlob';
76 $this->orphanBlobClass
= 'ConcatenatedGzipHistoryBlob';
79 function debug( $msg ) {
81 if ( $this->debugLog
) {
82 $this->logToFile( $msg, $this->debugLog
);
87 function info( $msg ) {
89 if ( $this->infoLog
) {
90 $this->logToFile( $msg, $this->infoLog
);
94 function critical( $msg ) {
96 if ( $this->criticalLog
) {
97 $this->logToFile( $msg, $this->criticalLog
);
101 function logToFile( $msg, $file ) {
102 $header = '[' . date( 'd\TH:i:s' ) . '] ' . wfHostname() . ' ' . posix_getpid();
103 if ( $this->slaveId
!== false ) {
104 $header .= "({$this->slaveId})";
106 $header .= ' ' . wfWikiID();
107 wfErrorLog( sprintf( "%-50s %s\n", $header, $msg ), $file );
111 * Wait until the selected slave has caught up to the master.
112 * This allows us to use the slave for things that were committed in a
113 * previous part of this batch process.
116 $dbw = wfGetDB( DB_MASTER
);
117 $dbr = wfGetDB( DB_SLAVE
);
118 $pos = $dbw->getMasterPos();
119 $dbr->masterPosWait( $pos, 100000 );
123 * Execute parent or child depending on the isChild option
126 if ( $this->isChild
) {
127 $this->executeChild();
129 $this->executeParent();
134 * Execute the parent process
136 function executeParent() {
137 if ( !$this->checkTrackingTable() ) {
142 $this->startSlaveProcs();
144 $this->doAllOrphans();
145 $this->killSlaveProcs();
149 * Make sure the tracking table exists and isn't empty
151 function checkTrackingTable() {
152 $dbr = wfGetDB( DB_SLAVE
);
153 if ( !$dbr->tableExists( 'blob_tracking' ) ) {
154 $this->critical( "Error: blob_tracking table does not exist" );
157 $row = $dbr->selectRow( 'blob_tracking', '*', false, __METHOD__
);
159 $this->info( "Warning: blob_tracking table contains no rows, skipping this wiki." );
166 * Start the worker processes.
167 * These processes will listen on stdin for commands.
168 * This necessary because text recompression is slow: loading, compressing and
169 * writing are all slow.
171 function startSlaveProcs() {
172 $cmd = 'php ' . wfEscapeShellArg( __FILE__
);
173 foreach ( self
::$cmdLineOptionMap as $cmdOption => $classOption ) {
174 if ( $cmdOption == 'slave-id' ) {
176 } elseif ( in_array( $cmdOption, self
::$optionsWithArgs ) && isset( $this->$classOption ) ) {
177 $cmd .= " --$cmdOption " . wfEscapeShellArg( $this->$classOption );
178 } elseif ( $this->$classOption ) {
179 $cmd .= " --$cmdOption";
183 ' --wiki ' . wfEscapeShellArg( wfWikiID() ) .
184 ' ' . call_user_func_array( 'wfEscapeShellArg', $this->destClusters
);
186 $this->slavePipes
= $this->slaveProcs
= array();
187 for ( $i = 0; $i < $this->numProcs
; $i++
) {
190 array( 'pipe', 'r' ),
191 array( 'file', 'php://stdout', 'w' ),
192 array( 'file', 'php://stderr', 'w' )
194 wfSuppressWarnings();
195 $proc = proc_open( "$cmd --slave-id $i", $spec, $pipes );
198 $this->critical( "Error opening slave process: $cmd" );
201 $this->slaveProcs
[$i] = $proc;
202 $this->slavePipes
[$i] = $pipes[0];
204 $this->prevSlaveId
= -1;
208 * Gracefully terminate the child processes
210 function killSlaveProcs() {
211 $this->info( "Waiting for slave processes to finish..." );
212 for ( $i = 0; $i < $this->numProcs
; $i++
) {
213 $this->dispatchToSlave( $i, 'quit' );
215 for ( $i = 0; $i < $this->numProcs
; $i++
) {
216 $status = proc_close( $this->slaveProcs
[$i] );
218 $this->critical( "Warning: child #$i exited with status $status" );
221 $this->info( "Done." );
225 * Dispatch a command to the next available slave.
226 * This may block until a slave finishes its work and becomes available.
228 function dispatch( /*...*/ ) {
229 $args = func_get_args();
230 $pipes = $this->slavePipes
;
231 $numPipes = stream_select( $x = array(), $pipes, $y = array(), 3600 );
233 $this->critical( "Error waiting to write to slaves. Aborting" );
236 for ( $i = 0; $i < $this->numProcs
; $i++
) {
237 $slaveId = ( $i +
$this->prevSlaveId +
1 ) %
$this->numProcs
;
238 if ( isset( $pipes[$slaveId] ) ) {
239 $this->prevSlaveId
= $slaveId;
240 $this->dispatchToSlave( $slaveId, $args );
244 $this->critical( "Unreachable" );
249 * Dispatch a command to a specified slave
251 function dispatchToSlave( $slaveId, $args ) {
252 $args = (array)$args;
253 $cmd = implode( ' ', $args );
254 fwrite( $this->slavePipes
[$slaveId], "$cmd\n" );
258 * Move all tracked pages to the new clusters
260 function doAllPages() {
261 $dbr = wfGetDB( DB_SLAVE
);
264 if ( $this->noCount
) {
265 $numPages = '[unknown]';
267 $numPages = $dbr->selectField( 'blob_tracking',
268 'COUNT(DISTINCT bt_page)',
269 # A condition is required so that this query uses the index
270 array( 'bt_moved' => 0 ),
274 if ( $this->copyOnly
) {
275 $this->info( "Copying pages..." );
277 $this->info( "Moving pages..." );
280 $res = $dbr->select( 'blob_tracking',
284 'bt_page > ' . $dbr->addQuotes( $startId )
289 'ORDER BY' => 'bt_page',
290 'LIMIT' => $this->batchSize
,
293 if ( !$res->numRows() ) {
296 foreach ( $res as $row ) {
297 $this->dispatch( 'doPage', $row->bt_page
);
300 $startId = $row->bt_page
;
301 $this->report( 'pages', $i, $numPages );
303 $this->report( 'pages', $i, $numPages );
304 if ( $this->copyOnly
) {
305 $this->info( "All page copies queued." );
307 $this->info( "All page moves queued." );
312 * Display a progress report
314 function report( $label, $current, $end ) {
316 if ( $current == $end ||
$this->numBatches
>= $this->reportingInterval
) {
317 $this->numBatches
= 0;
318 $this->info( "$label: $current / $end" );
319 $this->waitForSlaves();
324 * Move all orphan text to the new clusters
326 function doAllOrphans() {
327 $dbr = wfGetDB( DB_SLAVE
);
330 if ( $this->noCount
) {
331 $numOrphans = '[unknown]';
333 $numOrphans = $dbr->selectField( 'blob_tracking',
334 'COUNT(DISTINCT bt_text_id)',
335 array( 'bt_moved' => 0, 'bt_page' => 0 ),
337 if ( !$numOrphans ) {
341 if ( $this->copyOnly
) {
342 $this->info( "Copying orphans..." );
344 $this->info( "Moving orphans..." );
348 $res = $dbr->select( 'blob_tracking',
349 array( 'bt_text_id' ),
353 'bt_text_id > ' . $dbr->addQuotes( $startId )
358 'ORDER BY' => 'bt_text_id',
359 'LIMIT' => $this->batchSize
362 if ( !$res->numRows() ) {
366 foreach ( $res as $row ) {
367 $ids[] = $row->bt_text_id
;
370 // Need to send enough orphan IDs to the child at a time to fill a blob,
371 // so orphanBatchSize needs to be at least ~100.
372 // batchSize can be smaller or larger.
373 while ( count( $ids ) > $this->orphanBatchSize
) {
374 $args = array_slice( $ids, 0, $this->orphanBatchSize
);
375 $ids = array_slice( $ids, $this->orphanBatchSize
);
376 array_unshift( $args, 'doOrphanList' );
377 call_user_func_array( array( $this, 'dispatch' ), $args );
379 if ( count( $ids ) ) {
381 array_unshift( $args, 'doOrphanList' );
382 call_user_func_array( array( $this, 'dispatch' ), $args );
385 $startId = $row->bt_text_id
;
386 $this->report( 'orphans', $i, $numOrphans );
388 $this->report( 'orphans', $i, $numOrphans );
389 $this->info( "All orphans queued." );
393 * Main entry point for worker processes
395 function executeChild() {
396 $this->debug( 'starting' );
399 while ( !feof( STDIN
) ) {
400 $line = rtrim( fgets( STDIN
) );
404 $this->debug( $line );
405 $args = explode( ' ', $line );
406 $cmd = array_shift( $args );
409 $this->doPage( intval( $args[0] ) );
412 $this->doOrphanList( array_map( 'intval', $args ) );
417 $this->waitForSlaves();
422 * Move tracked text in a given page
424 function doPage( $pageId ) {
425 $title = Title
::newFromId( $pageId );
427 $titleText = $title->getPrefixedText();
429 $titleText = '[deleted]';
431 $dbr = wfGetDB( DB_SLAVE
);
433 // Finish any incomplete transactions
434 if ( !$this->copyOnly
) {
435 $this->finishIncompleteMoves( array( 'bt_page' => $pageId ) );
440 $trx = new CgzCopyTransaction( $this, $this->pageBlobClass
);
444 array( 'blob_tracking', 'text' ),
447 'bt_page' => $pageId,
448 'bt_text_id > ' . $dbr->addQuotes( $startId ),
450 'bt_new_url IS NULL',
455 'ORDER BY' => 'bt_text_id',
456 'LIMIT' => $this->batchSize
459 if ( !$res->numRows() ) {
464 foreach ( $res as $row ) {
465 if ( $lastTextId == $row->bt_text_id
) {
466 // Duplicate (null edit)
469 $lastTextId = $row->bt_text_id
;
471 $text = Revision
::getRevisionText( $row );
472 if ( $text === false ) {
473 $this->critical( "Error loading {$row->bt_rev_id}/{$row->bt_text_id}" );
478 if ( !$trx->addItem( $text, $row->bt_text_id
) ) {
479 $this->debug( "$titleText: committing blob with " . $trx->getSize() . " items" );
481 $trx = new CgzCopyTransaction( $this, $this->pageBlobClass
);
482 $this->waitForSlaves();
485 $startId = $row->bt_text_id
;
488 $this->debug( "$titleText: committing blob with " . $trx->getSize() . " items" );
493 * Atomic move operation.
495 * Write the new URL to the text table and set the bt_moved flag.
497 * This is done in a single transaction to provide restartable behaviour
500 * The transaction is kept short to reduce locking.
502 function moveTextRow( $textId, $url ) {
503 if ( $this->copyOnly
) {
504 $this->critical( "Internal error: can't call moveTextRow() in --copy-only mode" );
507 $dbw = wfGetDB( DB_MASTER
);
509 $dbw->update( 'text',
512 'old_flags' => 'external,utf-8',
519 $dbw->update( 'blob_tracking',
520 array( 'bt_moved' => 1 ),
521 array( 'bt_text_id' => $textId ),
528 * Moves are done in two phases: bt_new_url and then bt_moved.
529 * - bt_new_url indicates that the text has been copied to the new cluster.
530 * - bt_moved indicates that the text table has been updated.
532 * This function completes any moves that only have done bt_new_url. This
533 * can happen when the script is interrupted, or when --copy-only is used.
535 function finishIncompleteMoves( $conds ) {
536 $dbr = wfGetDB( DB_SLAVE
);
539 $conds = array_merge( $conds, array(
541 'bt_new_url IS NOT NULL'
544 $res = $dbr->select( 'blob_tracking',
546 array_merge( $conds, array( 'bt_text_id > ' . $dbr->addQuotes( $startId ) ) ),
549 'ORDER BY' => 'bt_text_id',
550 'LIMIT' => $this->batchSize
,
553 if ( !$res->numRows() ) {
556 $this->debug( 'Incomplete: ' . $res->numRows() . ' rows' );
557 foreach ( $res as $row ) {
558 $this->moveTextRow( $row->bt_text_id
, $row->bt_new_url
);
559 if ( $row->bt_text_id %
10 == 0 ) {
560 $this->waitForSlaves();
563 $startId = $row->bt_text_id
;
568 * Returns the name of the next target cluster
570 function getTargetCluster() {
571 $cluster = next( $this->destClusters
);
572 if ( $cluster === false ) {
573 $cluster = reset( $this->destClusters
);
579 * Gets a DB master connection for the given external cluster name
581 function getExtDB( $cluster ) {
582 $lb = wfGetLBFactory()->getExternalLB( $cluster );
583 return $lb->getConnection( DB_MASTER
);
587 * Move an orphan text_id to the new cluster
589 function doOrphanList( $textIds ) {
590 // Finish incomplete moves
591 if ( !$this->copyOnly
) {
592 $this->finishIncompleteMoves( array( 'bt_text_id' => $textIds ) );
596 $trx = new CgzCopyTransaction( $this, $this->orphanBlobClass
);
598 $res = wfGetDB( DB_SLAVE
)->select(
599 array( 'text', 'blob_tracking' ),
600 array( 'old_id', 'old_text', 'old_flags' ),
602 'old_id' => $textIds,
610 foreach ( $res as $row ) {
611 $text = Revision
::getRevisionText( $row );
612 if ( $text === false ) {
613 $this->critical( "Error: cannot load revision text for old_id=$textId" );
617 if ( !$trx->addItem( $text, $row->old_id
) ) {
618 $this->debug( "[orphan]: committing blob with " . $trx->getSize() . " rows" );
620 $trx = new CgzCopyTransaction( $this, $this->orphanBlobClass
);
621 $this->waitForSlaves();
624 $this->debug( "[orphan]: committing blob with " . $trx->getSize() . " rows" );
629 * Wait for slaves (quietly)
631 function waitForSlaves() {
634 list( $host, $maxLag ) = $lb->getMaxLag();
644 * Class to represent a recompression operation for a single CGZ blob
646 class CgzCopyTransaction
{
653 * Create a transaction from a RecompressTracked object
655 function __construct( $parent, $blobClass ) {
656 $this->blobClass
= $blobClass;
658 $this->texts
= array();
659 $this->parent
= $parent;
664 * Returns false if it's ready to commit.
666 function addItem( $text, $textId ) {
668 $class = $this->blobClass
;
669 $this->cgz
= new $class;
671 $hash = $this->cgz
->addItem( $text );
672 $this->referrers
[$textId] = $hash;
673 $this->texts
[$textId] = $text;
674 return $this->cgz
->isHappy();
678 return count( $this->texts
);
682 * Recompress text after some aberrant modification
684 function recompress() {
685 $class = $this->blobClass
;
686 $this->cgz
= new $class;
687 $this->referrers
= array();
688 foreach ( $this->texts
as $textId => $text ) {
689 $hash = $this->cgz
->addItem( $text );
690 $this->referrers
[$textId] = $hash;
696 * Does nothing if no text items have been added.
697 * May skip the move if --copy-only is set.
700 $originalCount = count( $this->texts
);
701 if ( !$originalCount ) {
705 // Check to see if the target text_ids have been moved already.
707 // We originally read from the slave, so this can happen when a single
708 // text_id is shared between multiple pages. It's rare, but possible
709 // if a delete/move/undelete cycle splits up a null edit.
711 // We do a locking read to prevent closer-run race conditions.
712 $dbw = wfGetDB( DB_MASTER
);
714 $res = $dbw->select( 'blob_tracking',
715 array( 'bt_text_id', 'bt_moved' ),
716 array( 'bt_text_id' => array_keys( $this->referrers
) ),
717 __METHOD__
, array( 'FOR UPDATE' ) );
719 foreach ( $res as $row ) {
720 if ( $row->bt_moved
) {
721 # This row has already been moved, remove it
722 $this->parent
->debug( "TRX: conflict detected in old_id={$row->bt_text_id}" );
723 unset( $this->texts
[$row->bt_text_id
] );
728 // Recompress the blob if necessary
730 if ( !count( $this->texts
) ) {
731 // All have been moved already
732 if ( $originalCount > 1 ) {
733 // This is suspcious, make noise
734 $this->critical( "Warning: concurrent operation detected, are there two conflicting " .
735 "processes running, doing the same job?" );
742 // Insert the data into the destination cluster
743 $targetCluster = $this->parent
->getTargetCluster();
744 $store = $this->parent
->store
;
745 $targetDB = $store->getMaster( $targetCluster );
746 $targetDB->clearFlag( DBO_TRX
); // we manage the transactions
748 $baseUrl = $this->parent
->store
->store( $targetCluster, serialize( $this->cgz
) );
750 // Write the new URLs to the blob_tracking table
751 foreach ( $this->referrers
as $textId => $hash ) {
752 $url = $baseUrl . '/' . $hash;
753 $dbw->update( 'blob_tracking',
754 array( 'bt_new_url' => $url ),
756 'bt_text_id' => $textId,
757 'bt_moved' => 0, # Check for concurrent conflicting update
764 // Critical section here: interruption at this point causes blob duplication
765 // Reversing the order of the commits would cause data loss instead
768 // Write the new URLs to the text table and set the moved flag
769 if ( !$this->parent
->copyOnly
) {
770 foreach ( $this->referrers
as $textId => $hash ) {
771 $url = $baseUrl . '/' . $hash;
772 $this->parent
->moveTextRow( $textId, $url );