Merge "Add ss_active_users in SiteStats::isSane"
[mediawiki.git] / includes / job / JobQueueFederated.php
blobdb5b6862addb08dfb52ca1eaeb48c1819c689051
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 Array (partition name => JobQueue) */
59 protected $partitionQueues = array();
60 /** @var BagOStuff */
61 protected $cache;
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
66 /**
67 * @params include:
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' ) {
125 return true;
126 } elseif ( $isEmpty === 'false' ) {
127 return false;
130 foreach ( $this->partitionQueues as $queue ) {
131 if ( !$queue->doIsEmpty() ) {
132 $this->cache->add( $key, 'false', self::CACHE_TTL_LONG );
133 return false;
137 $this->cache->add( $key, 'true', self::CACHE_TTL_LONG );
138 return true;
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
160 * @return integer
162 protected function getCrossPartitionSum( $type, $method ) {
163 $key = $this->getCacheKey( $type );
165 $count = $this->cache->get( $key );
166 if ( is_int( $count ) ) {
167 return $count;
170 $count = 0;
171 foreach ( $this->partitionQueues as $queue ) {
172 $count += $queue->$method();
175 $this->cache->set( $key, $count, self::CACHE_TTL_SHORT );
176 return $count;
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 ) );
194 } else {
195 return true;
200 * @param array $jobs
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
210 $jobsLeft = array();
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
227 } else {
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 );
240 } else {
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
250 } else {
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 );
255 } else {
256 unset( $partitionsTry[$partition] ); // blacklist partition
257 $jobsLeft = array_merge( $jobsLeft, $jobBatch ); // not inserted
262 return $jobsLeft;
265 protected function doPop() {
266 $key = $this->getCacheKey( 'empty' );
268 $isEmpty = $this->cache->get( $key );
269 if ( $isEmpty === 'true' ) {
270 return false;
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();
282 if ( $job ) {
283 $job->metadata['QueuePartition'] = $partition;
284 return $job;
285 } else {
286 unset( $partitionsTry[$partition] ); // blacklist partition
290 $this->cache->set( $key, 'true', JobQueueDB::CACHE_TTL_LONG );
291 return false;
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 doDelete() {
302 foreach ( $this->partitionQueues as $queue ) {
303 $queue->doDelete();
307 protected function doWaitForBackups() {
308 foreach ( $this->partitionQueues as $queue ) {
309 $queue->waitForBackups();
313 protected function doGetPeriodicTasks() {
314 $tasks = array();
315 foreach ( $this->partitionQueues as $partition => $queue ) {
316 foreach ( $queue->getPeriodicTasks() as $task => $def ) {
317 $tasks["{$partition}:{$task}"] = $def;
320 return $tasks;
323 protected function doFlushCaches() {
324 static $types = array(
325 'empty',
326 'size',
327 'acquiredcount',
328 'delayedcount',
329 'abandonedcount'
331 foreach ( $types as $type ) {
332 $this->cache->delete( $this->getCacheKey( $type ) );
334 foreach ( $this->partitionQueues as $queue ) {
335 $queue->doFlushCaches();
339 public function getAllQueuedJobs() {
340 $iterator = new AppendIterator();
341 foreach ( $this->partitionQueues as $queue ) {
342 $iterator->append( $queue->getAllQueuedJobs() );
344 return $iterator;
347 public function getAllDelayedJobs() {
348 $iterator = new AppendIterator();
349 foreach ( $this->partitionQueues as $queue ) {
350 $iterator->append( $queue->getAllDelayedJobs() );
352 return $iterator;
355 public function setTestingPrefix( $key ) {
356 foreach ( $this->partitionQueues as $queue ) {
357 $queue->setTestingPrefix( $key );
362 * @return Array Map of (partition name => weight)
364 protected function getPartitionMap() {
365 $section = isset( $this->sectionsByWiki[$this->wiki] )
366 ? $this->sectionsByWiki[$this->wiki]
367 : 'default';
368 if ( !isset( $this->partitionsBySection[$section] ) ) {
369 throw new MWException( "No configuration for section '$section'." );
371 return $this->partitionsBySection[$section];
375 * @return bool The queue is actually split up across multiple queue partitions
377 protected function isFederated() {
378 return ( count( $this->getPartitionMap() ) > 1 );
382 * @return string
384 private function getCacheKey( $property ) {
385 list( $db, $prefix ) = wfSplitWikiID( $this->wiki );
386 return wfForeignMemcKey( $db, $prefix, 'jobqueue', $this->type, $property );