jobqueue: various cleanups to JobQueueFederated
[mediawiki.git] / includes / job / JobQueueFederated.php
blobce2f3c71b71505264082737da2dc39bcb22d82c8
1 <?php
2 /**
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
20 * @file
21 * @author Aaron Schulz
24 /**
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.
46 * @ingroup JobQueue
47 * @since 1.22
49 class JobQueueFederated extends JobQueue {
50 /** @var Array (partition name => weight) */
51 protected $partitionMap = array();
52 /** @var Array (partition name => JobQueue) */
53 protected $partitionQueues = array();
54 /** @var HashRing */
55 protected $partitionPushRing;
56 /** @var BagOStuff */
57 protected $cache;
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
62 /**
63 * @params include:
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]
81 : 'default';
82 if ( !isset( $params['partitionsBySection'][$section] ) ) {
83 throw new MWException( "No configuration for section '$section'." );
85 $this->partitionMap = $params['partitionsBySection'][$section];
86 $partitionPushMap = $this->partitionMap;
87 if ( isset( $params['partitionsNoPush'] ) ) {
88 foreach ( $params['partitionsNoPush'] as $partition ) {
89 unset( $partitionPushMap[$partition] );
92 // Get the config to pass to merge into each partition queue config
93 $baseConfig = $params;
94 foreach ( array( 'class', 'sectionsByWiki',
95 'partitionsBySection', 'configByPartition', 'partitionsNoPush' ) as $o )
97 unset( $baseConfig[$o] );
99 // Get the partition queue objects
100 foreach ( $this->partitionMap as $partition => $w ) {
101 if ( !isset( $params['configByPartition'][$partition] ) ) {
102 throw new MWException( "No configuration for partition '$partition'." );
104 $this->partitionQueues[$partition] = JobQueue::factory(
105 $baseConfig + $params['configByPartition'][$partition] );
107 // Get the ring of partitions to push job de-duplication information into
108 $this->partitionPushRing = new HashRing( $partitionPushMap );
109 // Aggregate cache some per-queue values if there are multiple partition queues
110 $this->cache = count( $this->partitionMap ) > 1 ? wfGetMainCache() : new EmptyBagOStuff();
113 protected function supportedOrders() {
114 // No FIFO due to partitioning, though "rough timestamp order" is supported
115 return array( 'undefined', 'random', 'timestamp' );
118 protected function optimalOrder() {
119 return 'undefined'; // defer to the partitions
122 protected function supportsDelayedJobs() {
123 return true; // defer checks to the partitions
126 protected function doIsEmpty() {
127 $key = $this->getCacheKey( 'empty' );
129 $isEmpty = $this->cache->get( $key );
130 if ( $isEmpty === 'true' ) {
131 return true;
132 } elseif ( $isEmpty === 'false' ) {
133 return false;
136 foreach ( $this->partitionQueues as $queue ) {
137 try {
138 if ( !$queue->doIsEmpty() ) {
139 $this->cache->add( $key, 'false', self::CACHE_TTL_LONG );
140 return false;
142 } catch ( JobQueueError $e ) {
143 wfDebugLog( 'exception', $e->getLogMessage() );
147 $this->cache->add( $key, 'true', self::CACHE_TTL_LONG );
148 return true;
151 protected function doGetSize() {
152 return $this->getCrossPartitionSum( 'size', 'doGetSize' );
155 protected function doGetAcquiredCount() {
156 return $this->getCrossPartitionSum( 'acquiredcount', 'doGetAcquiredCount' );
159 protected function doGetDelayedCount() {
160 return $this->getCrossPartitionSum( 'delayedcount', 'doGetDelayedCount' );
163 protected function doGetAbandonedCount() {
164 return $this->getCrossPartitionSum( 'abandonedcount', 'doGetAbandonedCount' );
168 * @param string $type
169 * @param string $method
170 * @return integer
172 protected function getCrossPartitionSum( $type, $method ) {
173 $key = $this->getCacheKey( $type );
175 $count = $this->cache->get( $key );
176 if ( is_int( $count ) ) {
177 return $count;
180 $count = 0;
181 foreach ( $this->partitionQueues as $queue ) {
182 try {
183 $count += $queue->$method();
184 } catch ( JobQueueError $e ) {
185 wfDebugLog( 'exception', $e->getLogMessage() );
189 $this->cache->set( $key, $count, self::CACHE_TTL_SHORT );
190 return $count;
193 protected function doBatchPush( array $jobs, $flags ) {
194 if ( !count( $jobs ) ) {
195 return true; // nothing to do
197 // Local ring variable that may be changed to point to a new ring on failure
198 $partitionRing = $this->partitionPushRing;
199 // Try to insert the jobs and update $partitionsTry on any failures
200 $jobsLeft = $this->tryJobInsertions( $jobs, $partitionRing, $flags );
201 if ( count( $jobsLeft ) ) { // some jobs failed to insert?
202 // Try to insert the remaning jobs once more, ignoring the bad partitions
203 return !count( $this->tryJobInsertions( $jobsLeft, $partitionRing, $flags ) );
205 return true;
209 * @param array $jobs
210 * @param HashRing $partitionRing
211 * @param integer $flags
212 * @return array List of Job object that could not be inserted
214 protected function tryJobInsertions( array $jobs, HashRing &$partitionRing, $flags ) {
215 $jobsLeft = array();
217 // Because jobs are spread across partitions, per-job de-duplication needs
218 // to use a consistent hash to avoid allowing duplicate jobs per partition.
219 // When inserting a batch of de-duplicated jobs, QOS_ATOMIC is disregarded.
220 $uJobsByPartition = array(); // (partition name => job list)
221 foreach ( $jobs as $key => $job ) {
222 if ( $job->ignoreDuplicates() ) {
223 $sha1 = sha1( serialize( $job->getDeduplicationInfo() ) );
224 $uJobsByPartition[$partitionRing->getLocation( $sha1 )][] = $job;
225 unset( $jobs[$key] );
228 // Get the batches of jobs that are not de-duplicated
229 if ( $flags & self::QOS_ATOMIC ) {
230 $nuJobBatches = array( $jobs ); // all or nothing
231 } else {
232 // Split the jobs into batches and spread them out over servers if there
233 // are many jobs. This helps keep the partitions even. Otherwise, send all
234 // the jobs to a single partition queue to avoids the extra connections.
235 $nuJobBatches = array_chunk( $jobs, 300 );
238 // Insert the de-duplicated jobs into the queues...
239 foreach ( $uJobsByPartition as $partition => $jobBatch ) {
240 $queue = $this->partitionQueues[$partition];
241 try {
242 $ok = $queue->doBatchPush( $jobBatch, $flags | self::QOS_ATOMIC );
243 } catch ( JobQueueError $e ) {
244 $ok = false;
245 wfDebugLog( 'exception', $e->getLogMessage() );
247 if ( $ok ) {
248 $key = $this->getCacheKey( 'empty' );
249 $this->cache->set( $key, 'false', JobQueueDB::CACHE_TTL_LONG );
250 } else {
251 $partitionRing = $partitionRing->newWithoutLocation( $partition ); // blacklist
252 if ( !$partitionRing ) {
253 throw new JobQueueError( "Could not insert job(s), all partitions are down." );
255 $jobsLeft = array_merge( $jobsLeft, $jobBatch ); // not inserted
259 // Insert the jobs that are not de-duplicated into the queues...
260 foreach ( $nuJobBatches as $jobBatch ) {
261 $partition = ArrayUtils::pickRandom( $partitionRing->getLocationWeights() );
262 $queue = $this->partitionQueues[$partition];
263 try {
264 $ok = $queue->doBatchPush( $jobBatch, $flags | self::QOS_ATOMIC );
265 } catch ( JobQueueError $e ) {
266 $ok = false;
267 wfDebugLog( 'exception', $e->getLogMessage() );
269 if ( $ok ) {
270 $key = $this->getCacheKey( 'empty' );
271 $this->cache->set( $key, 'false', JobQueueDB::CACHE_TTL_LONG );
272 } else {
273 $partitionRing = $partitionRing->newWithoutLocation( $partition ); // blacklist
274 if ( !$partitionRing ) {
275 throw new JobQueueError( "Could not insert job(s), all partitions are down." );
277 $jobsLeft = array_merge( $jobsLeft, $jobBatch ); // not inserted
281 return $jobsLeft;
284 protected function doPop() {
285 $key = $this->getCacheKey( 'empty' );
287 $isEmpty = $this->cache->get( $key );
288 if ( $isEmpty === 'true' ) {
289 return false;
292 $partitionsTry = $this->partitionMap; // (partition => weight)
294 while ( count( $partitionsTry ) ) {
295 $partition = ArrayUtils::pickRandom( $partitionsTry );
296 if ( $partition === false ) {
297 break; // all partitions at 0 weight
299 $queue = $this->partitionQueues[$partition];
300 try {
301 $job = $queue->pop();
302 } catch ( JobQueueError $e ) {
303 $job = false;
304 wfDebugLog( 'exception', $e->getLogMessage() );
306 if ( $job ) {
307 $job->metadata['QueuePartition'] = $partition;
308 return $job;
309 } else {
310 unset( $partitionsTry[$partition] ); // blacklist partition
314 $this->cache->set( $key, 'true', JobQueueDB::CACHE_TTL_LONG );
315 return false;
318 protected function doAck( Job $job ) {
319 if ( !isset( $job->metadata['QueuePartition'] ) ) {
320 throw new MWException( "The given job has no defined partition name." );
322 return $this->partitionQueues[$job->metadata['QueuePartition']]->ack( $job );
325 protected function doIsRootJobOldDuplicate( Job $job ) {
326 $params = $job->getRootJobParams();
327 $partitions = $this->partitionPushRing->getLocations( $params['rootJobSignature'], 2 );
328 try {
329 return $this->partitionQueues[$partitions[0]]->doIsRootJobOldDuplicate( $job );
330 } catch ( MWException $e ) {
331 if ( isset( $partitions[1] ) ) { // check fallback partition
332 return $this->partitionQueues[$partitions[1]]->doIsRootJobOldDuplicate( $job );
335 return false;
338 protected function doDeduplicateRootJob( Job $job ) {
339 $params = $job->getRootJobParams();
340 $partitions = $this->partitionPushRing->getLocations( $params['rootJobSignature'], 2 );
341 try {
342 return $this->partitionQueues[$partitions[0]]->doDeduplicateRootJob( $job );
343 } catch ( MWException $e ) {
344 if ( isset( $partitions[1] ) ) { // check fallback partition
345 return $this->partitionQueues[$partitions[1]]->doDeduplicateRootJob( $job );
348 return false;
351 protected function doDelete() {
352 foreach ( $this->partitionQueues as $queue ) {
353 try {
354 $queue->doDelete();
355 } catch ( JobQueueError $e ) {
356 wfDebugLog( 'exception', $e->getLogMessage() );
361 protected function doWaitForBackups() {
362 foreach ( $this->partitionQueues as $queue ) {
363 try {
364 $queue->waitForBackups();
365 } catch ( JobQueueError $e ) {
366 wfDebugLog( 'exception', $e->getLogMessage() );
371 protected function doGetPeriodicTasks() {
372 $tasks = array();
373 foreach ( $this->partitionQueues as $partition => $queue ) {
374 foreach ( $queue->getPeriodicTasks() as $task => $def ) {
375 $tasks["{$partition}:{$task}"] = $def;
378 return $tasks;
381 protected function doFlushCaches() {
382 static $types = array(
383 'empty',
384 'size',
385 'acquiredcount',
386 'delayedcount',
387 'abandonedcount'
389 foreach ( $types as $type ) {
390 $this->cache->delete( $this->getCacheKey( $type ) );
392 foreach ( $this->partitionQueues as $queue ) {
393 $queue->doFlushCaches();
397 public function getAllQueuedJobs() {
398 $iterator = new AppendIterator();
399 foreach ( $this->partitionQueues as $queue ) {
400 $iterator->append( $queue->getAllQueuedJobs() );
402 return $iterator;
405 public function getAllDelayedJobs() {
406 $iterator = new AppendIterator();
407 foreach ( $this->partitionQueues as $queue ) {
408 $iterator->append( $queue->getAllDelayedJobs() );
410 return $iterator;
413 public function getCoalesceLocationInternal() {
414 return "JobQueueFederated:wiki:{$this->wiki}" .
415 sha1( serialize( array_keys( $this->partitionMap ) ) );
418 protected function doGetSiblingQueuesWithJobs( array $types ) {
419 $result = array();
420 foreach ( $this->partitionQueues as $queue ) {
421 try {
422 $nonEmpty = $queue->doGetSiblingQueuesWithJobs( $types );
423 if ( is_array( $nonEmpty ) ) {
424 $result = array_merge( $result, $nonEmpty );
425 } else {
426 return null; // not supported on all partitions; bail
428 } catch ( JobQueueError $e ) {
429 wfDebugLog( 'exception', $e->getLogMessage() );
432 return array_values( array_unique( $result ) );
435 protected function doGetSiblingQueueSizes( array $types ) {
436 $result = array();
437 foreach ( $this->partitionQueues as $queue ) {
438 try {
439 $sizes = $queue->doGetSiblingQueueSizes( $types );
440 if ( is_array( $sizes ) ) {
441 foreach ( $sizes as $type => $size ) {
442 $result[$type] = isset( $result[$type] ) ? $result[$type] + $size : $size;
444 } else {
445 return null; // not supported on all partitions; bail
447 } catch ( JobQueueError $e ) {
448 wfDebugLog( 'exception', $e->getLogMessage() );
451 return $result;
454 public function setTestingPrefix( $key ) {
455 foreach ( $this->partitionQueues as $queue ) {
456 $queue->setTestingPrefix( $key );
461 * @return string
463 private function getCacheKey( $property ) {
464 list( $db, $prefix ) = wfSplitWikiID( $this->wiki );
465 return wfForeignMemcKey( $db, $prefix, 'jobqueue', $this->type, $property );