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();
52 /** @var Array (partition name => JobQueue) reverse sorted by weight */
53 protected $partitionQueues = array();
55 protected $partitionPushRing;
59 protected $maxPartitionsTry; // integer; maximum number of partitions to try
61 const CACHE_TTL_SHORT
= 30; // integer; seconds to cache info without re-validating
62 const CACHE_TTL_LONG
= 300; // integer; seconds to cache info that is kept up to date
66 * - sectionsByWiki : A map of wiki IDs to section names.
67 * Wikis will default to using the section "default".
68 * - partitionsBySection : Map of section names to maps of (partition name => weight).
69 * A section called 'default' must be defined if not all wikis
70 * have explicitly defined sections.
71 * - configByPartition : Map of queue partition names to configuration arrays.
72 * These configuration arrays are passed to JobQueue::factory().
73 * The options set here are overriden by those passed to this
74 * the federated queue itself (e.g. 'order' and 'claimTTL').
75 * - partitionsNoPush : List of partition names that can handle pop() but not push().
76 * This can be used to migrate away from a certain partition.
77 * - maxPartitionsTry : Maximum number of times to attempt job insertion using
78 * different partition queues. This improves availability
79 * during failure, at the cost of added latency and somewhat
80 * less reliable job de-duplication mechanisms.
81 * @param array $params
83 protected function __construct( array $params ) {
84 parent
::__construct( $params );
85 $section = isset( $params['sectionsByWiki'][$this->wiki
] )
86 ?
$params['sectionsByWiki'][$this->wiki
]
88 if ( !isset( $params['partitionsBySection'][$section] ) ) {
89 throw new MWException( "No configuration for section '$section'." );
91 $this->maxPartitionsTry
= isset( $params['maxPartitionsTry'] )
92 ?
$params['maxPartitionsTry']
94 // Get the full partition map
95 $this->partitionMap
= $params['partitionsBySection'][$section];
96 arsort( $this->partitionMap
, SORT_NUMERIC
);
97 // Get the partitions jobs can actually be pushed to
98 $partitionPushMap = $this->partitionMap
;
99 if ( isset( $params['partitionsNoPush'] ) ) {
100 foreach ( $params['partitionsNoPush'] as $partition ) {
101 unset( $partitionPushMap[$partition] );
104 // Get the config to pass to merge into each partition queue config
105 $baseConfig = $params;
106 foreach ( array( 'class', 'sectionsByWiki', 'maxPartitionsTry',
107 'partitionsBySection', 'configByPartition', 'partitionsNoPush' ) as $o )
109 unset( $baseConfig[$o] ); // partition queue doesn't care about this
111 // Get the partition queue objects
112 foreach ( $this->partitionMap
as $partition => $w ) {
113 if ( !isset( $params['configByPartition'][$partition] ) ) {
114 throw new MWException( "No configuration for partition '$partition'." );
116 $this->partitionQueues
[$partition] = JobQueue
::factory(
117 $baseConfig +
$params['configByPartition'][$partition] );
119 // Get the ring of partitions to push jobs into
120 $this->partitionPushRing
= new HashRing( $partitionPushMap );
121 // Aggregate cache some per-queue values if there are multiple partition queues
122 $this->cache
= count( $this->partitionMap
) > 1 ?
wfGetMainCache() : new EmptyBagOStuff();
125 protected function supportedOrders() {
126 // No FIFO due to partitioning, though "rough timestamp order" is supported
127 return array( 'undefined', 'random', 'timestamp' );
130 protected function optimalOrder() {
131 return 'undefined'; // defer to the partitions
134 protected function supportsDelayedJobs() {
135 return true; // defer checks to the partitions
138 protected function doIsEmpty() {
139 $key = $this->getCacheKey( 'empty' );
141 $isEmpty = $this->cache
->get( $key );
142 if ( $isEmpty === 'true' ) {
144 } elseif ( $isEmpty === 'false' ) {
148 foreach ( $this->partitionQueues
as $queue ) {
150 if ( !$queue->doIsEmpty() ) {
151 $this->cache
->add( $key, 'false', self
::CACHE_TTL_LONG
);
154 } catch ( JobQueueError
$e ) {
155 MWExceptionHandler
::logException( $e );
159 $this->cache
->add( $key, 'true', self
::CACHE_TTL_LONG
);
163 protected function doGetSize() {
164 return $this->getCrossPartitionSum( 'size', 'doGetSize' );
167 protected function doGetAcquiredCount() {
168 return $this->getCrossPartitionSum( 'acquiredcount', 'doGetAcquiredCount' );
171 protected function doGetDelayedCount() {
172 return $this->getCrossPartitionSum( 'delayedcount', 'doGetDelayedCount' );
175 protected function doGetAbandonedCount() {
176 return $this->getCrossPartitionSum( 'abandonedcount', 'doGetAbandonedCount' );
180 * @param string $type
181 * @param string $method
184 protected function getCrossPartitionSum( $type, $method ) {
185 $key = $this->getCacheKey( $type );
187 $count = $this->cache
->get( $key );
188 if ( is_int( $count ) ) {
193 foreach ( $this->partitionQueues
as $queue ) {
195 $count +
= $queue->$method();
196 } catch ( JobQueueError
$e ) {
197 MWExceptionHandler
::logException( $e );
201 $this->cache
->set( $key, $count, self
::CACHE_TTL_SHORT
);
205 protected function doBatchPush( array $jobs, $flags ) {
206 // Local ring variable that may be changed to point to a new ring on failure
207 $partitionRing = $this->partitionPushRing
;
208 // Try to insert the jobs and update $partitionsTry on any failures.
209 // Retry to insert any remaning jobs again, ignoring the bad partitions.
211 for ( $i = $this->maxPartitionsTry
; $i > 0 && count( $jobsLeft ); --$i ) {
212 $jobsLeft = $this->tryJobInsertions( $jobsLeft, $partitionRing, $flags );
214 if ( count( $jobsLeft ) ) {
215 throw new JobQueueError(
216 "Could not insert job(s), {$this->maxPartitionsTry} partitions tried." );
223 * @param HashRing $partitionRing
224 * @param integer $flags
225 * @return array List of Job object that could not be inserted
227 protected function tryJobInsertions( array $jobs, HashRing
&$partitionRing, $flags ) {
230 // Because jobs are spread across partitions, per-job de-duplication needs
231 // to use a consistent hash to avoid allowing duplicate jobs per partition.
232 // When inserting a batch of de-duplicated jobs, QOS_ATOMIC is disregarded.
233 $uJobsByPartition = array(); // (partition name => job list)
234 foreach ( $jobs as $key => $job ) {
235 if ( $job->ignoreDuplicates() ) {
236 $sha1 = sha1( serialize( $job->getDeduplicationInfo() ) );
237 $uJobsByPartition[$partitionRing->getLocation( $sha1 )][] = $job;
238 unset( $jobs[$key] );
241 // Get the batches of jobs that are not de-duplicated
242 if ( $flags & self
::QOS_ATOMIC
) {
243 $nuJobBatches = array( $jobs ); // all or nothing
245 // Split the jobs into batches and spread them out over servers if there
246 // are many jobs. This helps keep the partitions even. Otherwise, send all
247 // the jobs to a single partition queue to avoids the extra connections.
248 $nuJobBatches = array_chunk( $jobs, 300 );
251 // Insert the de-duplicated jobs into the queues...
252 foreach ( $uJobsByPartition as $partition => $jobBatch ) {
253 $queue = $this->partitionQueues
[$partition];
255 $ok = $queue->doBatchPush( $jobBatch, $flags | self
::QOS_ATOMIC
);
256 } catch ( JobQueueError
$e ) {
258 MWExceptionHandler
::logException( $e );
261 $key = $this->getCacheKey( 'empty' );
262 $this->cache
->set( $key, 'false', JobQueueDB
::CACHE_TTL_LONG
);
264 $partitionRing = $partitionRing->newWithoutLocation( $partition ); // blacklist
265 if ( !$partitionRing ) {
266 throw new JobQueueError( "Could not insert job(s), all partitions are down." );
268 $jobsLeft = array_merge( $jobsLeft, $jobBatch ); // not inserted
272 // Insert the jobs that are not de-duplicated into the queues...
273 foreach ( $nuJobBatches as $jobBatch ) {
274 $partition = ArrayUtils
::pickRandom( $partitionRing->getLocationWeights() );
275 $queue = $this->partitionQueues
[$partition];
277 $ok = $queue->doBatchPush( $jobBatch, $flags | self
::QOS_ATOMIC
);
278 } catch ( JobQueueError
$e ) {
280 MWExceptionHandler
::logException( $e );
283 $key = $this->getCacheKey( 'empty' );
284 $this->cache
->set( $key, 'false', JobQueueDB
::CACHE_TTL_LONG
);
286 $partitionRing = $partitionRing->newWithoutLocation( $partition ); // blacklist
287 if ( !$partitionRing ) {
288 throw new JobQueueError( "Could not insert job(s), all partitions are down." );
290 $jobsLeft = array_merge( $jobsLeft, $jobBatch ); // not inserted
297 protected function doPop() {
298 $key = $this->getCacheKey( 'empty' );
300 $isEmpty = $this->cache
->get( $key );
301 if ( $isEmpty === 'true' ) {
305 $partitionsTry = $this->partitionMap
; // (partition => weight)
307 while ( count( $partitionsTry ) ) {
308 $partition = ArrayUtils
::pickRandom( $partitionsTry );
309 if ( $partition === false ) {
310 break; // all partitions at 0 weight
312 $queue = $this->partitionQueues
[$partition];
314 $job = $queue->pop();
315 } catch ( JobQueueError
$e ) {
317 MWExceptionHandler
::logException( $e );
320 $job->metadata
['QueuePartition'] = $partition;
323 unset( $partitionsTry[$partition] ); // blacklist partition
327 $this->cache
->set( $key, 'true', JobQueueDB
::CACHE_TTL_LONG
);
331 protected function doAck( Job
$job ) {
332 if ( !isset( $job->metadata
['QueuePartition'] ) ) {
333 throw new MWException( "The given job has no defined partition name." );
335 return $this->partitionQueues
[$job->metadata
['QueuePartition']]->ack( $job );
338 protected function doIsRootJobOldDuplicate( Job
$job ) {
339 $params = $job->getRootJobParams();
340 $partitions = $this->partitionPushRing
->getLocations( $params['rootJobSignature'], 2 );
342 return $this->partitionQueues
[$partitions[0]]->doIsRootJobOldDuplicate( $job );
343 } catch ( JobQueueError
$e ) {
344 if ( isset( $partitions[1] ) ) { // check fallback partition
345 return $this->partitionQueues
[$partitions[1]]->doIsRootJobOldDuplicate( $job );
351 protected function doDeduplicateRootJob( Job
$job ) {
352 $params = $job->getRootJobParams();
353 $partitions = $this->partitionPushRing
->getLocations( $params['rootJobSignature'], 2 );
355 return $this->partitionQueues
[$partitions[0]]->doDeduplicateRootJob( $job );
356 } catch ( JobQueueError
$e ) {
357 if ( isset( $partitions[1] ) ) { // check fallback partition
358 return $this->partitionQueues
[$partitions[1]]->doDeduplicateRootJob( $job );
364 protected function doDelete() {
365 foreach ( $this->partitionQueues
as $queue ) {
368 } catch ( JobQueueError
$e ) {
369 MWExceptionHandler
::logException( $e );
374 protected function doWaitForBackups() {
375 foreach ( $this->partitionQueues
as $queue ) {
377 $queue->waitForBackups();
378 } catch ( JobQueueError
$e ) {
379 MWExceptionHandler
::logException( $e );
384 protected function doGetPeriodicTasks() {
386 foreach ( $this->partitionQueues
as $partition => $queue ) {
387 foreach ( $queue->getPeriodicTasks() as $task => $def ) {
388 $tasks["{$partition}:{$task}"] = $def;
394 protected function doFlushCaches() {
395 static $types = array(
402 foreach ( $types as $type ) {
403 $this->cache
->delete( $this->getCacheKey( $type ) );
405 foreach ( $this->partitionQueues
as $queue ) {
406 $queue->doFlushCaches();
410 public function getAllQueuedJobs() {
411 $iterator = new AppendIterator();
412 foreach ( $this->partitionQueues
as $queue ) {
413 $iterator->append( $queue->getAllQueuedJobs() );
418 public function getAllDelayedJobs() {
419 $iterator = new AppendIterator();
420 foreach ( $this->partitionQueues
as $queue ) {
421 $iterator->append( $queue->getAllDelayedJobs() );
426 public function getCoalesceLocationInternal() {
427 return "JobQueueFederated:wiki:{$this->wiki}" .
428 sha1( serialize( array_keys( $this->partitionMap
) ) );
431 protected function doGetSiblingQueuesWithJobs( array $types ) {
433 foreach ( $this->partitionQueues
as $queue ) {
435 $nonEmpty = $queue->doGetSiblingQueuesWithJobs( $types );
436 if ( is_array( $nonEmpty ) ) {
437 $result = array_unique( array_merge( $result, $nonEmpty ) );
439 return null; // not supported on all partitions; bail
441 if ( count( $result ) == count( $types ) ) {
442 break; // short-circuit
444 } catch ( JobQueueError
$e ) {
445 MWExceptionHandler
::logException( $e );
448 return array_values( $result );
451 protected function doGetSiblingQueueSizes( array $types ) {
453 foreach ( $this->partitionQueues
as $queue ) {
455 $sizes = $queue->doGetSiblingQueueSizes( $types );
456 if ( is_array( $sizes ) ) {
457 foreach ( $sizes as $type => $size ) {
458 $result[$type] = isset( $result[$type] ) ?
$result[$type] +
$size : $size;
461 return null; // not supported on all partitions; bail
463 } catch ( JobQueueError
$e ) {
464 MWExceptionHandler
::logException( $e );
470 public function setTestingPrefix( $key ) {
471 foreach ( $this->partitionQueues
as $queue ) {
472 $queue->setTestingPrefix( $key );
479 private function getCacheKey( $property ) {
480 list( $db, $prefix ) = wfSplitWikiID( $this->wiki
);
481 return wfForeignMemcKey( $db, $prefix, 'jobqueue', $this->type
, $property );