Reorder SpecialRecentChanges::webOutput
[lhc/web/wiklou.git] / includes / job / JobQueueFederated.php
1 <?php
2 /**
3 * Job queue code for federated queues.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 * @author Aaron Schulz
22 */
23
24 /**
25 * Class to handle enqueueing and running of background jobs for federated queues
26 *
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.
34 *
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.
40 *
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".
44 *
45 * @ingroup JobQueue
46 * @since 1.22
47 */
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();
57
58 /** @var Array (partition name => JobQueue) */
59 protected $partitionQueues = array();
60 /** @var BagOStuff */
61 protected $cache;
62
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
65
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
80 */
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'] );
88 }
89 $baseConfig = $params;
90 foreach ( array( 'class', 'sectionsByWiki',
91 'partitionsBySection', 'configByPartition', 'partitionsNoPush' ) as $o )
92 {
93 unset( $baseConfig[$o] );
94 }
95 foreach ( $this->getPartitionMap() as $partition => $w ) {
96 if ( !isset( $this->configByPartition[$partition] ) ) {
97 throw new MWException( "No configuration for partition '$partition'." );
98 }
99 $this->partitionQueues[$partition] = JobQueue::factory(
100 $baseConfig + $this->configByPartition[$partition]
101 );
102 }
103 // Aggregate cache some per-queue values if there are multiple partition queues
104 $this->cache = $this->isFederated() ? wfGetMainCache() : new EmptyBagOStuff();
105 }
106
107 protected function supportedOrders() {
108 // No FIFO due to partitioning, though "rough timestamp order" is supported
109 return array( 'undefined', 'random', 'timestamp' );
110 }
111
112 protected function optimalOrder() {
113 return 'undefined'; // defer to the partitions
114 }
115
116 protected function supportsDelayedJobs() {
117 return true; // defer checks to the partitions
118 }
119
120 protected function doIsEmpty() {
121 $key = $this->getCacheKey( 'empty' );
122
123 $isEmpty = $this->cache->get( $key );
124 if ( $isEmpty === 'true' ) {
125 return true;
126 } elseif ( $isEmpty === 'false' ) {
127 return false;
128 }
129
130 foreach ( $this->partitionQueues as $queue ) {
131 if ( !$queue->doIsEmpty() ) {
132 $this->cache->add( $key, 'false', self::CACHE_TTL_LONG );
133 return false;
134 }
135 }
136
137 $this->cache->add( $key, 'true', self::CACHE_TTL_LONG );
138 return true;
139 }
140
141 protected function doGetSize() {
142 return $this->getCrossPartitionSum( 'size', 'doGetSize' );
143 }
144
145 protected function doGetAcquiredCount() {
146 return $this->getCrossPartitionSum( 'acquiredcount', 'doGetAcquiredCount' );
147 }
148
149 protected function doGetDelayedCount() {
150 return $this->getCrossPartitionSum( 'delayedcount', 'doGetDelayedCount' );
151 }
152
153 protected function doGetAbandonedCount() {
154 return $this->getCrossPartitionSum( 'abandonedcount', 'doGetAbandonedCount' );
155 }
156
157 /**
158 * @param string $type
159 * @param string $method
160 * @return integer
161 */
162 protected function getCrossPartitionSum( $type, $method ) {
163 $key = $this->getCacheKey( $type );
164
165 $count = $this->cache->get( $key );
166 if ( is_int( $count ) ) {
167 return $count;
168 }
169
170 $count = 0;
171 foreach ( $this->partitionQueues as $queue ) {
172 $count += $queue->$method();
173 }
174
175 $this->cache->set( $key, $count, self::CACHE_TTL_SHORT );
176 return $count;
177 }
178
179 protected function doBatchPush( array $jobs, $flags ) {
180 if ( !count( $jobs ) ) {
181 return true; // nothing to do
182 }
183
184 $partitionsTry = array_diff_key(
185 $this->getPartitionMap(),
186 $this->partitionsNoPush
187 ); // (partition => weight)
188
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;
196 }
197 }
198
199 /**
200 * @param array $jobs
201 * @param array $partitionsTry
202 * @param integer $flags
203 * @return array List of Job object that could not be inserted
204 */
205 protected function tryJobInsertions( array $jobs, array &$partitionsTry, $flags ) {
206 if ( !count( $partitionsTry ) ) {
207 return $jobs; // can't insert anything
208 }
209
210 $jobsLeft = array();
211
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] );
222 }
223 }
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 );
232 }
233
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
243 }
244 }
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
258 }
259 }
260 }
261
262 return $jobsLeft;
263 }
264
265 protected function doPop() {
266 $key = $this->getCacheKey( 'empty' );
267
268 $isEmpty = $this->cache->get( $key );
269 if ( $isEmpty === 'true' ) {
270 return false;
271 }
272
273 $partitionsTry = $this->getPartitionMap(); // (partition => weight)
274
275 while ( count( $partitionsTry ) ) {
276 $partition = ArrayUtils::pickRandom( $partitionsTry );
277 if ( $partition === false ) {
278 break; // all partitions at 0 weight
279 }
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
287 }
288 }
289
290 $this->cache->set( $key, 'true', JobQueueDB::CACHE_TTL_LONG );
291 return false;
292 }
293
294 protected function doAck( Job $job ) {
295 if ( !isset( $job->metadata['QueuePartition'] ) ) {
296 throw new MWException( "The given job has no defined partition name." );
297 }
298 return $this->partitionQueues[$job->metadata['QueuePartition']]->ack( $job );
299 }
300
301 protected function doDelete() {
302 foreach ( $this->partitionQueues as $queue ) {
303 $queue->doDelete();
304 }
305 }
306
307 protected function doWaitForBackups() {
308 foreach ( $this->partitionQueues as $queue ) {
309 $queue->waitForBackups();
310 }
311 }
312
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;
318 }
319 }
320 return $tasks;
321 }
322
323 protected function doFlushCaches() {
324 static $types = array(
325 'empty',
326 'size',
327 'acquiredcount',
328 'delayedcount',
329 'abandonedcount'
330 );
331 foreach ( $types as $type ) {
332 $this->cache->delete( $this->getCacheKey( $type ) );
333 }
334 foreach ( $this->partitionQueues as $queue ) {
335 $queue->doFlushCaches();
336 }
337 }
338
339 public function getAllQueuedJobs() {
340 $iterator = new AppendIterator();
341 foreach ( $this->partitionQueues as $queue ) {
342 $iterator->append( $queue->getAllQueuedJobs() );
343 }
344 return $iterator;
345 }
346
347 public function getAllDelayedJobs() {
348 $iterator = new AppendIterator();
349 foreach ( $this->partitionQueues as $queue ) {
350 $iterator->append( $queue->getAllDelayedJobs() );
351 }
352 return $iterator;
353 }
354
355 public function setTestingPrefix( $key ) {
356 foreach ( $this->partitionQueues as $queue ) {
357 $queue->setTestingPrefix( $key );
358 }
359 }
360
361 /**
362 * @return Array Map of (partition name => weight)
363 */
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'." );
370 }
371 return $this->partitionsBySection[$section];
372 }
373
374 /**
375 * @return bool The queue is actually split up across multiple queue partitions
376 */
377 protected function isFederated() {
378 return ( count( $this->getPartitionMap() ) > 1 );
379 }
380
381 /**
382 * @return string
383 */
384 private function getCacheKey( $property ) {
385 list( $db, $prefix ) = wfSplitWikiID( $this->wiki );
386 return wfForeignMemcKey( $db, $prefix, 'jobqueue', $this->type, $property );
387 }
388 }