Merge "Typo fix"
[mediawiki.git] / includes / job / JobQueueFederated.php
blob19de8bb529eb723912d3156fdec23c2816abf754
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".
45 * @ingroup JobQueue
46 * @since 1.22
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 HashRing */
59 protected $partitionRing;
60 /** @var Array (partition name => JobQueue) */
61 protected $partitionQueues = array();
62 /** @var BagOStuff */
63 protected $cache;
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
68 /**
69 * @params include:
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 * @param array $params
83 protected function __construct( array $params ) {
84 parent::__construct( $params );
85 $this->sectionsByWiki = isset( $params['sectionsByWiki'] )
86 ? $params['sectionsByWiki']
87 : array(); // all in "default" section
88 $this->partitionsBySection = $params['partitionsBySection'];
89 $this->configByPartition = $params['configByPartition'];
90 if ( isset( $params['partitionsNoPush'] ) ) {
91 $this->partitionsNoPush = array_flip( $params['partitionsNoPush'] );
93 $baseConfig = $params;
94 foreach ( array( 'class', 'sectionsByWiki',
95 'partitionsBySection', 'configByPartition', 'partitionsNoPush' ) as $o )
97 unset( $baseConfig[$o] );
99 foreach ( $this->getPartitionMap() as $partition => $w ) {
100 if ( !isset( $this->configByPartition[$partition] ) ) {
101 throw new MWException( "No configuration for partition '$partition'." );
103 $this->partitionQueues[$partition] = JobQueue::factory(
104 $baseConfig + $this->configByPartition[$partition]
107 // Get the ring of partitions to push job de-duplication information into
108 $partitionsTry = array_diff_key(
109 $this->getPartitionMap(),
110 $this->partitionsNoPush
111 ); // (partition => weight)
112 $this->partitionRing = new HashRing( $partitionsTry );
113 // Aggregate cache some per-queue values if there are multiple partition queues
114 $this->cache = $this->isFederated() ? wfGetMainCache() : new EmptyBagOStuff();
117 protected function supportedOrders() {
118 // No FIFO due to partitioning, though "rough timestamp order" is supported
119 return array( 'undefined', 'random', 'timestamp' );
122 protected function optimalOrder() {
123 return 'undefined'; // defer to the partitions
126 protected function supportsDelayedJobs() {
127 return true; // defer checks to the partitions
130 protected function doIsEmpty() {
131 $key = $this->getCacheKey( 'empty' );
133 $isEmpty = $this->cache->get( $key );
134 if ( $isEmpty === 'true' ) {
135 return true;
136 } elseif ( $isEmpty === 'false' ) {
137 return false;
140 foreach ( $this->partitionQueues as $queue ) {
141 if ( !$queue->doIsEmpty() ) {
142 $this->cache->add( $key, 'false', self::CACHE_TTL_LONG );
143 return false;
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 $count += $queue->$method();
185 $this->cache->set( $key, $count, self::CACHE_TTL_SHORT );
186 return $count;
189 protected function doBatchPush( array $jobs, $flags ) {
190 if ( !count( $jobs ) ) {
191 return true; // nothing to do
194 $partitionsTry = array_diff_key(
195 $this->getPartitionMap(),
196 $this->partitionsNoPush
197 ); // (partition => weight)
199 // Try to insert the jobs and update $partitionsTry on any failures
200 $jobsLeft = $this->tryJobInsertions( $jobs, $partitionsTry, $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, $partitionsTry, $flags ) );
204 } else {
205 return true;
210 * @param array $jobs
211 * @param array $partitionsTry
212 * @param integer $flags
213 * @return array List of Job object that could not be inserted
215 protected function tryJobInsertions( array $jobs, array &$partitionsTry, $flags ) {
216 if ( !count( $partitionsTry ) ) {
217 return $jobs; // can't insert anything
220 $jobsLeft = array();
222 $partitionRing = new HashRing( $partitionsTry );
223 // Because jobs are spread across partitions, per-job de-duplication needs
224 // to use a consistent hash to avoid allowing duplicate jobs per partition.
225 // When inserting a batch of de-duplicated jobs, QOS_ATOMIC is disregarded.
226 $uJobsByPartition = array(); // (partition name => job list)
227 foreach ( $jobs as $key => $job ) {
228 if ( $job->ignoreDuplicates() ) {
229 $sha1 = sha1( serialize( $job->getDeduplicationInfo() ) );
230 $uJobsByPartition[$partitionRing->getLocation( $sha1 )][] = $job;
231 unset( $jobs[$key] );
234 // Get the batches of jobs that are not de-duplicated
235 if ( $flags & self::QOS_ATOMIC ) {
236 $nuJobBatches = array( $jobs ); // all or nothing
237 } else {
238 // Split the jobs into batches and spread them out over servers if there
239 // are many jobs. This helps keep the partitions even. Otherwise, send all
240 // the jobs to a single partition queue to avoids the extra connections.
241 $nuJobBatches = array_chunk( $jobs, 300 );
244 // Insert the de-duplicated jobs into the queues...
245 foreach ( $uJobsByPartition as $partition => $jobBatch ) {
246 $queue = $this->partitionQueues[$partition];
247 if ( $queue->doBatchPush( $jobBatch, $flags ) ) {
248 $key = $this->getCacheKey( 'empty' );
249 $this->cache->set( $key, 'false', JobQueueDB::CACHE_TTL_LONG );
250 } else {
251 unset( $partitionsTry[$partition] ); // blacklist partition
252 $jobsLeft = array_merge( $jobsLeft, $jobBatch ); // not inserted
255 // Insert the jobs that are not de-duplicated into the queues...
256 foreach ( $nuJobBatches as $jobBatch ) {
257 $partition = ArrayUtils::pickRandom( $partitionsTry );
258 if ( $partition === false ) { // all partitions at 0 weight?
259 $jobsLeft = array_merge( $jobsLeft, $jobBatch ); // not inserted
260 } else {
261 $queue = $this->partitionQueues[$partition];
262 if ( $queue->doBatchPush( $jobBatch, $flags ) ) {
263 $key = $this->getCacheKey( 'empty' );
264 $this->cache->set( $key, 'false', JobQueueDB::CACHE_TTL_LONG );
265 } else {
266 unset( $partitionsTry[$partition] ); // blacklist partition
267 $jobsLeft = array_merge( $jobsLeft, $jobBatch ); // not inserted
272 return $jobsLeft;
275 protected function doPop() {
276 $key = $this->getCacheKey( 'empty' );
278 $isEmpty = $this->cache->get( $key );
279 if ( $isEmpty === 'true' ) {
280 return false;
283 $partitionsTry = $this->getPartitionMap(); // (partition => weight)
285 while ( count( $partitionsTry ) ) {
286 $partition = ArrayUtils::pickRandom( $partitionsTry );
287 if ( $partition === false ) {
288 break; // all partitions at 0 weight
290 $queue = $this->partitionQueues[$partition];
291 $job = $queue->pop();
292 if ( $job ) {
293 $job->metadata['QueuePartition'] = $partition;
294 return $job;
295 } else {
296 unset( $partitionsTry[$partition] ); // blacklist partition
300 $this->cache->set( $key, 'true', JobQueueDB::CACHE_TTL_LONG );
301 return false;
304 protected function doAck( Job $job ) {
305 if ( !isset( $job->metadata['QueuePartition'] ) ) {
306 throw new MWException( "The given job has no defined partition name." );
308 return $this->partitionQueues[$job->metadata['QueuePartition']]->ack( $job );
311 protected function doIsRootJobOldDuplicate( Job $job ) {
312 $params = $job->getRootJobParams();
313 $partitions = $this->partitionRing->getLocations( $params['rootJobSignature'], 2 );
314 try {
315 return $this->partitionQueues[$partitions[0]]->doIsRootJobOldDuplicate( $job );
316 } catch ( MWException $e ) {
317 if ( isset( $partitions[1] ) ) { // check fallback partition
318 return $this->partitionQueues[$partitions[1]]->doIsRootJobOldDuplicate( $job );
321 return false;
324 protected function doDeduplicateRootJob( Job $job ) {
325 $params = $job->getRootJobParams();
326 $partitions = $this->partitionRing->getLocations( $params['rootJobSignature'], 2 );
327 try {
328 return $this->partitionQueues[$partitions[0]]->doDeduplicateRootJob( $job );
329 } catch ( MWException $e ) {
330 if ( isset( $partitions[1] ) ) { // check fallback partition
331 return $this->partitionQueues[$partitions[1]]->doDeduplicateRootJob( $job );
334 return false;
337 protected function doDelete() {
338 foreach ( $this->partitionQueues as $queue ) {
339 $queue->doDelete();
343 protected function doWaitForBackups() {
344 foreach ( $this->partitionQueues as $queue ) {
345 $queue->waitForBackups();
349 protected function doGetPeriodicTasks() {
350 $tasks = array();
351 foreach ( $this->partitionQueues as $partition => $queue ) {
352 foreach ( $queue->getPeriodicTasks() as $task => $def ) {
353 $tasks["{$partition}:{$task}"] = $def;
356 return $tasks;
359 protected function doFlushCaches() {
360 static $types = array(
361 'empty',
362 'size',
363 'acquiredcount',
364 'delayedcount',
365 'abandonedcount'
367 foreach ( $types as $type ) {
368 $this->cache->delete( $this->getCacheKey( $type ) );
370 foreach ( $this->partitionQueues as $queue ) {
371 $queue->doFlushCaches();
375 public function getAllQueuedJobs() {
376 $iterator = new AppendIterator();
377 foreach ( $this->partitionQueues as $queue ) {
378 $iterator->append( $queue->getAllQueuedJobs() );
380 return $iterator;
383 public function getAllDelayedJobs() {
384 $iterator = new AppendIterator();
385 foreach ( $this->partitionQueues as $queue ) {
386 $iterator->append( $queue->getAllDelayedJobs() );
388 return $iterator;
391 public function setTestingPrefix( $key ) {
392 foreach ( $this->partitionQueues as $queue ) {
393 $queue->setTestingPrefix( $key );
398 * @return Array Map of (partition name => weight)
400 protected function getPartitionMap() {
401 $section = isset( $this->sectionsByWiki[$this->wiki] )
402 ? $this->sectionsByWiki[$this->wiki]
403 : 'default';
404 if ( !isset( $this->partitionsBySection[$section] ) ) {
405 throw new MWException( "No configuration for section '$section'." );
407 return $this->partitionsBySection[$section];
411 * @return bool The queue is actually split up across multiple queue partitions
413 protected function isFederated() {
414 return ( count( $this->getPartitionMap() ) > 1 );
418 * @return string
420 private function getCacheKey( $property ) {
421 list( $db, $prefix ) = wfSplitWikiID( $this->wiki );
422 return wfForeignMemcKey( $db, $prefix, 'jobqueue', $this->type, $property );