3 * Job queue code for federated queues.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @author Aaron Schulz
25 * Class to handle enqueueing and running of background jobs for federated queues
27 * This class allows for queues to be partitioned into smaller queues.
28 * A partition is defined by the configuration for a JobQueue instance.
29 * For example, one can set $wgJobTypeConf['refreshLinks'] to point to a
30 * JobQueueFederated instance, which itself would consist of three JobQueueRedis
31 * instances, each using their own redis server. This would allow for the jobs
32 * to be split (evenly or based on weights) accross multiple servers if a single
33 * server becomes impractical or expensive. Different JobQueue classes can be mixed.
35 * The basic queue configuration (e.g. "order", "claimTTL") of a federated queue
36 * is inherited by the partition queues. Additional configuration defines what
37 * section each wiki is in, what partition queues each section uses (and their weight),
38 * and the JobQueue configuration for each partition. Some sections might only need a
39 * single queue partition, like the sections for groups of small wikis.
41 * If used for performance, then $wgMainCacheType should be set to memcached/redis.
42 * Note that "fifo" cannot be used for the ordering, since the data is distributed.
43 * One can still use "timestamp" instead, as in "roughly timestamp ordered". Also,
44 * queue classes used by this should ignore down servers (with TTL) to avoid slowness.
49 class JobQueueFederated
extends JobQueue
{
50 /** @var array (partition name => weight) reverse sorted by weight */
51 protected $partitionMap = array();
53 /** @var array (partition name => JobQueue) reverse sorted by weight */
54 protected $partitionQueues = array();
57 protected $partitionPushRing;
62 /** @var int Maximum number of partitions to try */
63 protected $maxPartitionsTry;
65 const CACHE_TTL_SHORT
= 30; // integer; seconds to cache info without re-validating
66 const CACHE_TTL_LONG
= 300; // integer; seconds to cache info that is kept up to date
70 * - sectionsByWiki : A map of wiki IDs to section names.
71 * Wikis will default to using the section "default".
72 * - partitionsBySection : Map of section names to maps of (partition name => weight).
73 * A section called 'default' must be defined if not all wikis
74 * have explicitly defined sections.
75 * - configByPartition : Map of queue partition names to configuration arrays.
76 * These configuration arrays are passed to JobQueue::factory().
77 * The options set here are overriden by those passed to this
78 * the federated queue itself (e.g. 'order' and 'claimTTL').
79 * - partitionsNoPush : List of partition names that can handle pop() but not push().
80 * This can be used to migrate away from a certain partition.
81 * - maxPartitionsTry : Maximum number of times to attempt job insertion using
82 * different partition queues. This improves availability
83 * during failure, at the cost of added latency and somewhat
84 * less reliable job de-duplication mechanisms.
85 * @param array $params
88 protected function __construct( array $params ) {
89 parent
::__construct( $params );
90 $section = isset( $params['sectionsByWiki'][$this->wiki
] )
91 ?
$params['sectionsByWiki'][$this->wiki
]
93 if ( !isset( $params['partitionsBySection'][$section] ) ) {
94 throw new MWException( "No configuration for section '$section'." );
96 $this->maxPartitionsTry
= isset( $params['maxPartitionsTry'] )
97 ?
$params['maxPartitionsTry']
99 // Get the full partition map
100 $this->partitionMap
= $params['partitionsBySection'][$section];
101 arsort( $this->partitionMap
, SORT_NUMERIC
);
102 // Get the partitions jobs can actually be pushed to
103 $partitionPushMap = $this->partitionMap
;
104 if ( isset( $params['partitionsNoPush'] ) ) {
105 foreach ( $params['partitionsNoPush'] as $partition ) {
106 unset( $partitionPushMap[$partition] );
109 // Get the config to pass to merge into each partition queue config
110 $baseConfig = $params;
111 foreach ( array( 'class', 'sectionsByWiki', 'maxPartitionsTry',
112 'partitionsBySection', 'configByPartition', 'partitionsNoPush' ) as $o
114 unset( $baseConfig[$o] ); // partition queue doesn't care about this
116 // Get the partition queue objects
117 foreach ( $this->partitionMap
as $partition => $w ) {
118 if ( !isset( $params['configByPartition'][$partition] ) ) {
119 throw new MWException( "No configuration for partition '$partition'." );
121 $this->partitionQueues
[$partition] = JobQueue
::factory(
122 $baseConfig +
$params['configByPartition'][$partition] );
124 // Get the ring of partitions to push jobs into
125 $this->partitionPushRing
= new HashRing( $partitionPushMap );
126 // Aggregate cache some per-queue values if there are multiple partition queues
127 $this->cache
= count( $this->partitionMap
) > 1 ?
wfGetMainCache() : new EmptyBagOStuff();
130 protected function supportedOrders() {
131 // No FIFO due to partitioning, though "rough timestamp order" is supported
132 return array( 'undefined', 'random', 'timestamp' );
135 protected function optimalOrder() {
136 return 'undefined'; // defer to the partitions
139 protected function supportsDelayedJobs() {
140 return true; // defer checks to the partitions
143 protected function doIsEmpty() {
144 $key = $this->getCacheKey( 'empty' );
146 $isEmpty = $this->cache
->get( $key );
147 if ( $isEmpty === 'true' ) {
149 } elseif ( $isEmpty === 'false' ) {
155 foreach ( $this->partitionQueues
as $queue ) {
157 $empty = $empty && $queue->doIsEmpty();
158 } catch ( JobQueueError
$e ) {
160 MWExceptionHandler
::logException( $e );
163 $this->throwErrorIfAllPartitionsDown( $failed );
165 $this->cache
->add( $key, $empty ?
'true' : 'false', self
::CACHE_TTL_LONG
);
169 protected function doGetSize() {
170 return $this->getCrossPartitionSum( 'size', 'doGetSize' );
173 protected function doGetAcquiredCount() {
174 return $this->getCrossPartitionSum( 'acquiredcount', 'doGetAcquiredCount' );
177 protected function doGetDelayedCount() {
178 return $this->getCrossPartitionSum( 'delayedcount', 'doGetDelayedCount' );
181 protected function doGetAbandonedCount() {
182 return $this->getCrossPartitionSum( 'abandonedcount', 'doGetAbandonedCount' );
186 * @param string $type
187 * @param string $method
190 protected function getCrossPartitionSum( $type, $method ) {
191 $key = $this->getCacheKey( $type );
193 $count = $this->cache
->get( $key );
194 if ( is_int( $count ) ) {
199 foreach ( $this->partitionQueues
as $queue ) {
201 $count +
= $queue->$method();
202 } catch ( JobQueueError
$e ) {
204 MWExceptionHandler
::logException( $e );
207 $this->throwErrorIfAllPartitionsDown( $failed );
209 $this->cache
->set( $key, $count, self
::CACHE_TTL_SHORT
);
214 protected function doBatchPush( array $jobs, $flags ) {
215 // Local ring variable that may be changed to point to a new ring on failure
216 $partitionRing = $this->partitionPushRing
;
217 // Try to insert the jobs and update $partitionsTry on any failures.
218 // Retry to insert any remaning jobs again, ignoring the bad partitions.
220 for ( $i = $this->maxPartitionsTry
; $i > 0 && count( $jobsLeft ); --$i ) {
221 $jobsLeft = $this->tryJobInsertions( $jobsLeft, $partitionRing, $flags );
223 if ( count( $jobsLeft ) ) {
224 throw new JobQueueError(
225 "Could not insert job(s), {$this->maxPartitionsTry} partitions tried." );
233 * @param HashRing $partitionRing
235 * @throws JobQueueError
236 * @return array List of Job object that could not be inserted
238 protected function tryJobInsertions( array $jobs, HashRing
&$partitionRing, $flags ) {
241 // Because jobs are spread across partitions, per-job de-duplication needs
242 // to use a consistent hash to avoid allowing duplicate jobs per partition.
243 // When inserting a batch of de-duplicated jobs, QOS_ATOMIC is disregarded.
244 $uJobsByPartition = array(); // (partition name => job list)
246 foreach ( $jobs as $key => $job ) {
247 if ( $job->ignoreDuplicates() ) {
248 $sha1 = sha1( serialize( $job->getDeduplicationInfo() ) );
249 $uJobsByPartition[$partitionRing->getLocation( $sha1 )][] = $job;
250 unset( $jobs[$key] );
253 // Get the batches of jobs that are not de-duplicated
254 if ( $flags & self
::QOS_ATOMIC
) {
255 $nuJobBatches = array( $jobs ); // all or nothing
257 // Split the jobs into batches and spread them out over servers if there
258 // are many jobs. This helps keep the partitions even. Otherwise, send all
259 // the jobs to a single partition queue to avoids the extra connections.
260 $nuJobBatches = array_chunk( $jobs, 300 );
263 // Insert the de-duplicated jobs into the queues...
264 foreach ( $uJobsByPartition as $partition => $jobBatch ) {
265 /** @var JobQueue $queue */
266 $queue = $this->partitionQueues
[$partition];
268 $ok = $queue->doBatchPush( $jobBatch, $flags | self
::QOS_ATOMIC
);
269 } catch ( JobQueueError
$e ) {
271 MWExceptionHandler
::logException( $e );
274 $key = $this->getCacheKey( 'empty' );
275 $this->cache
->set( $key, 'false', JobQueueDB
::CACHE_TTL_LONG
);
277 $partitionRing = $partitionRing->newWithoutLocation( $partition ); // blacklist
278 if ( !$partitionRing ) {
279 throw new JobQueueError( "Could not insert job(s), no partitions available." );
281 $jobsLeft = array_merge( $jobsLeft, $jobBatch ); // not inserted
285 // Insert the jobs that are not de-duplicated into the queues...
286 foreach ( $nuJobBatches as $jobBatch ) {
287 $partition = ArrayUtils
::pickRandom( $partitionRing->getLocationWeights() );
288 $queue = $this->partitionQueues
[$partition];
290 $ok = $queue->doBatchPush( $jobBatch, $flags | self
::QOS_ATOMIC
);
291 } catch ( JobQueueError
$e ) {
293 MWExceptionHandler
::logException( $e );
296 $key = $this->getCacheKey( 'empty' );
297 $this->cache
->set( $key, 'false', JobQueueDB
::CACHE_TTL_LONG
);
299 $partitionRing = $partitionRing->newWithoutLocation( $partition ); // blacklist
300 if ( !$partitionRing ) {
301 throw new JobQueueError( "Could not insert job(s), no partitions available." );
303 $jobsLeft = array_merge( $jobsLeft, $jobBatch ); // not inserted
310 protected function doPop() {
311 $key = $this->getCacheKey( 'empty' );
313 $isEmpty = $this->cache
->get( $key );
314 if ( $isEmpty === 'true' ) {
318 $partitionsTry = $this->partitionMap
; // (partition => weight)
321 while ( count( $partitionsTry ) ) {
322 $partition = ArrayUtils
::pickRandom( $partitionsTry );
323 if ( $partition === false ) {
324 break; // all partitions at 0 weight
327 /** @var JobQueue $queue */
328 $queue = $this->partitionQueues
[$partition];
330 $job = $queue->pop();
331 } catch ( JobQueueError
$e ) {
333 MWExceptionHandler
::logException( $e );
337 $job->metadata
['QueuePartition'] = $partition;
341 unset( $partitionsTry[$partition] ); // blacklist partition
344 $this->throwErrorIfAllPartitionsDown( $failed );
346 $this->cache
->set( $key, 'true', JobQueueDB
::CACHE_TTL_LONG
);
351 protected function doAck( Job
$job ) {
352 if ( !isset( $job->metadata
['QueuePartition'] ) ) {
353 throw new MWException( "The given job has no defined partition name." );
356 return $this->partitionQueues
[$job->metadata
['QueuePartition']]->ack( $job );
359 protected function doIsRootJobOldDuplicate( Job
$job ) {
360 $params = $job->getRootJobParams();
361 $partitions = $this->partitionPushRing
->getLocations( $params['rootJobSignature'], 2 );
363 return $this->partitionQueues
[$partitions[0]]->doIsRootJobOldDuplicate( $job );
364 } catch ( JobQueueError
$e ) {
365 if ( isset( $partitions[1] ) ) { // check fallback partition
366 return $this->partitionQueues
[$partitions[1]]->doIsRootJobOldDuplicate( $job );
373 protected function doDeduplicateRootJob( Job
$job ) {
374 $params = $job->getRootJobParams();
375 $partitions = $this->partitionPushRing
->getLocations( $params['rootJobSignature'], 2 );
377 return $this->partitionQueues
[$partitions[0]]->doDeduplicateRootJob( $job );
378 } catch ( JobQueueError
$e ) {
379 if ( isset( $partitions[1] ) ) { // check fallback partition
380 return $this->partitionQueues
[$partitions[1]]->doDeduplicateRootJob( $job );
387 protected function doDelete() {
389 /** @var JobQueue $queue */
390 foreach ( $this->partitionQueues
as $queue ) {
393 } catch ( JobQueueError
$e ) {
395 MWExceptionHandler
::logException( $e );
398 $this->throwErrorIfAllPartitionsDown( $failed );
402 protected function doWaitForBackups() {
404 /** @var JobQueue $queue */
405 foreach ( $this->partitionQueues
as $queue ) {
407 $queue->waitForBackups();
408 } catch ( JobQueueError
$e ) {
410 MWExceptionHandler
::logException( $e );
413 $this->throwErrorIfAllPartitionsDown( $failed );
416 protected function doGetPeriodicTasks() {
418 /** @var JobQueue $queue */
419 foreach ( $this->partitionQueues
as $partition => $queue ) {
420 foreach ( $queue->getPeriodicTasks() as $task => $def ) {
421 $tasks["{$partition}:{$task}"] = $def;
428 protected function doFlushCaches() {
429 static $types = array(
437 foreach ( $types as $type ) {
438 $this->cache
->delete( $this->getCacheKey( $type ) );
441 /** @var JobQueue $queue */
442 foreach ( $this->partitionQueues
as $queue ) {
443 $queue->doFlushCaches();
447 public function getAllQueuedJobs() {
448 $iterator = new AppendIterator();
450 /** @var JobQueue $queue */
451 foreach ( $this->partitionQueues
as $queue ) {
452 $iterator->append( $queue->getAllQueuedJobs() );
458 public function getAllDelayedJobs() {
459 $iterator = new AppendIterator();
461 /** @var JobQueue $queue */
462 foreach ( $this->partitionQueues
as $queue ) {
463 $iterator->append( $queue->getAllDelayedJobs() );
469 public function getCoalesceLocationInternal() {
470 return "JobQueueFederated:wiki:{$this->wiki}" .
471 sha1( serialize( array_keys( $this->partitionMap
) ) );
474 protected function doGetSiblingQueuesWithJobs( array $types ) {
478 /** @var JobQueue $queue */
479 foreach ( $this->partitionQueues
as $queue ) {
481 $nonEmpty = $queue->doGetSiblingQueuesWithJobs( $types );
482 if ( is_array( $nonEmpty ) ) {
483 $result = array_unique( array_merge( $result, $nonEmpty ) );
485 return null; // not supported on all partitions; bail
487 if ( count( $result ) == count( $types ) ) {
488 break; // short-circuit
490 } catch ( JobQueueError
$e ) {
492 MWExceptionHandler
::logException( $e );
495 $this->throwErrorIfAllPartitionsDown( $failed );
497 return array_values( $result );
500 protected function doGetSiblingQueueSizes( array $types ) {
503 /** @var JobQueue $queue */
504 foreach ( $this->partitionQueues
as $queue ) {
506 $sizes = $queue->doGetSiblingQueueSizes( $types );
507 if ( is_array( $sizes ) ) {
508 foreach ( $sizes as $type => $size ) {
509 $result[$type] = isset( $result[$type] ) ?
$result[$type] +
$size : $size;
512 return null; // not supported on all partitions; bail
514 } catch ( JobQueueError
$e ) {
516 MWExceptionHandler
::logException( $e );
519 $this->throwErrorIfAllPartitionsDown( $failed );
525 * Throw an error if no partitions available
527 * @param int $down The number of up partitions down
529 * @throws JobQueueError
531 protected function throwErrorIfAllPartitionsDown( $down ) {
532 if ( $down >= count( $this->partitionQueues
) ) {
533 throw new JobQueueError( 'No queue partitions available.' );
537 public function setTestingPrefix( $key ) {
538 /** @var JobQueue $queue */
539 foreach ( $this->partitionQueues
as $queue ) {
540 $queue->setTestingPrefix( $key );
548 private function getCacheKey( $property ) {
549 list( $db, $prefix ) = wfSplitWikiID( $this->wiki
);
551 return wfForeignMemcKey( $db, $prefix, 'jobqueue', $this->type
, $property );