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".
48 class JobQueueFederated
extends JobQueue
{
49 /** @var Array (wiki ID => section name) */
50 protected $sectionsByWiki = array();
51 /** @var Array (section name => (partition name => weight)) */
52 protected $partitionsBySection = array();
53 /** @var Array (section name => config array) */
54 protected $configByPartition = array();
55 /** @var Array (partition names => integer) */
56 protected $partitionsNoPush = array();
58 /** @var Array (partition name => JobQueue) */
59 protected $partitionQueues = array();
63 const CACHE_TTL_SHORT
= 30; // integer; seconds to cache info without re-validating
64 const CACHE_TTL_LONG
= 300; // integer; seconds to cache info that is kept up to date
68 * - sectionsByWiki : A map of wiki IDs to section names.
69 * Wikis will default to using the section "default".
70 * - partitionsBySection : Map of section names to maps of (partition name => weight).
71 * A section called 'default' must be defined if not all wikis
72 * have explicitly defined sections.
73 * - configByPartition : Map of queue partition names to configuration arrays.
74 * These configuration arrays are passed to JobQueue::factory().
75 * The options set here are overriden by those passed to this
76 * the federated queue itself (e.g. 'order' and 'claimTTL').
77 * - partitionsNoPush : List of partition names that can handle pop() but not push().
78 * This can be used to migrate away from a certain partition.
79 * @param array $params
81 protected function __construct( array $params ) {
82 parent
::__construct( $params );
83 $this->sectionsByWiki
= $params['sectionsByWiki'];
84 $this->partitionsBySection
= $params['partitionsBySection'];
85 $this->configByPartition
= $params['configByPartition'];
86 if ( isset( $params['partitionsNoPush'] ) ) {
87 $this->partitionsNoPush
= array_flip( $params['partitionsNoPush'] );
89 $baseConfig = $params;
90 foreach ( array( 'class', 'sectionsByWiki',
91 'partitionsBySection', 'configByPartition', 'partitionsNoPush' ) as $o )
93 unset( $baseConfig[$o] );
95 foreach ( $this->getPartitionMap() as $partition => $w ) {
96 if ( !isset( $this->configByPartition
[$partition] ) ) {
97 throw new MWException( "No configuration for partition '$partition'." );
99 $this->partitionQueues
[$partition] = JobQueue
::factory(
100 $baseConfig +
$this->configByPartition
[$partition]
103 // Aggregate cache some per-queue values if there are multiple partition queues
104 $this->cache
= $this->isFederated() ?
wfGetMainCache() : new EmptyBagOStuff();
107 protected function supportedOrders() {
108 // No FIFO due to partitioning, though "rough timestamp order" is supported
109 return array( 'undefined', 'random', 'timestamp' );
112 protected function optimalOrder() {
113 return 'undefined'; // defer to the partitions
116 protected function supportsDelayedJobs() {
117 return true; // defer checks to the partitions
120 protected function doIsEmpty() {
121 $key = $this->getCacheKey( 'empty' );
123 $isEmpty = $this->cache
->get( $key );
124 if ( $isEmpty === 'true' ) {
126 } elseif ( $isEmpty === 'false' ) {
130 foreach ( $this->partitionQueues
as $queue ) {
131 if ( !$queue->doIsEmpty() ) {
132 $this->cache
->add( $key, 'false', self
::CACHE_TTL_LONG
);
137 $this->cache
->add( $key, 'true', self
::CACHE_TTL_LONG
);
141 protected function doGetSize() {
142 return $this->getCrossPartitionSum( 'size', 'doGetSize' );
145 protected function doGetAcquiredCount() {
146 return $this->getCrossPartitionSum( 'acquiredcount', 'doGetAcquiredCount' );
149 protected function doGetDelayedCount() {
150 return $this->getCrossPartitionSum( 'delayedcount', 'doGetDelayedCount' );
153 protected function doGetAbandonedCount() {
154 return $this->getCrossPartitionSum( 'abandonedcount', 'doGetAbandonedCount' );
158 * @param string $type
159 * @param string $method
162 protected function getCrossPartitionSum( $type, $method ) {
163 $key = $this->getCacheKey( $type );
165 $count = $this->cache
->get( $key );
166 if ( is_int( $count ) ) {
171 foreach ( $this->partitionQueues
as $queue ) {
172 $count +
= $queue->$method();
175 $this->cache
->set( $key, $count, self
::CACHE_TTL_SHORT
);
179 protected function doBatchPush( array $jobs, $flags ) {
180 if ( !count( $jobs ) ) {
181 return true; // nothing to do
184 $partitionsTry = array_diff_key(
185 $this->getPartitionMap(),
186 $this->partitionsNoPush
187 ); // (partition => weight)
189 // Try to insert the jobs and update $partitionsTry on any failures
190 $jobsLeft = $this->tryJobInsertions( $jobs, $partitionsTry, $flags );
191 if ( count( $jobsLeft ) ) { // some jobs failed to insert?
192 // Try to insert the remaning jobs once more, ignoring the bad partitions
193 return !count( $this->tryJobInsertions( $jobsLeft, $partitionsTry, $flags ) );
201 * @param array $partitionsTry
202 * @param integer $flags
203 * @return array List of Job object that could not be inserted
205 protected function tryJobInsertions( array $jobs, array &$partitionsTry, $flags ) {
206 if ( !count( $partitionsTry ) ) {
207 return $jobs; // can't insert anything
212 $partitionRing = new HashRing( $partitionsTry );
213 // Because jobs are spread across partitions, per-job de-duplication needs
214 // to use a consistent hash to avoid allowing duplicate jobs per partition.
215 // When inserting a batch of de-duplicated jobs, QoS_Atomic is disregarded.
216 $uJobsByPartition = array(); // (partition name => job list)
217 foreach ( $jobs as $key => $job ) {
218 if ( $job->ignoreDuplicates() ) {
219 $sha1 = sha1( serialize( $job->getDeduplicationInfo() ) );
220 $uJobsByPartition[$partitionRing->getLocation( $sha1 )][] = $job;
221 unset( $jobs[$key] );
224 // Get the batches of jobs that are not de-duplicated
225 if ( $flags & self
::QoS_Atomic
) {
226 $nuJobBatches = array( $jobs ); // all or nothing
228 // Split the jobs into batches and spread them out over servers if there
229 // are many jobs. This helps keep the partitions even. Otherwise, send all
230 // the jobs to a single partition queue to avoids the extra connections.
231 $nuJobBatches = array_chunk( $jobs, 300 );
234 // Insert the de-duplicated jobs into the queues...
235 foreach ( $uJobsByPartition as $partition => $jobBatch ) {
236 $queue = $this->partitionQueues
[$partition];
237 if ( $queue->doBatchPush( $jobBatch, $flags ) ) {
238 $key = $this->getCacheKey( 'empty' );
239 $this->cache
->set( $key, 'false', JobQueueDB
::CACHE_TTL_LONG
);
241 unset( $partitionsTry[$partition] ); // blacklist partition
242 $jobsLeft = array_merge( $jobsLeft, $jobBatch ); // not inserted
245 // Insert the jobs that are not de-duplicated into the queues...
246 foreach ( $nuJobBatches as $jobBatch ) {
247 $partition = ArrayUtils
::pickRandom( $partitionsTry );
248 if ( $partition === false ) { // all partitions at 0 weight?
249 $jobsLeft = array_merge( $jobsLeft, $jobBatch ); // not inserted
251 $queue = $this->partitionQueues
[$partition];
252 if ( $queue->doBatchPush( $jobBatch, $flags ) ) {
253 $key = $this->getCacheKey( 'empty' );
254 $this->cache
->set( $key, 'false', JobQueueDB
::CACHE_TTL_LONG
);
256 unset( $partitionsTry[$partition] ); // blacklist partition
257 $jobsLeft = array_merge( $jobsLeft, $jobBatch ); // not inserted
265 protected function doPop() {
266 $key = $this->getCacheKey( 'empty' );
268 $isEmpty = $this->cache
->get( $key );
269 if ( $isEmpty === 'true' ) {
273 $partitionsTry = $this->getPartitionMap(); // (partition => weight)
275 while ( count( $partitionsTry ) ) {
276 $partition = ArrayUtils
::pickRandom( $partitionsTry );
277 if ( $partition === false ) {
278 break; // all partitions at 0 weight
280 $queue = $this->partitionQueues
[$partition];
281 $job = $queue->pop();
283 $job->metadata
['QueuePartition'] = $partition;
286 unset( $partitionsTry[$partition] ); // blacklist partition
290 $this->cache
->set( $key, 'true', JobQueueDB
::CACHE_TTL_LONG
);
294 protected function doAck( Job
$job ) {
295 if ( !isset( $job->metadata
['QueuePartition'] ) ) {
296 throw new MWException( "The given job has no defined partition name." );
298 return $this->partitionQueues
[$job->metadata
['QueuePartition']]->ack( $job );
301 protected function doWaitForBackups() {
302 foreach ( $this->partitionQueues
as $queue ) {
303 $queue->waitForBackups();
307 protected function doGetPeriodicTasks() {
309 foreach ( $this->partitionQueues
as $partition => $queue ) {
310 foreach ( $queue->getPeriodicTasks() as $task => $def ) {
311 $tasks["{$partition}:{$task}"] = $def;
317 protected function doFlushCaches() {
318 static $types = array(
325 foreach ( $types as $type ) {
326 $this->cache
->delete( $this->getCacheKey( $type ) );
328 foreach ( $this->partitionQueues
as $queue ) {
329 $queue->doFlushCaches();
333 public function getAllQueuedJobs() {
334 $iterator = new AppendIterator();
335 foreach ( $this->partitionQueues
as $queue ) {
336 $iterator->append( $queue->getAllQueuedJobs() );
341 public function getAllDelayedJobs() {
342 $iterator = new AppendIterator();
343 foreach ( $this->partitionQueues
as $queue ) {
344 $iterator->append( $queue->getAllDelayedJobs() );
349 public function setTestingPrefix( $key ) {
350 foreach ( $this->partitionQueues
as $queue ) {
351 $queue->setTestingPrefix( $key );
356 * @return Array Map of (partition name => weight)
358 protected function getPartitionMap() {
359 $section = isset( $this->sectionsByWiki
[$this->wiki
] )
360 ?
$this->sectionsByWiki
[$this->wiki
]
362 if ( !isset( $this->partitionsBySection
[$section] ) ) {
363 throw new MWException( "No configuration for section '$section'." );
365 return $this->partitionsBySection
[$section];
369 * @return bool The queue is actually split up across multiple queue partitions
371 protected function isFederated() {
372 return ( count( $this->getPartitionMap() ) > 1 );
378 private function getCacheKey( $property ) {
379 list( $db, $prefix ) = wfSplitWikiID( $this->wiki
);
380 return wfForeignMemcKey( $db, $prefix, 'jobqueue', $this->type
, $property );