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];
98 return new self( $jobOptions );
101 function __construct( $options ) {
102 foreach ( $options as $name => $value ) {
103 $this->$name = $value;
105 $this->store
= new ExternalStoreDB
;
106 if ( !$this->isChild
) {
107 $GLOBALS['wgDebugLogPrefix'] = "RCT M: ";
108 } elseif ( $this->slaveId
!== false ) {
109 $GLOBALS['wgDebugLogPrefix'] = "RCT {$this->slaveId}: ";
111 $this->useDiff
= function_exists( 'xdiff_string_bdiff' );
112 $this->pageBlobClass
= $this->useDiff ?
'DiffHistoryBlob' : 'ConcatenatedGzipHistoryBlob';
113 $this->orphanBlobClass
= 'ConcatenatedGzipHistoryBlob';
116 function debug( $msg ) {
118 if ( $this->debugLog
) {
119 $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" );
195 $row = $dbr->selectRow( 'blob_tracking', '*', false, __METHOD__
);
197 $this->info( "Warning: blob_tracking table contains no rows, skipping this wiki." );
204 * Start the worker processes.
205 * These processes will listen on stdin for commands.
206 * This necessary because text recompression is slow: loading, compressing and
207 * writing are all slow.
209 function startSlaveProcs() {
210 $cmd = 'php ' . wfEscapeShellArg( __FILE__
);
211 foreach ( self
::$cmdLineOptionMap as $cmdOption => $classOption ) {
212 if ( $cmdOption == 'slave-id' ) {
214 } elseif ( in_array( $cmdOption, self
::$optionsWithArgs ) && isset( $this->$classOption ) ) {
215 $cmd .= " --$cmdOption " . wfEscapeShellArg( $this->$classOption );
216 } elseif ( $this->$classOption ) {
217 $cmd .= " --$cmdOption";
221 ' --wiki ' . wfEscapeShellArg( wfWikiID() ) .
222 ' ' . call_user_func_array( 'wfEscapeShellArg', $this->destClusters
);
224 $this->slavePipes
= $this->slaveProcs
= array();
225 for ( $i = 0; $i < $this->numProcs
; $i++
) {
228 array( 'pipe', 'r' ),
229 array( 'file', 'php://stdout', 'w' ),
230 array( 'file', 'php://stderr', 'w' )
232 wfSuppressWarnings();
233 $proc = proc_open( "$cmd --slave-id $i", $spec, $pipes );
236 $this->critical( "Error opening slave process: $cmd" );
239 $this->slaveProcs
[$i] = $proc;
240 $this->slavePipes
[$i] = $pipes[0];
242 $this->prevSlaveId
= -1;
246 * Gracefully terminate the child processes
248 function killSlaveProcs() {
249 $this->info( "Waiting for slave processes to finish..." );
250 for ( $i = 0; $i < $this->numProcs
; $i++
) {
251 $this->dispatchToSlave( $i, 'quit' );
253 for ( $i = 0; $i < $this->numProcs
; $i++
) {
254 $status = proc_close( $this->slaveProcs
[$i] );
256 $this->critical( "Warning: child #$i exited with status $status" );
259 $this->info( "Done." );
263 * Dispatch a command to the next available slave.
264 * This may block until a slave finishes its work and becomes available.
266 function dispatch( /*...*/ ) {
267 $args = func_get_args();
268 $pipes = $this->slavePipes
;
269 $numPipes = stream_select( $x = array(), $pipes, $y = array(), 3600 );
271 $this->critical( "Error waiting to write to slaves. Aborting" );
274 for ( $i = 0; $i < $this->numProcs
; $i++
) {
275 $slaveId = ( $i +
$this->prevSlaveId +
1 ) %
$this->numProcs
;
276 if ( isset( $pipes[$slaveId] ) ) {
277 $this->prevSlaveId
= $slaveId;
278 $this->dispatchToSlave( $slaveId, $args );
282 $this->critical( "Unreachable" );
287 * Dispatch a command to a specified slave
289 function dispatchToSlave( $slaveId, $args ) {
290 $args = (array)$args;
291 $cmd = implode( ' ', $args );
292 fwrite( $this->slavePipes
[$slaveId], "$cmd\n" );
296 * Move all tracked pages to the new clusters
298 function doAllPages() {
299 $dbr = wfGetDB( DB_SLAVE
);
302 if ( $this->noCount
) {
303 $numPages = '[unknown]';
305 $numPages = $dbr->selectField( 'blob_tracking',
306 'COUNT(DISTINCT bt_page)',
307 # A condition is required so that this query uses the index
308 array( 'bt_moved' => 0 ),
312 if ( $this->copyOnly
) {
313 $this->info( "Copying pages..." );
315 $this->info( "Moving pages..." );
318 $res = $dbr->select( 'blob_tracking',
322 'bt_page > ' . $dbr->addQuotes( $startId )
327 'ORDER BY' => 'bt_page',
328 'LIMIT' => $this->batchSize
,
331 if ( !$res->numRows() ) {
334 foreach ( $res as $row ) {
335 $this->dispatch( 'doPage', $row->bt_page
);
338 $startId = $row->bt_page
;
339 $this->report( 'pages', $i, $numPages );
341 $this->report( 'pages', $i, $numPages );
342 if ( $this->copyOnly
) {
343 $this->info( "All page copies queued." );
345 $this->info( "All page moves queued." );
350 * Display a progress report
352 function report( $label, $current, $end ) {
354 if ( $current == $end ||
$this->numBatches
>= $this->reportingInterval
) {
355 $this->numBatches
= 0;
356 $this->info( "$label: $current / $end" );
357 $this->waitForSlaves();
362 * Move all orphan text to the new clusters
364 function doAllOrphans() {
365 $dbr = wfGetDB( DB_SLAVE
);
368 if ( $this->noCount
) {
369 $numOrphans = '[unknown]';
371 $numOrphans = $dbr->selectField( 'blob_tracking',
372 'COUNT(DISTINCT bt_text_id)',
373 array( 'bt_moved' => 0, 'bt_page' => 0 ),
375 if ( !$numOrphans ) {
379 if ( $this->copyOnly
) {
380 $this->info( "Copying orphans..." );
382 $this->info( "Moving orphans..." );
386 $res = $dbr->select( 'blob_tracking',
387 array( 'bt_text_id' ),
391 'bt_text_id > ' . $dbr->addQuotes( $startId )
396 'ORDER BY' => 'bt_text_id',
397 'LIMIT' => $this->batchSize
400 if ( !$res->numRows() ) {
404 foreach ( $res as $row ) {
405 $ids[] = $row->bt_text_id
;
408 // Need to send enough orphan IDs to the child at a time to fill a blob,
409 // so orphanBatchSize needs to be at least ~100.
410 // batchSize can be smaller or larger.
411 while ( count( $ids ) > $this->orphanBatchSize
) {
412 $args = array_slice( $ids, 0, $this->orphanBatchSize
);
413 $ids = array_slice( $ids, $this->orphanBatchSize
);
414 array_unshift( $args, 'doOrphanList' );
415 call_user_func_array( array( $this, 'dispatch' ), $args );
417 if ( count( $ids ) ) {
419 array_unshift( $args, 'doOrphanList' );
420 call_user_func_array( array( $this, 'dispatch' ), $args );
423 $startId = $row->bt_text_id
;
424 $this->report( 'orphans', $i, $numOrphans );
426 $this->report( 'orphans', $i, $numOrphans );
427 $this->info( "All orphans queued." );
431 * Main entry point for worker processes
433 function executeChild() {
434 $this->debug( 'starting' );
437 while ( !feof( STDIN
) ) {
438 $line = rtrim( fgets( STDIN
) );
442 $this->debug( $line );
443 $args = explode( ' ', $line );
444 $cmd = array_shift( $args );
447 $this->doPage( intval( $args[0] ) );
450 $this->doOrphanList( array_map( 'intval', $args ) );
455 $this->waitForSlaves();
460 * Move tracked text in a given page
464 function doPage( $pageId ) {
465 $title = Title
::newFromId( $pageId );
467 $titleText = $title->getPrefixedText();
469 $titleText = '[deleted]';
471 $dbr = wfGetDB( DB_SLAVE
);
473 // Finish any incomplete transactions
474 if ( !$this->copyOnly
) {
475 $this->finishIncompleteMoves( array( 'bt_page' => $pageId ) );
480 $trx = new CgzCopyTransaction( $this, $this->pageBlobClass
);
484 array( 'blob_tracking', 'text' ),
487 'bt_page' => $pageId,
488 'bt_text_id > ' . $dbr->addQuotes( $startId ),
490 'bt_new_url IS NULL',
495 'ORDER BY' => 'bt_text_id',
496 'LIMIT' => $this->batchSize
499 if ( !$res->numRows() ) {
504 foreach ( $res as $row ) {
505 if ( $lastTextId == $row->bt_text_id
) {
506 // Duplicate (null edit)
509 $lastTextId = $row->bt_text_id
;
511 $text = Revision
::getRevisionText( $row );
512 if ( $text === false ) {
513 $this->critical( "Error loading {$row->bt_rev_id}/{$row->bt_text_id}" );
518 if ( !$trx->addItem( $text, $row->bt_text_id
) ) {
519 $this->debug( "$titleText: committing blob with " . $trx->getSize() . " items" );
521 $trx = new CgzCopyTransaction( $this, $this->pageBlobClass
);
522 $this->waitForSlaves();
525 $startId = $row->bt_text_id
;
528 $this->debug( "$titleText: committing blob with " . $trx->getSize() . " items" );
533 * Atomic move operation.
535 * Write the new URL to the text table and set the bt_moved flag.
537 * This is done in a single transaction to provide restartable behavior
540 * The transaction is kept short to reduce locking.
545 function moveTextRow( $textId, $url ) {
546 if ( $this->copyOnly
) {
547 $this->critical( "Internal error: can't call moveTextRow() in --copy-only mode" );
550 $dbw = wfGetDB( DB_MASTER
);
551 $dbw->begin( __METHOD__
);
552 $dbw->update( 'text',
555 'old_flags' => 'external,utf-8',
562 $dbw->update( 'blob_tracking',
563 array( 'bt_moved' => 1 ),
564 array( 'bt_text_id' => $textId ),
567 $dbw->commit( __METHOD__
);
571 * Moves are done in two phases: bt_new_url and then bt_moved.
572 * - bt_new_url indicates that the text has been copied to the new cluster.
573 * - bt_moved indicates that the text table has been updated.
575 * This function completes any moves that only have done bt_new_url. This
576 * can happen when the script is interrupted, or when --copy-only is used.
578 * @param array $conds
580 function finishIncompleteMoves( $conds ) {
581 $dbr = wfGetDB( DB_SLAVE
);
584 $conds = array_merge( $conds, array(
586 'bt_new_url IS NOT NULL'
589 $res = $dbr->select( 'blob_tracking',
591 array_merge( $conds, array( 'bt_text_id > ' . $dbr->addQuotes( $startId ) ) ),
594 'ORDER BY' => 'bt_text_id',
595 'LIMIT' => $this->batchSize
,
598 if ( !$res->numRows() ) {
601 $this->debug( 'Incomplete: ' . $res->numRows() . ' rows' );
602 foreach ( $res as $row ) {
603 $this->moveTextRow( $row->bt_text_id
, $row->bt_new_url
);
604 if ( $row->bt_text_id %
10 == 0 ) {
605 $this->waitForSlaves();
608 $startId = $row->bt_text_id
;
613 * Returns the name of the next target cluster
616 function getTargetCluster() {
617 $cluster = next( $this->destClusters
);
618 if ( $cluster === false ) {
619 $cluster = reset( $this->destClusters
);
625 * Gets a DB master connection for the given external cluster name
626 * @param string $cluster
627 * @return DatabaseBase
629 function getExtDB( $cluster ) {
630 $lb = wfGetLBFactory()->getExternalLB( $cluster );
631 return $lb->getConnection( DB_MASTER
);
635 * Move an orphan text_id to the new cluster
637 * @param array $textIds
639 function doOrphanList( $textIds ) {
640 // Finish incomplete moves
641 if ( !$this->copyOnly
) {
642 $this->finishIncompleteMoves( array( 'bt_text_id' => $textIds ) );
646 $trx = new CgzCopyTransaction( $this, $this->orphanBlobClass
);
648 $res = wfGetDB( DB_SLAVE
)->select(
649 array( 'text', 'blob_tracking' ),
650 array( 'old_id', 'old_text', 'old_flags' ),
652 'old_id' => $textIds,
660 foreach ( $res as $row ) {
661 $text = Revision
::getRevisionText( $row );
662 if ( $text === false ) {
663 $this->critical( "Error: cannot load revision text for old_id={$row->old_id}" );
667 if ( !$trx->addItem( $text, $row->old_id
) ) {
668 $this->debug( "[orphan]: committing blob with " . $trx->getSize() . " rows" );
670 $trx = new CgzCopyTransaction( $this, $this->orphanBlobClass
);
671 $this->waitForSlaves();
674 $this->debug( "[orphan]: committing blob with " . $trx->getSize() . " rows" );
679 * Wait for slaves (quietly)
681 function waitForSlaves() {
684 list( $host, $maxLag ) = $lb->getMaxLag();
694 * Class to represent a recompression operation for a single CGZ blob
696 class CgzCopyTransaction
{
703 * Create a transaction from a RecompressTracked object
705 function __construct( $parent, $blobClass ) {
706 $this->blobClass
= $blobClass;
708 $this->texts
= array();
709 $this->parent
= $parent;
714 * Returns false if it's ready to commit.
715 * @param string $text
719 function addItem( $text, $textId ) {
721 $class = $this->blobClass
;
722 $this->cgz
= new $class;
724 $hash = $this->cgz
->addItem( $text );
725 $this->referrers
[$textId] = $hash;
726 $this->texts
[$textId] = $text;
727 return $this->cgz
->isHappy();
731 return count( $this->texts
);
735 * Recompress text after some aberrant modification
737 function recompress() {
738 $class = $this->blobClass
;
739 $this->cgz
= new $class;
740 $this->referrers
= array();
741 foreach ( $this->texts
as $textId => $text ) {
742 $hash = $this->cgz
->addItem( $text );
743 $this->referrers
[$textId] = $hash;
749 * Does nothing if no text items have been added.
750 * May skip the move if --copy-only is set.
753 $originalCount = count( $this->texts
);
754 if ( !$originalCount ) {
758 // Check to see if the target text_ids have been moved already.
760 // We originally read from the slave, so this can happen when a single
761 // text_id is shared between multiple pages. It's rare, but possible
762 // if a delete/move/undelete cycle splits up a null edit.
764 // We do a locking read to prevent closer-run race conditions.
765 $dbw = wfGetDB( DB_MASTER
);
766 $dbw->begin( __METHOD__
);
767 $res = $dbw->select( 'blob_tracking',
768 array( 'bt_text_id', 'bt_moved' ),
769 array( 'bt_text_id' => array_keys( $this->referrers
) ),
770 __METHOD__
, array( 'FOR UPDATE' ) );
772 foreach ( $res as $row ) {
773 if ( $row->bt_moved
) {
774 # This row has already been moved, remove it
775 $this->parent
->debug( "TRX: conflict detected in old_id={$row->bt_text_id}" );
776 unset( $this->texts
[$row->bt_text_id
] );
781 // Recompress the blob if necessary
783 if ( !count( $this->texts
) ) {
784 // All have been moved already
785 if ( $originalCount > 1 ) {
786 // This is suspcious, make noise
787 $this->critical( "Warning: concurrent operation detected, are there two conflicting " .
788 "processes running, doing the same job?" );
795 // Insert the data into the destination cluster
796 $targetCluster = $this->parent
->getTargetCluster();
797 $store = $this->parent
->store
;
798 $targetDB = $store->getMaster( $targetCluster );
799 $targetDB->clearFlag( DBO_TRX
); // we manage the transactions
800 $targetDB->begin( __METHOD__
);
801 $baseUrl = $this->parent
->store
->store( $targetCluster, serialize( $this->cgz
) );
803 // Write the new URLs to the blob_tracking table
804 foreach ( $this->referrers
as $textId => $hash ) {
805 $url = $baseUrl . '/' . $hash;
806 $dbw->update( 'blob_tracking',
807 array( 'bt_new_url' => $url ),
809 'bt_text_id' => $textId,
810 'bt_moved' => 0, # Check for concurrent conflicting update
816 $targetDB->commit( __METHOD__
);
817 // Critical section here: interruption at this point causes blob duplication
818 // Reversing the order of the commits would cause data loss instead
819 $dbw->commit( __METHOD__
);
821 // Write the new URLs to the text table and set the moved flag
822 if ( !$this->parent
->copyOnly
) {
823 foreach ( $this->referrers
as $textId => $hash ) {
824 $url = $baseUrl . '/' . $hash;
825 $this->parent
->moveTextRow( $textId, $url );