3 $optionsWithArgs = RecompressTracked
::getOptionsWithArgs();
4 require( dirname( __FILE__
) .'/../commandLine.inc' );
6 if ( count( $args ) < 1 ) {
7 echo "Usage: php recompressTracked.php <cluster> [... <cluster>...]\n";
8 echo "Moves blobs indexed by trackBlobs.php to a specified list of destination
9 clusters, and recompresses them in the process. Restartable.\n";
13 $job = RecompressTracked
::newFromCommandLine( $args, $options );
16 class RecompressTracked
{
18 var $batchSize = 1000;
19 var $reportingInterval = 10;
21 var $slavePipes, $slaveProcs, $prevSlaveId;
22 var $blobClass = 'DiffHistoryBlob';
23 var $copyOnly = false;
28 static $optionsWithArgs = array( 'procs', 'class' );
29 static $cmdLineOptionMap = array(
30 'procs' => 'numProcs',
31 'class' => 'blobClass',
32 'copy-only' => 'copyOnly',
34 'slave-id' => 'slaveId',
37 static function getOptionsWithArgs() {
38 return self
::$optionsWithArgs;
41 static function newFromCommandLine( $args, $options ) {
42 $jobOptions = array( 'destClusters' => $args );
43 foreach ( self
::$cmdLineOptionMap as $cmdOption => $classOption ) {
44 if ( isset( $options[$cmdOption] ) ) {
45 $jobOptions[$classOption] = $options[$cmdOption];
48 return new self( $jobOptions );
51 function __construct( $options ) {
52 foreach ( $options as $name => $value ) {
53 $this->$name = $value;
55 $this->store
= new ExternalStoreDB
;
58 function debug( $msg ) {
59 if ( $this->slaveId
!== false ) {
60 $msg = "{$this->slaveId}: $msg";
67 * Wait until the selected slave has caught up to the master.
68 * This allows us to use the slave for things that were committed in a
69 * previous part of this batch process.
72 $dbw = wfGetDB( DB_MASTER
);
73 $dbr = wfGetDB( DB_SLAVE
);
74 $pos = $dbw->getMasterPos();
75 $dbr->masterPosWait( $pos, 100000 );
79 * Execute parent or child depending on the isChild option
82 if ( $this->isChild
) {
83 $this->executeChild();
85 $this->executeParent();
90 * Execute the parent process
92 function executeParent() {
93 if ( !$this->checkTrackingTable() ) {
98 $this->startSlaveProcs();
100 $this->doAllOrphans();
101 $this->killSlaveProcs();
105 * Make sure the tracking table exists and isn't empty
107 function checkTrackingTable() {
108 $dbr = wfGetDB( DB_SLAVE
);
109 if ( !$dbr->tableExists( 'blob_tracking' ) ) {
110 echo "Error: blob_tracking table does not exist\n";
113 $row = $dbr->selectRow( 'blob_tracking', '*', false, __METHOD__
);
115 echo "Warning: blob_tracking table contains no rows, skipping this wiki.\n";
122 * Start the worker processes.
123 * These processes will listen on stdin for commands.
124 * This necessary because text recompression is slow: loading, compressing and
125 * writing are all slow.
127 function startSlaveProcs() {
128 $cmd = 'php ' . wfEscapeShellArg( __FILE__
);
129 foreach ( self
::$cmdLineOptionMap as $cmdOption => $classOption ) {
130 if ( in_array( $cmdOption, self
::$optionsWithArgs ) ) {
131 $cmd .= " --$cmdOption " . wfEscapeShellArg( $this->$classOption );
132 } elseif ( $this->$classOption ) {
133 $cmd .= " --$cmdOption";
137 ' --wiki ' . wfEscapeShellArg( wfWikiID() ) .
138 ' ' . call_user_func_array( 'wfEscapeShellArg', $this->destClusters
);
140 $this->slavePipes
= $this->slaveProcs
= array();
141 for ( $i = 0; $i < $this->numProcs
; $i++
) {
144 array( 'pipe', 'r' ),
145 array( 'file', '/dev/stdout', 'w' ),
146 array( 'file', '/dev/stderr', 'w' )
148 wfSuppressWarnings();
149 $proc = proc_open( $cmd, $spec, $pipes );
152 echo "Error opening slave process\n";
155 $this->slaveProcs
[$i] = $proc;
156 $this->slavePipes
[$i] = $pipes[0];
158 $this->prevSlaveId
= -1;
162 * Gracefully terminate the child processes
164 function killSlaveProcs() {
165 for ( $i = 0; $i < $this->numProcs
; $i++
) {
166 $this->dispatchToSlave( $i, 'quit' );
168 for ( $i = 0; $i < $this->numProcs
; $i++
) {
169 proc_close( $this->slaveProcs
[$i] );
174 * Dispatch a command to the next available slave.
175 * This may block until a slave finishes its work and becomes available.
177 function dispatch( /*...*/ ) {
178 $args = func_get_args();
179 $pipes = $this->slavePipes
;
180 $numPipes = stream_select( $x=array(), $pipes, $y=array(), 3600 );
182 echo "Error waiting to write to slaves. Aborting\n";
185 for ( $i = 0; $i < $this->numProcs
; $i++
) {
186 $slaveId = ( $i +
$this->prevSlaveId +
1 ) %
$this->numProcs
;
187 if ( isset( $pipes[$slaveId] ) ) {
188 $this->prevSlaveId
= $slaveId;
189 $this->dispatchToSlave( $slaveId, $args );
193 echo "Unreachable\n";
198 * Dispatch a command to a specified slave
200 function dispatchToSlave( $slaveId, $args ) {
201 $args = (array)$args;
202 $cmd = implode( ' ', $args );
203 fwrite( $this->slavePipes
[$slaveId], "$cmd\n" );
207 * Move all tracked pages to the new clusters
209 function doAllPages() {
210 $dbr = wfGetDB( DB_SLAVE
);
212 $endId = $dbr->selectField( 'blob_tracking', 'MAX(bt_page)',
213 # A condition is required so that this query uses the index
214 array( 'bt_moved' => 0 ),
216 echo "Moving pages...\n";
218 $res = $dbr->select( 'blob_tracking',
222 'bt_page > ' . $dbr->addQuotes( $startId )
227 'ORDER BY' => 'bt_page',
228 'LIMIT' => $this->batchSize
,
231 if ( !$res->numRows() ) {
234 foreach ( $res as $row ) {
235 $this->dispatch( 'doPage', $row->bt_page
);
237 $startId = $row->bt_page
;
238 $this->report( $startId, $endId );
240 echo "Done moving pages.\n";
244 * Display a progress report
246 function report( $start, $end ) {
248 if ( $this->numBatches
>= $this->reportingInterval
) {
249 $this->numBatches
= 0;
250 echo "$start / $end\n";
251 wfWaitForSlaves( 5 );
256 * Move all orphan text to the new clusters
258 function doAllOrphans() {
259 $dbr = wfGetDB( DB_SLAVE
);
261 $endId = $dbr->selectField( 'blob_tracking', 'MAX(bt_text_id)',
262 array( 'bt_moved' => 0, 'bt_page' => 0 ),
267 echo "Moving orphans...\n";
270 $res = $dbr->select( 'blob_tracking',
271 array( 'bt_text_id' ),
275 'bt_text_id > ' . $dbr->addQuotes( $startId )
280 'ORDER BY' => 'bt_text_id',
281 'LIMIT' => $this->batchSize
284 if ( !$res->numRows() ) {
287 $args = array( 'doOrphanList' );
288 foreach ( $res as $row ) {
289 $args[] = $row->bt_text_id
;
291 call_user_func_array( array( $this, 'dispatch' ), $args );
292 $startId = $row->bt_text_id
;
293 $this->report( $startId, $endId );
295 echo "Done moving orphans.\n";
299 * Main entry point for worker processes
301 function executeChild() {
304 while ( !feof( STDIN
) ) {
305 $line = rtrim( fgets( STDIN
) );
309 $args = explode( ' ', $line );
310 $cmd = array_shift( $args );
313 $this->doPage( intval( $args[0] ) );
316 $this->doOrphanList( array_map( 'intval', $args ) );
325 * Move tracked text in a given page
327 function doPage( $pageId ) {
328 $dbr = wfGetDB( DB_SLAVE
);
330 // Finish any incomplete transactions
331 if ( !$this->copyOnly
) {
332 $this->finishIncompleteMoves();
336 $trx = new CgzCopyTransaction( $this );
340 array( 'blob_tracking', 'text' ),
343 'bt_page' => $pageId,
344 'bt_text_id > ' . $dbr->addQuotes( $startId ),
351 'ORDER BY' => 'bt_text_id',
352 'LIMIT' => $this->batchSize
355 if ( !$res->numRows() ) {
360 foreach ( $res as $row ) {
361 if ( $lastTextId == $row->bt_text_id
) {
362 // Duplicate (null edit)
365 $lastTextId = $row->bt_text_id
;
367 $text = Revision
::getRevisionText( $row );
368 if ( $text === false ) {
369 echo "Error loading {$row->bt_rev_id}/{$row->bt_text_id}\n";
374 if ( !$trx->addItem( $text, $row->bt_text_id
) ) {
376 $trx = new CgzCopyTransaction( $this );
379 $startId = $row->bt_text_id
;
385 * Atomic move operation.
387 * Write the new URL to the text table and set the bt_moved flag.
389 * This is done in a single transaction to provide restartable behaviour
392 * The transaction is kept short to reduce locking.
394 function moveTextRow( $textId, $url ) {
395 $dbw = wfGetDB( DB_MASTER
);
397 $dbw->update( 'text',
400 'old_flags' => 'external,utf8',
407 $dbw->update( 'blob_tracking',
408 array( 'bt_moved' => 1 ),
409 array( 'bt_text_id' => $textId ),
416 * Moves are done in two phases: bt_new_url and then bt_moved.
417 * - bt_new_url indicates that the text has been copied to the new cluster.
418 * - bt_moved indicates that the text table has been updated.
420 * This function completes any moves that only have done bt_new_url. This
421 * can happen when the script is interrupted, or when --copy-only is used.
423 function finishIncompleteMoves() {
424 $dbr = wfGetDB( DB_SLAVE
);
428 $res = $dbr->select( 'blob_tracking',
431 'bt_text_id > ' . $dbr->addQuotes( $startId ),
437 'ORDER BY' => 'bt_text_id',
438 'LIMIT' => $this->batchSize
,
441 if ( !$res->numRows() ) {
444 foreach ( $res as $row ) {
445 $this->moveTextRow( $row->bt_text_id
, $row->bt_new_url
);
447 $startId = $row->bt_text_id
;
452 * Returns the name of the next target cluster
454 function getTargetCluster() {
455 $cluster = next( $this->destClusters
);
456 if ( $cluster === false ) {
457 $cluster = reset( $this->destClusters
);
463 * Gets a DB master connection for the given external cluster name
465 function getExtDB( $cluster ) {
466 $lb = wfGetLBFactory()->getExternalLB( $cluster );
467 return $lb->getConnection( DB_MASTER
);
471 * Move an orphan text_id to the new cluster
473 function doOrphanList( $textIds ) {
474 $trx = new CgzCopyTransaction( $this );
475 foreach ( $textIds as $textId ) {
476 $row = wfGetDB( DB_SLAVE
)->selectRow( 'text', array( 'old_text', 'old_flags' ),
477 array( 'old_id' => $textId ), __METHOD__
);
478 $text = Revision
::getRevisionText( $row );
479 if ( $text === false ) {
480 echo "Error: cannot load revision text for $textId\n";
484 if ( !$trx->addItem( $text, $textId ) ) {
486 $trx = new CgzCopyTransaction( $this );
493 * Class to represent a recompression operation for a single CGZ blob
495 class CgzCopyTransaction
{
501 * Create a transaction from a RecompressTracked object
503 function __construct( $parent ) {
504 $this->blobClass
= $parent->blobClass
;
506 $this->texts
= array();
511 * Returns false if it's ready to commit.
513 function addItem( $text, $textId ) {
515 $class = $this->blobClass
;
516 $this->cgz
= new $class;
518 $hash = $this->cgz
->addItem( $text );
519 $this->referrers
[$textId] = $hash;
520 $this->texts
[$textId] = $text;
521 return $this->cgz
->isHappy();
525 * Recompress text after some aberrant modification
527 function recompress() {
528 $class = $this->blobClass
;
529 $this->cgz
= new $class;
530 $this->referrers
= array();
531 foreach ( $this->texts
as $textId => $text ) {
532 $hash = $this->cgz
->addItem( $text );
533 $this->referrers
[$textId] = $hash;
539 * Does nothing if no text items have been added.
540 * May skip the move if --copy-only is set.
543 $originalCount = count( $this->texts
);
544 if ( !$originalCount ) {
548 // Check to see if the target text_ids have been moved already.
550 // We originally read from the slave, so this can happen when a single
551 // text_id is shared between multiple pages. It's rare, but possible
552 // if a delete/move/undelete cycle splits up a null edit.
554 // We do a locking read to prevent closer-run race conditions.
555 $dbw = wfGetDB( DB_MASTER
);
558 foreach ( $this->referrers
as $textId => $hash ) {
559 $moved = $dbw->selectField( 'blob_tracking', 'bt_moved',
560 array( 'bt_text_id' => $textId ),
562 array( 'FOR UPDATE' )
565 # This row has already been moved, remove it
566 unset( $this->texts
[$textId] );
571 // Recompress the blob if necessary
573 if ( !count( $this->texts
) ) {
574 // All have been moved already
575 if ( $originalCount > 1 ) {
576 // This is suspcious, make noise
577 echo "Warning: concurrent operation detected, are there two conflicting\n" .
578 "processes running, doing the same job?\n";
585 // Insert the data into the destination cluster
586 $targetCluster = $this->parent
->getTargetCluster();
587 $store = $this->parent
->store
;
588 $targetDB = $store->getMaster( $targetCluster );
589 $targetDB->clearFlag( DBO_TRX
); // we manage the transactions
591 $baseUrl = $this->parent
->store
->store( $targetCluster, serialize( $this->cgz
) );
593 // Write the new URLs to the blob_tracking table
594 foreach ( $this->referrers
as $textId => $hash ) {
595 $url = $baseUrl . '/' . $hash;
596 $dbw->update( 'blob_tracking',
597 array( 'bt_new_url' => $url ),
599 'bt_text_id' => $textId,
600 'bt_moved' => 0, # Check for concurrent conflicting update
607 // Critical section here: interruption at this point causes blob duplication
608 // Reversing the order of the commits would cause data loss instead
611 // Write the new URLs to the text table and set the moved flag
612 if ( !$this->parent
->copyOnly
) {
613 foreach ( $this->referrers
as $textId => $hash ) {
614 $url = $baseUrl . '/' . $hash;
615 $this->parent
->moveTextRow( $textId, $url );
620 function signalHandler() {
621 $this->signalled
= true;