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 const CACHE_TTL_SHORT
= 30; // integer; seconds to cache info without re-validating
60 const CACHE_TTL_LONG
= 300; // integer; seconds to cache info that is kept up to date
64 * - sectionsByWiki : A map of wiki IDs to section names.
65 * Wikis will default to using the section "default".
66 * - partitionsBySection : Map of section names to maps of (partition name => weight).
67 * A section called 'default' must be defined if not all wikis
68 * have explicitly defined sections.
69 * - configByPartition : Map of queue partition names to configuration arrays.
70 * These configuration arrays are passed to JobQueue::factory().
71 * The options set here are overriden by those passed to this
72 * the federated queue itself (e.g. 'order' and 'claimTTL').
73 * - partitionsNoPush : List of partition names that can handle pop() but not push().
74 * This can be used to migrate away from a certain partition.
75 * @param array $params
77 protected function __construct( array $params ) {
78 parent
::__construct( $params );
79 $section = isset( $params['sectionsByWiki'][$this->wiki
] )
80 ?
$params['sectionsByWiki'][$this->wiki
]
82 if ( !isset( $params['partitionsBySection'][$section] ) ) {
83 throw new MWException( "No configuration for section '$section'." );
85 // Get the full partition map
86 $this->partitionMap
= $params['partitionsBySection'][$section];
87 arsort( $this->partitionMap
, SORT_NUMERIC
);
88 // Get the partitions jobs can actually be pushed to
89 $partitionPushMap = $this->partitionMap
;
90 if ( isset( $params['partitionsNoPush'] ) ) {
91 foreach ( $params['partitionsNoPush'] as $partition ) {
92 unset( $partitionPushMap[$partition] );
95 // Get the config to pass to merge into each partition queue config
96 $baseConfig = $params;
97 foreach ( array( 'class', 'sectionsByWiki',
98 'partitionsBySection', 'configByPartition', 'partitionsNoPush' ) as $o )
100 unset( $baseConfig[$o] );
102 // Get the partition queue objects
103 foreach ( $this->partitionMap
as $partition => $w ) {
104 if ( !isset( $params['configByPartition'][$partition] ) ) {
105 throw new MWException( "No configuration for partition '$partition'." );
107 $this->partitionQueues
[$partition] = JobQueue
::factory(
108 $baseConfig +
$params['configByPartition'][$partition] );
110 // Get the ring of partitions to push jobs into
111 $this->partitionPushRing
= new HashRing( $partitionPushMap );
112 // Aggregate cache some per-queue values if there are multiple partition queues
113 $this->cache
= count( $this->partitionMap
) > 1 ?
wfGetMainCache() : new EmptyBagOStuff();
116 protected function supportedOrders() {
117 // No FIFO due to partitioning, though "rough timestamp order" is supported
118 return array( 'undefined', 'random', 'timestamp' );
121 protected function optimalOrder() {
122 return 'undefined'; // defer to the partitions
125 protected function supportsDelayedJobs() {
126 return true; // defer checks to the partitions
129 protected function doIsEmpty() {
130 $key = $this->getCacheKey( 'empty' );
132 $isEmpty = $this->cache
->get( $key );
133 if ( $isEmpty === 'true' ) {
135 } elseif ( $isEmpty === 'false' ) {
139 foreach ( $this->partitionQueues
as $queue ) {
141 if ( !$queue->doIsEmpty() ) {
142 $this->cache
->add( $key, 'false', self
::CACHE_TTL_LONG
);
145 } catch ( JobQueueError
$e ) {
146 MWExceptionHandler
::logException( $e );
150 $this->cache
->add( $key, 'true', self
::CACHE_TTL_LONG
);
154 protected function doGetSize() {
155 return $this->getCrossPartitionSum( 'size', 'doGetSize' );
158 protected function doGetAcquiredCount() {
159 return $this->getCrossPartitionSum( 'acquiredcount', 'doGetAcquiredCount' );
162 protected function doGetDelayedCount() {
163 return $this->getCrossPartitionSum( 'delayedcount', 'doGetDelayedCount' );
166 protected function doGetAbandonedCount() {
167 return $this->getCrossPartitionSum( 'abandonedcount', 'doGetAbandonedCount' );
171 * @param string $type
172 * @param string $method
175 protected function getCrossPartitionSum( $type, $method ) {
176 $key = $this->getCacheKey( $type );
178 $count = $this->cache
->get( $key );
179 if ( is_int( $count ) ) {
184 foreach ( $this->partitionQueues
as $queue ) {
186 $count +
= $queue->$method();
187 } catch ( JobQueueError
$e ) {
188 MWExceptionHandler
::logException( $e );
192 $this->cache
->set( $key, $count, self
::CACHE_TTL_SHORT
);
196 protected function doBatchPush( array $jobs, $flags ) {
197 if ( !count( $jobs ) ) {
198 return true; // nothing to do
200 // Local ring variable that may be changed to point to a new ring on failure
201 $partitionRing = $this->partitionPushRing
;
202 // Try to insert the jobs and update $partitionsTry on any failures
203 $jobsLeft = $this->tryJobInsertions( $jobs, $partitionRing, $flags );
204 if ( count( $jobsLeft ) ) { // some jobs failed to insert?
205 // Try to insert the remaning jobs once more, ignoring the bad partitions
206 return !count( $this->tryJobInsertions( $jobsLeft, $partitionRing, $flags ) );
213 * @param HashRing $partitionRing
214 * @param integer $flags
215 * @return array List of Job object that could not be inserted
217 protected function tryJobInsertions( array $jobs, HashRing
&$partitionRing, $flags ) {
220 // Because jobs are spread across partitions, per-job de-duplication needs
221 // to use a consistent hash to avoid allowing duplicate jobs per partition.
222 // When inserting a batch of de-duplicated jobs, QOS_ATOMIC is disregarded.
223 $uJobsByPartition = array(); // (partition name => job list)
224 foreach ( $jobs as $key => $job ) {
225 if ( $job->ignoreDuplicates() ) {
226 $sha1 = sha1( serialize( $job->getDeduplicationInfo() ) );
227 $uJobsByPartition[$partitionRing->getLocation( $sha1 )][] = $job;
228 unset( $jobs[$key] );
231 // Get the batches of jobs that are not de-duplicated
232 if ( $flags & self
::QOS_ATOMIC
) {
233 $nuJobBatches = array( $jobs ); // all or nothing
235 // Split the jobs into batches and spread them out over servers if there
236 // are many jobs. This helps keep the partitions even. Otherwise, send all
237 // the jobs to a single partition queue to avoids the extra connections.
238 $nuJobBatches = array_chunk( $jobs, 300 );
241 // Insert the de-duplicated jobs into the queues...
242 foreach ( $uJobsByPartition as $partition => $jobBatch ) {
243 $queue = $this->partitionQueues
[$partition];
245 $ok = $queue->doBatchPush( $jobBatch, $flags | self
::QOS_ATOMIC
);
246 } catch ( JobQueueError
$e ) {
248 MWExceptionHandler
::logException( $e );
251 $key = $this->getCacheKey( 'empty' );
252 $this->cache
->set( $key, 'false', JobQueueDB
::CACHE_TTL_LONG
);
254 $partitionRing = $partitionRing->newWithoutLocation( $partition ); // blacklist
255 if ( !$partitionRing ) {
256 throw new JobQueueError( "Could not insert job(s), all partitions are down." );
258 $jobsLeft = array_merge( $jobsLeft, $jobBatch ); // not inserted
262 // Insert the jobs that are not de-duplicated into the queues...
263 foreach ( $nuJobBatches as $jobBatch ) {
264 $partition = ArrayUtils
::pickRandom( $partitionRing->getLocationWeights() );
265 $queue = $this->partitionQueues
[$partition];
267 $ok = $queue->doBatchPush( $jobBatch, $flags | self
::QOS_ATOMIC
);
268 } catch ( JobQueueError
$e ) {
270 MWExceptionHandler
::logException( $e );
273 $key = $this->getCacheKey( 'empty' );
274 $this->cache
->set( $key, 'false', JobQueueDB
::CACHE_TTL_LONG
);
276 $partitionRing = $partitionRing->newWithoutLocation( $partition ); // blacklist
277 if ( !$partitionRing ) {
278 throw new JobQueueError( "Could not insert job(s), all partitions are down." );
280 $jobsLeft = array_merge( $jobsLeft, $jobBatch ); // not inserted
287 protected function doPop() {
288 $key = $this->getCacheKey( 'empty' );
290 $isEmpty = $this->cache
->get( $key );
291 if ( $isEmpty === 'true' ) {
295 $partitionsTry = $this->partitionMap
; // (partition => weight)
297 while ( count( $partitionsTry ) ) {
298 $partition = ArrayUtils
::pickRandom( $partitionsTry );
299 if ( $partition === false ) {
300 break; // all partitions at 0 weight
302 $queue = $this->partitionQueues
[$partition];
304 $job = $queue->pop();
305 } catch ( JobQueueError
$e ) {
307 MWExceptionHandler
::logException( $e );
310 $job->metadata
['QueuePartition'] = $partition;
313 unset( $partitionsTry[$partition] ); // blacklist partition
317 $this->cache
->set( $key, 'true', JobQueueDB
::CACHE_TTL_LONG
);
321 protected function doAck( Job
$job ) {
322 if ( !isset( $job->metadata
['QueuePartition'] ) ) {
323 throw new MWException( "The given job has no defined partition name." );
325 return $this->partitionQueues
[$job->metadata
['QueuePartition']]->ack( $job );
328 protected function doIsRootJobOldDuplicate( Job
$job ) {
329 $params = $job->getRootJobParams();
330 $partitions = $this->partitionPushRing
->getLocations( $params['rootJobSignature'], 2 );
332 return $this->partitionQueues
[$partitions[0]]->doIsRootJobOldDuplicate( $job );
333 } catch ( JobQueueError
$e ) {
334 if ( isset( $partitions[1] ) ) { // check fallback partition
335 return $this->partitionQueues
[$partitions[1]]->doIsRootJobOldDuplicate( $job );
341 protected function doDeduplicateRootJob( Job
$job ) {
342 $params = $job->getRootJobParams();
343 $partitions = $this->partitionPushRing
->getLocations( $params['rootJobSignature'], 2 );
345 return $this->partitionQueues
[$partitions[0]]->doDeduplicateRootJob( $job );
346 } catch ( JobQueueError
$e ) {
347 if ( isset( $partitions[1] ) ) { // check fallback partition
348 return $this->partitionQueues
[$partitions[1]]->doDeduplicateRootJob( $job );
354 protected function doDelete() {
355 foreach ( $this->partitionQueues
as $queue ) {
358 } catch ( JobQueueError
$e ) {
359 MWExceptionHandler
::logException( $e );
364 protected function doWaitForBackups() {
365 foreach ( $this->partitionQueues
as $queue ) {
367 $queue->waitForBackups();
368 } catch ( JobQueueError
$e ) {
369 MWExceptionHandler
::logException( $e );
374 protected function doGetPeriodicTasks() {
376 foreach ( $this->partitionQueues
as $partition => $queue ) {
377 foreach ( $queue->getPeriodicTasks() as $task => $def ) {
378 $tasks["{$partition}:{$task}"] = $def;
384 protected function doFlushCaches() {
385 static $types = array(
392 foreach ( $types as $type ) {
393 $this->cache
->delete( $this->getCacheKey( $type ) );
395 foreach ( $this->partitionQueues
as $queue ) {
396 $queue->doFlushCaches();
400 public function getAllQueuedJobs() {
401 $iterator = new AppendIterator();
402 foreach ( $this->partitionQueues
as $queue ) {
403 $iterator->append( $queue->getAllQueuedJobs() );
408 public function getAllDelayedJobs() {
409 $iterator = new AppendIterator();
410 foreach ( $this->partitionQueues
as $queue ) {
411 $iterator->append( $queue->getAllDelayedJobs() );
416 public function getCoalesceLocationInternal() {
417 return "JobQueueFederated:wiki:{$this->wiki}" .
418 sha1( serialize( array_keys( $this->partitionMap
) ) );
421 protected function doGetSiblingQueuesWithJobs( array $types ) {
423 foreach ( $this->partitionQueues
as $queue ) {
425 $nonEmpty = $queue->doGetSiblingQueuesWithJobs( $types );
426 if ( is_array( $nonEmpty ) ) {
427 $result = array_unique( array_merge( $result, $nonEmpty ) );
429 return null; // not supported on all partitions; bail
431 if ( count( $result ) == count( $types ) ) {
432 break; // short-circuit
434 } catch ( JobQueueError
$e ) {
435 MWExceptionHandler
::logException( $e );
438 return array_values( $result );
441 protected function doGetSiblingQueueSizes( array $types ) {
443 foreach ( $this->partitionQueues
as $queue ) {
445 $sizes = $queue->doGetSiblingQueueSizes( $types );
446 if ( is_array( $sizes ) ) {
447 foreach ( $sizes as $type => $size ) {
448 $result[$type] = isset( $result[$type] ) ?
$result[$type] +
$size : $size;
451 return null; // not supported on all partitions; bail
453 } catch ( JobQueueError
$e ) {
454 MWExceptionHandler
::logException( $e );
460 public function setTestingPrefix( $key ) {
461 foreach ( $this->partitionQueues
as $queue ) {
462 $queue->setTestingPrefix( $key );
469 private function getCacheKey( $property ) {
470 list( $db, $prefix ) = wfSplitWikiID( $this->wiki
);
471 return wfForeignMemcKey( $db, $prefix, 'jobqueue', $this->type
, $property );