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 8)
12 --copy-only Copy only, do not update the text table. Restart without this option to complete.
17 $job = RecompressTracked
::newFromCommandLine( $args, $options );
20 class RecompressTracked
{
22 var $batchSize = 1000;
23 var $reportingInterval = 10;
25 var $useDiff, $pageBlobClass, $orphanBlobClass;
26 var $slavePipes, $slaveProcs, $prevSlaveId;
27 var $copyOnly = false;
32 static $optionsWithArgs = array( 'procs', 'slave-id' );
33 static $cmdLineOptionMap = array(
34 'procs' => 'numProcs',
35 'copy-only' => 'copyOnly',
37 'slave-id' => 'slaveId',
40 static function getOptionsWithArgs() {
41 return self
::$optionsWithArgs;
44 static function newFromCommandLine( $args, $options ) {
45 $jobOptions = array( 'destClusters' => $args );
46 foreach ( self
::$cmdLineOptionMap as $cmdOption => $classOption ) {
47 if ( isset( $options[$cmdOption] ) ) {
48 $jobOptions[$classOption] = $options[$cmdOption];
51 return new self( $jobOptions );
54 function __construct( $options ) {
55 foreach ( $options as $name => $value ) {
56 $this->$name = $value;
58 $this->store
= new ExternalStoreDB
;
59 if ( !$this->isChild
) {
60 $GLOBALS['wgDebugLogPrefix'] = "RCT M: ";
61 } elseif ( $this->slaveId
!== false ) {
62 $GLOBALS['wgDebugLogPrefix'] = "RCT {$this->slaveId}: ";
64 $this->useDiff
= function_exists( 'xdiff_string_bdiff' );
65 $this->pageBlobClass
= $this->useDiff ?
'DiffHistoryBlob' : 'ConcatenatedGzipHistoryBlob';
66 $this->orphanBlobClass
= 'ConcatenatedGzipHistoryBlob';
69 function debug( $msg ) {
74 * Wait until the selected slave has caught up to the master.
75 * This allows us to use the slave for things that were committed in a
76 * previous part of this batch process.
79 $dbw = wfGetDB( DB_MASTER
);
80 $dbr = wfGetDB( DB_SLAVE
);
81 $pos = $dbw->getMasterPos();
82 $dbr->masterPosWait( $pos, 100000 );
86 * Execute parent or child depending on the isChild option
89 if ( $this->isChild
) {
90 $this->executeChild();
92 $this->executeParent();
97 * Execute the parent process
99 function executeParent() {
100 if ( !$this->checkTrackingTable() ) {
105 $this->startSlaveProcs();
107 $this->doAllOrphans();
108 $this->killSlaveProcs();
112 * Make sure the tracking table exists and isn't empty
114 function checkTrackingTable() {
115 $dbr = wfGetDB( DB_SLAVE
);
116 if ( !$dbr->tableExists( 'blob_tracking' ) ) {
117 echo "Error: blob_tracking table does not exist\n";
120 $row = $dbr->selectRow( 'blob_tracking', '*', false, __METHOD__
);
122 echo "Warning: blob_tracking table contains no rows, skipping this wiki.\n";
129 * Start the worker processes.
130 * These processes will listen on stdin for commands.
131 * This necessary because text recompression is slow: loading, compressing and
132 * writing are all slow.
134 function startSlaveProcs() {
135 $cmd = 'php ' . wfEscapeShellArg( __FILE__
);
136 foreach ( self
::$cmdLineOptionMap as $cmdOption => $classOption ) {
137 if ( in_array( $cmdOption, self
::$optionsWithArgs ) ) {
138 $cmd .= " --$cmdOption " . wfEscapeShellArg( $this->$classOption );
139 } elseif ( $this->$classOption ) {
140 $cmd .= " --$cmdOption";
144 ' --wiki ' . wfEscapeShellArg( wfWikiID() ) .
145 ' ' . call_user_func_array( 'wfEscapeShellArg', $this->destClusters
);
147 $this->slavePipes
= $this->slaveProcs
= array();
148 for ( $i = 0; $i < $this->numProcs
; $i++
) {
151 array( 'pipe', 'r' ),
152 array( 'file', '/dev/stdout', 'w' ),
153 array( 'file', '/dev/stderr', 'w' )
155 wfSuppressWarnings();
156 $proc = proc_open( "$cmd --slave-id $i", $spec, $pipes );
159 echo "Error opening slave process\n";
162 $this->slaveProcs
[$i] = $proc;
163 $this->slavePipes
[$i] = $pipes[0];
165 $this->prevSlaveId
= -1;
169 * Gracefully terminate the child processes
171 function killSlaveProcs() {
172 for ( $i = 0; $i < $this->numProcs
; $i++
) {
173 $this->dispatchToSlave( $i, 'quit' );
175 for ( $i = 0; $i < $this->numProcs
; $i++
) {
176 proc_close( $this->slaveProcs
[$i] );
181 * Dispatch a command to the next available slave.
182 * This may block until a slave finishes its work and becomes available.
184 function dispatch( /*...*/ ) {
185 $args = func_get_args();
186 $pipes = $this->slavePipes
;
187 $numPipes = stream_select( $x=array(), $pipes, $y=array(), 3600 );
189 echo "Error waiting to write to slaves. Aborting\n";
192 for ( $i = 0; $i < $this->numProcs
; $i++
) {
193 $slaveId = ( $i +
$this->prevSlaveId +
1 ) %
$this->numProcs
;
194 if ( isset( $pipes[$slaveId] ) ) {
195 $this->prevSlaveId
= $slaveId;
196 $this->dispatchToSlave( $slaveId, $args );
200 echo "Unreachable\n";
205 * Dispatch a command to a specified slave
207 function dispatchToSlave( $slaveId, $args ) {
208 $args = (array)$args;
209 $cmd = implode( ' ', $args );
210 fwrite( $this->slavePipes
[$slaveId], "$cmd\n" );
214 * Move all tracked pages to the new clusters
216 function doAllPages() {
217 $dbr = wfGetDB( DB_SLAVE
);
219 $endId = $dbr->selectField( 'blob_tracking', 'MAX(bt_page)',
220 # A condition is required so that this query uses the index
221 array( 'bt_moved' => 0 ),
223 echo "Moving pages...\n";
225 $res = $dbr->select( 'blob_tracking',
229 'bt_page > ' . $dbr->addQuotes( $startId )
234 'ORDER BY' => 'bt_page',
235 'LIMIT' => $this->batchSize
,
238 if ( !$res->numRows() ) {
241 foreach ( $res as $row ) {
242 $this->dispatch( 'doPage', $row->bt_page
);
244 $startId = $row->bt_page
;
245 $this->report( $startId, $endId );
247 echo "Done moving pages.\n";
251 * Display a progress report
253 function report( $start, $end ) {
255 if ( $this->numBatches
>= $this->reportingInterval
) {
256 $this->numBatches
= 0;
257 echo "$start / $end\n";
258 wfWaitForSlaves( 5 );
263 * Move all orphan text to the new clusters
265 function doAllOrphans() {
266 $dbr = wfGetDB( DB_SLAVE
);
268 $endId = $dbr->selectField( 'blob_tracking', 'MAX(bt_text_id)',
269 array( 'bt_moved' => 0, 'bt_page' => 0 ),
274 echo "Moving orphans...\n";
277 $res = $dbr->select( 'blob_tracking',
278 array( 'bt_text_id' ),
282 'bt_text_id > ' . $dbr->addQuotes( $startId )
287 'ORDER BY' => 'bt_text_id',
288 'LIMIT' => $this->batchSize
291 if ( !$res->numRows() ) {
294 $args = array( 'doOrphanList' );
295 foreach ( $res as $row ) {
296 $args[] = $row->bt_text_id
;
298 call_user_func_array( array( $this, 'dispatch' ), $args );
299 $startId = $row->bt_text_id
;
300 $this->report( $startId, $endId );
302 echo "Done moving orphans.\n";
306 * Main entry point for worker processes
308 function executeChild() {
309 $this->debug( 'starting' );
312 while ( !feof( STDIN
) ) {
313 $line = rtrim( fgets( STDIN
) );
317 $this->debug( $line );
318 $args = explode( ' ', $line );
319 $cmd = array_shift( $args );
322 $this->doPage( intval( $args[0] ) );
325 $this->doOrphanList( array_map( 'intval', $args ) );
334 * Move tracked text in a given page
336 function doPage( $pageId ) {
337 $title = Title
::newFromId( $pageId );
339 $titleText = $title->getPrefixedText();
341 $titleText = '[deleted]';
343 $dbr = wfGetDB( DB_SLAVE
);
345 // Finish any incomplete transactions
346 if ( !$this->copyOnly
) {
347 $this->finishIncompleteMoves( array( 'bt_page' => $pageId ) );
351 $trx = new CgzCopyTransaction( $this, $this->pageBlobClass
);
355 array( 'blob_tracking', 'text' ),
358 'bt_page' => $pageId,
359 'bt_text_id > ' . $dbr->addQuotes( $startId ),
361 'bt_new_url IS NULL',
366 'ORDER BY' => 'bt_text_id',
367 'LIMIT' => $this->batchSize
370 if ( !$res->numRows() ) {
375 foreach ( $res as $row ) {
376 if ( $lastTextId == $row->bt_text_id
) {
377 // Duplicate (null edit)
380 $lastTextId = $row->bt_text_id
;
382 $text = Revision
::getRevisionText( $row );
383 if ( $text === false ) {
384 echo "Error loading {$row->bt_rev_id}/{$row->bt_text_id}\n";
389 if ( !$trx->addItem( $text, $row->bt_text_id
) ) {
390 $this->debug( "$titleText: committing blob with " . $trx->getSize() . " items" );
392 $trx = new CgzCopyTransaction( $this, $this->pageBlobClass
);
395 $startId = $row->bt_text_id
;
398 $this->debug( "$titleText: committing blob with " . $trx->getSize() . " items" );
403 * Atomic move operation.
405 * Write the new URL to the text table and set the bt_moved flag.
407 * This is done in a single transaction to provide restartable behaviour
410 * The transaction is kept short to reduce locking.
412 function moveTextRow( $textId, $url ) {
413 $dbw = wfGetDB( DB_MASTER
);
415 $dbw->update( 'text',
418 'old_flags' => 'external,utf8',
425 $dbw->update( 'blob_tracking',
426 array( 'bt_moved' => 1 ),
427 array( 'bt_text_id' => $textId ),
434 * Moves are done in two phases: bt_new_url and then bt_moved.
435 * - bt_new_url indicates that the text has been copied to the new cluster.
436 * - bt_moved indicates that the text table has been updated.
438 * This function completes any moves that only have done bt_new_url. This
439 * can happen when the script is interrupted, or when --copy-only is used.
441 function finishIncompleteMoves( $conds ) {
442 $dbr = wfGetDB( DB_SLAVE
);
445 $conds = array_merge( $conds, array(
447 'bt_new_url IS NOT NULL'
450 $res = $dbr->select( 'blob_tracking',
452 array_merge( $conds, array( 'bt_text_id > ' . $dbr->addQuotes( $startId ) ) ),
455 'ORDER BY' => 'bt_text_id',
456 'LIMIT' => $this->batchSize
,
459 if ( !$res->numRows() ) {
462 $this->debug( 'Incomplete: ' . $res->numRows() . ' rows' );
463 foreach ( $res as $row ) {
464 $this->moveTextRow( $row->bt_text_id
, $row->bt_new_url
);
466 $startId = $row->bt_text_id
;
471 * Returns the name of the next target cluster
473 function getTargetCluster() {
474 $cluster = next( $this->destClusters
);
475 if ( $cluster === false ) {
476 $cluster = reset( $this->destClusters
);
482 * Gets a DB master connection for the given external cluster name
484 function getExtDB( $cluster ) {
485 $lb = wfGetLBFactory()->getExternalLB( $cluster );
486 return $lb->getConnection( DB_MASTER
);
490 * Move an orphan text_id to the new cluster
492 function doOrphanList( $textIds ) {
493 // Finish incomplete moves
494 $this->finishIncompleteMoves( array( 'bt_text_id' => $textIds ) );
496 $trx = new CgzCopyTransaction( $this, $this->orphanBlobClass
);
497 foreach ( $textIds as $textId ) {
498 $row = wfGetDB( DB_SLAVE
)->selectRow( 'text', array( 'old_text', 'old_flags' ),
499 array( 'old_id' => $textId ), __METHOD__
);
500 $text = Revision
::getRevisionText( $row );
501 if ( $text === false ) {
502 echo "Error: cannot load revision text for $textId\n";
506 if ( !$trx->addItem( $text, $textId ) ) {
507 $this->debug( "[orphan]: committing blob with " . $trx->getSize() . " rows" );
509 $trx = new CgzCopyTransaction( $this, $this->orphanBlobClass
);
512 $this->debug( "[orphan]: committing blob with " . $trx->getSize() . " rows" );
518 * Class to represent a recompression operation for a single CGZ blob
520 class CgzCopyTransaction
{
527 * Create a transaction from a RecompressTracked object
529 function __construct( $parent, $blobClass ) {
530 $this->blobClass
= $blobClass;
532 $this->texts
= array();
533 $this->parent
= $parent;
538 * Returns false if it's ready to commit.
540 function addItem( $text, $textId ) {
542 $class = $this->blobClass
;
543 $this->cgz
= new $class;
545 $hash = $this->cgz
->addItem( $text );
546 $this->referrers
[$textId] = $hash;
547 $this->texts
[$textId] = $text;
548 return $this->cgz
->isHappy();
552 return count( $this->texts
);
556 * Recompress text after some aberrant modification
558 function recompress() {
559 $class = $this->blobClass
;
560 $this->cgz
= new $class;
561 $this->referrers
= array();
562 foreach ( $this->texts
as $textId => $text ) {
563 $hash = $this->cgz
->addItem( $text );
564 $this->referrers
[$textId] = $hash;
570 * Does nothing if no text items have been added.
571 * May skip the move if --copy-only is set.
574 $originalCount = count( $this->texts
);
575 if ( !$originalCount ) {
579 // Check to see if the target text_ids have been moved already.
581 // We originally read from the slave, so this can happen when a single
582 // text_id is shared between multiple pages. It's rare, but possible
583 // if a delete/move/undelete cycle splits up a null edit.
585 // We do a locking read to prevent closer-run race conditions.
586 $dbw = wfGetDB( DB_MASTER
);
588 $res = $dbw->select( 'blob_tracking',
589 array( 'bt_text_id', 'bt_moved' ),
590 array( 'bt_text_id' => array_keys( $this->referrers
) ),
591 __METHOD__
, array( 'FOR UPDATE' ) );
593 foreach ( $res as $row ) {
594 if ( $row->bt_moved
) {
595 # This row has already been moved, remove it
596 $this->parent
->debug( "TRX: conflict detected in old_id={$row->bt_text_id}" );
597 unset( $this->texts
[$row->bt_text_id
] );
602 // Recompress the blob if necessary
604 if ( !count( $this->texts
) ) {
605 // All have been moved already
606 if ( $originalCount > 1 ) {
607 // This is suspcious, make noise
608 echo "Warning: concurrent operation detected, are there two conflicting " .
609 "processes running, doing the same job?\n";
616 // Insert the data into the destination cluster
617 $targetCluster = $this->parent
->getTargetCluster();
618 $store = $this->parent
->store
;
619 $targetDB = $store->getMaster( $targetCluster );
620 $targetDB->clearFlag( DBO_TRX
); // we manage the transactions
622 $baseUrl = $this->parent
->store
->store( $targetCluster, serialize( $this->cgz
) );
624 // Write the new URLs to the blob_tracking table
625 foreach ( $this->referrers
as $textId => $hash ) {
626 $url = $baseUrl . '/' . $hash;
627 $dbw->update( 'blob_tracking',
628 array( 'bt_new_url' => $url ),
630 'bt_text_id' => $textId,
631 'bt_moved' => 0, # Check for concurrent conflicting update
638 // Critical section here: interruption at this point causes blob duplication
639 // Reversing the order of the commits would cause data loss instead
642 // Write the new URLs to the text table and set the moved flag
643 if ( !$this->parent
->copyOnly
) {
644 foreach ( $this->referrers
as $textId => $hash ) {
645 $url = $baseUrl . '/' . $hash;
646 $this->parent
->moveTextRow( $textId, $url );