Merge "Added "maxPartitionsTry" option to JobQueueFederated"
[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". Also,
44 * queue classes used by this should ignore down servers (with TTL) to avoid slowness.
45 *
46 * @ingroup JobQueue
47 * @since 1.22
48 */
49 class JobQueueFederated extends JobQueue {
50 /** @var Array (partition name => weight) reverse sorted by weight */
51 protected $partitionMap = array();
52 /** @var Array (partition name => JobQueue) reverse sorted by weight */
53 protected $partitionQueues = array();
54 /** @var HashRing */
55 protected $partitionPushRing;
56 /** @var BagOStuff */
57 protected $cache;
58
59 protected $maxPartitionsTry; // integer; maximum number of partitions to try
60
61 const CACHE_TTL_SHORT = 30; // integer; seconds to cache info without re-validating
62 const CACHE_TTL_LONG = 300; // integer; seconds to cache info that is kept up to date
63
64 /**
65 * @params include:
66 * - sectionsByWiki : A map of wiki IDs to section names.
67 * Wikis will default to using the section "default".
68 * - partitionsBySection : Map of section names to maps of (partition name => weight).
69 * A section called 'default' must be defined if not all wikis
70 * have explicitly defined sections.
71 * - configByPartition : Map of queue partition names to configuration arrays.
72 * These configuration arrays are passed to JobQueue::factory().
73 * The options set here are overriden by those passed to this
74 * the federated queue itself (e.g. 'order' and 'claimTTL').
75 * - partitionsNoPush : List of partition names that can handle pop() but not push().
76 * This can be used to migrate away from a certain partition.
77 * - maxPartitionsTry : Maximum number of times to attempt job insertion using
78 * different partition queues. This improves availability
79 * during failure, at the cost of added latency and somewhat
80 * less reliable job de-duplication mechanisms.
81 * @param array $params
82 */
83 protected function __construct( array $params ) {
84 parent::__construct( $params );
85 $section = isset( $params['sectionsByWiki'][$this->wiki] )
86 ? $params['sectionsByWiki'][$this->wiki]
87 : 'default';
88 if ( !isset( $params['partitionsBySection'][$section] ) ) {
89 throw new MWException( "No configuration for section '$section'." );
90 }
91 $this->maxPartitionsTry = isset( $params['maxPartitionsTry'] )
92 ? $params['maxPartitionsTry']
93 : 2;
94 // Get the full partition map
95 $this->partitionMap = $params['partitionsBySection'][$section];
96 arsort( $this->partitionMap, SORT_NUMERIC );
97 // Get the partitions jobs can actually be pushed to
98 $partitionPushMap = $this->partitionMap;
99 if ( isset( $params['partitionsNoPush'] ) ) {
100 foreach ( $params['partitionsNoPush'] as $partition ) {
101 unset( $partitionPushMap[$partition] );
102 }
103 }
104 // Get the config to pass to merge into each partition queue config
105 $baseConfig = $params;
106 foreach ( array( 'class', 'sectionsByWiki', 'maxPartitionsTry',
107 'partitionsBySection', 'configByPartition', 'partitionsNoPush' ) as $o )
108 {
109 unset( $baseConfig[$o] ); // partition queue doesn't care about this
110 }
111 // Get the partition queue objects
112 foreach ( $this->partitionMap as $partition => $w ) {
113 if ( !isset( $params['configByPartition'][$partition] ) ) {
114 throw new MWException( "No configuration for partition '$partition'." );
115 }
116 $this->partitionQueues[$partition] = JobQueue::factory(
117 $baseConfig + $params['configByPartition'][$partition] );
118 }
119 // Get the ring of partitions to push jobs into
120 $this->partitionPushRing = new HashRing( $partitionPushMap );
121 // Aggregate cache some per-queue values if there are multiple partition queues
122 $this->cache = count( $this->partitionMap ) > 1 ? wfGetMainCache() : new EmptyBagOStuff();
123 }
124
125 protected function supportedOrders() {
126 // No FIFO due to partitioning, though "rough timestamp order" is supported
127 return array( 'undefined', 'random', 'timestamp' );
128 }
129
130 protected function optimalOrder() {
131 return 'undefined'; // defer to the partitions
132 }
133
134 protected function supportsDelayedJobs() {
135 return true; // defer checks to the partitions
136 }
137
138 protected function doIsEmpty() {
139 $key = $this->getCacheKey( 'empty' );
140
141 $isEmpty = $this->cache->get( $key );
142 if ( $isEmpty === 'true' ) {
143 return true;
144 } elseif ( $isEmpty === 'false' ) {
145 return false;
146 }
147
148 foreach ( $this->partitionQueues as $queue ) {
149 try {
150 if ( !$queue->doIsEmpty() ) {
151 $this->cache->add( $key, 'false', self::CACHE_TTL_LONG );
152 return false;
153 }
154 } catch ( JobQueueError $e ) {
155 MWExceptionHandler::logException( $e );
156 }
157 }
158
159 $this->cache->add( $key, 'true', self::CACHE_TTL_LONG );
160 return true;
161 }
162
163 protected function doGetSize() {
164 return $this->getCrossPartitionSum( 'size', 'doGetSize' );
165 }
166
167 protected function doGetAcquiredCount() {
168 return $this->getCrossPartitionSum( 'acquiredcount', 'doGetAcquiredCount' );
169 }
170
171 protected function doGetDelayedCount() {
172 return $this->getCrossPartitionSum( 'delayedcount', 'doGetDelayedCount' );
173 }
174
175 protected function doGetAbandonedCount() {
176 return $this->getCrossPartitionSum( 'abandonedcount', 'doGetAbandonedCount' );
177 }
178
179 /**
180 * @param string $type
181 * @param string $method
182 * @return integer
183 */
184 protected function getCrossPartitionSum( $type, $method ) {
185 $key = $this->getCacheKey( $type );
186
187 $count = $this->cache->get( $key );
188 if ( is_int( $count ) ) {
189 return $count;
190 }
191
192 $count = 0;
193 foreach ( $this->partitionQueues as $queue ) {
194 try {
195 $count += $queue->$method();
196 } catch ( JobQueueError $e ) {
197 MWExceptionHandler::logException( $e );
198 }
199 }
200
201 $this->cache->set( $key, $count, self::CACHE_TTL_SHORT );
202 return $count;
203 }
204
205 protected function doBatchPush( array $jobs, $flags ) {
206 // Local ring variable that may be changed to point to a new ring on failure
207 $partitionRing = $this->partitionPushRing;
208 // Try to insert the jobs and update $partitionsTry on any failures.
209 // Retry to insert any remaning jobs again, ignoring the bad partitions.
210 $jobsLeft = $jobs;
211 for ( $i = $this->maxPartitionsTry; $i > 0 && count( $jobsLeft ); --$i ) {
212 $jobsLeft = $this->tryJobInsertions( $jobsLeft, $partitionRing, $flags );
213 }
214 if ( count( $jobsLeft ) ) {
215 throw new JobQueueError(
216 "Could not insert job(s), {$this->maxPartitionsTry} partitions tried." );
217 }
218 return true;
219 }
220
221 /**
222 * @param array $jobs
223 * @param HashRing $partitionRing
224 * @param integer $flags
225 * @return array List of Job object that could not be inserted
226 */
227 protected function tryJobInsertions( array $jobs, HashRing &$partitionRing, $flags ) {
228 $jobsLeft = array();
229
230 // Because jobs are spread across partitions, per-job de-duplication needs
231 // to use a consistent hash to avoid allowing duplicate jobs per partition.
232 // When inserting a batch of de-duplicated jobs, QOS_ATOMIC is disregarded.
233 $uJobsByPartition = array(); // (partition name => job list)
234 foreach ( $jobs as $key => $job ) {
235 if ( $job->ignoreDuplicates() ) {
236 $sha1 = sha1( serialize( $job->getDeduplicationInfo() ) );
237 $uJobsByPartition[$partitionRing->getLocation( $sha1 )][] = $job;
238 unset( $jobs[$key] );
239 }
240 }
241 // Get the batches of jobs that are not de-duplicated
242 if ( $flags & self::QOS_ATOMIC ) {
243 $nuJobBatches = array( $jobs ); // all or nothing
244 } else {
245 // Split the jobs into batches and spread them out over servers if there
246 // are many jobs. This helps keep the partitions even. Otherwise, send all
247 // the jobs to a single partition queue to avoids the extra connections.
248 $nuJobBatches = array_chunk( $jobs, 300 );
249 }
250
251 // Insert the de-duplicated jobs into the queues...
252 foreach ( $uJobsByPartition as $partition => $jobBatch ) {
253 $queue = $this->partitionQueues[$partition];
254 try {
255 $ok = $queue->doBatchPush( $jobBatch, $flags | self::QOS_ATOMIC );
256 } catch ( JobQueueError $e ) {
257 $ok = false;
258 MWExceptionHandler::logException( $e );
259 }
260 if ( $ok ) {
261 $key = $this->getCacheKey( 'empty' );
262 $this->cache->set( $key, 'false', JobQueueDB::CACHE_TTL_LONG );
263 } else {
264 $partitionRing = $partitionRing->newWithoutLocation( $partition ); // blacklist
265 if ( !$partitionRing ) {
266 throw new JobQueueError( "Could not insert job(s), all partitions are down." );
267 }
268 $jobsLeft = array_merge( $jobsLeft, $jobBatch ); // not inserted
269 }
270 }
271
272 // Insert the jobs that are not de-duplicated into the queues...
273 foreach ( $nuJobBatches as $jobBatch ) {
274 $partition = ArrayUtils::pickRandom( $partitionRing->getLocationWeights() );
275 $queue = $this->partitionQueues[$partition];
276 try {
277 $ok = $queue->doBatchPush( $jobBatch, $flags | self::QOS_ATOMIC );
278 } catch ( JobQueueError $e ) {
279 $ok = false;
280 MWExceptionHandler::logException( $e );
281 }
282 if ( $ok ) {
283 $key = $this->getCacheKey( 'empty' );
284 $this->cache->set( $key, 'false', JobQueueDB::CACHE_TTL_LONG );
285 } else {
286 $partitionRing = $partitionRing->newWithoutLocation( $partition ); // blacklist
287 if ( !$partitionRing ) {
288 throw new JobQueueError( "Could not insert job(s), all partitions are down." );
289 }
290 $jobsLeft = array_merge( $jobsLeft, $jobBatch ); // not inserted
291 }
292 }
293
294 return $jobsLeft;
295 }
296
297 protected function doPop() {
298 $key = $this->getCacheKey( 'empty' );
299
300 $isEmpty = $this->cache->get( $key );
301 if ( $isEmpty === 'true' ) {
302 return false;
303 }
304
305 $partitionsTry = $this->partitionMap; // (partition => weight)
306
307 while ( count( $partitionsTry ) ) {
308 $partition = ArrayUtils::pickRandom( $partitionsTry );
309 if ( $partition === false ) {
310 break; // all partitions at 0 weight
311 }
312 $queue = $this->partitionQueues[$partition];
313 try {
314 $job = $queue->pop();
315 } catch ( JobQueueError $e ) {
316 $job = false;
317 MWExceptionHandler::logException( $e );
318 }
319 if ( $job ) {
320 $job->metadata['QueuePartition'] = $partition;
321 return $job;
322 } else {
323 unset( $partitionsTry[$partition] ); // blacklist partition
324 }
325 }
326
327 $this->cache->set( $key, 'true', JobQueueDB::CACHE_TTL_LONG );
328 return false;
329 }
330
331 protected function doAck( Job $job ) {
332 if ( !isset( $job->metadata['QueuePartition'] ) ) {
333 throw new MWException( "The given job has no defined partition name." );
334 }
335 return $this->partitionQueues[$job->metadata['QueuePartition']]->ack( $job );
336 }
337
338 protected function doIsRootJobOldDuplicate( Job $job ) {
339 $params = $job->getRootJobParams();
340 $partitions = $this->partitionPushRing->getLocations( $params['rootJobSignature'], 2 );
341 try {
342 return $this->partitionQueues[$partitions[0]]->doIsRootJobOldDuplicate( $job );
343 } catch ( JobQueueError $e ) {
344 if ( isset( $partitions[1] ) ) { // check fallback partition
345 return $this->partitionQueues[$partitions[1]]->doIsRootJobOldDuplicate( $job );
346 }
347 }
348 return false;
349 }
350
351 protected function doDeduplicateRootJob( Job $job ) {
352 $params = $job->getRootJobParams();
353 $partitions = $this->partitionPushRing->getLocations( $params['rootJobSignature'], 2 );
354 try {
355 return $this->partitionQueues[$partitions[0]]->doDeduplicateRootJob( $job );
356 } catch ( JobQueueError $e ) {
357 if ( isset( $partitions[1] ) ) { // check fallback partition
358 return $this->partitionQueues[$partitions[1]]->doDeduplicateRootJob( $job );
359 }
360 }
361 return false;
362 }
363
364 protected function doDelete() {
365 foreach ( $this->partitionQueues as $queue ) {
366 try {
367 $queue->doDelete();
368 } catch ( JobQueueError $e ) {
369 MWExceptionHandler::logException( $e );
370 }
371 }
372 }
373
374 protected function doWaitForBackups() {
375 foreach ( $this->partitionQueues as $queue ) {
376 try {
377 $queue->waitForBackups();
378 } catch ( JobQueueError $e ) {
379 MWExceptionHandler::logException( $e );
380 }
381 }
382 }
383
384 protected function doGetPeriodicTasks() {
385 $tasks = array();
386 foreach ( $this->partitionQueues as $partition => $queue ) {
387 foreach ( $queue->getPeriodicTasks() as $task => $def ) {
388 $tasks["{$partition}:{$task}"] = $def;
389 }
390 }
391 return $tasks;
392 }
393
394 protected function doFlushCaches() {
395 static $types = array(
396 'empty',
397 'size',
398 'acquiredcount',
399 'delayedcount',
400 'abandonedcount'
401 );
402 foreach ( $types as $type ) {
403 $this->cache->delete( $this->getCacheKey( $type ) );
404 }
405 foreach ( $this->partitionQueues as $queue ) {
406 $queue->doFlushCaches();
407 }
408 }
409
410 public function getAllQueuedJobs() {
411 $iterator = new AppendIterator();
412 foreach ( $this->partitionQueues as $queue ) {
413 $iterator->append( $queue->getAllQueuedJobs() );
414 }
415 return $iterator;
416 }
417
418 public function getAllDelayedJobs() {
419 $iterator = new AppendIterator();
420 foreach ( $this->partitionQueues as $queue ) {
421 $iterator->append( $queue->getAllDelayedJobs() );
422 }
423 return $iterator;
424 }
425
426 public function getCoalesceLocationInternal() {
427 return "JobQueueFederated:wiki:{$this->wiki}" .
428 sha1( serialize( array_keys( $this->partitionMap ) ) );
429 }
430
431 protected function doGetSiblingQueuesWithJobs( array $types ) {
432 $result = array();
433 foreach ( $this->partitionQueues as $queue ) {
434 try {
435 $nonEmpty = $queue->doGetSiblingQueuesWithJobs( $types );
436 if ( is_array( $nonEmpty ) ) {
437 $result = array_unique( array_merge( $result, $nonEmpty ) );
438 } else {
439 return null; // not supported on all partitions; bail
440 }
441 if ( count( $result ) == count( $types ) ) {
442 break; // short-circuit
443 }
444 } catch ( JobQueueError $e ) {
445 MWExceptionHandler::logException( $e );
446 }
447 }
448 return array_values( $result );
449 }
450
451 protected function doGetSiblingQueueSizes( array $types ) {
452 $result = array();
453 foreach ( $this->partitionQueues as $queue ) {
454 try {
455 $sizes = $queue->doGetSiblingQueueSizes( $types );
456 if ( is_array( $sizes ) ) {
457 foreach ( $sizes as $type => $size ) {
458 $result[$type] = isset( $result[$type] ) ? $result[$type] + $size : $size;
459 }
460 } else {
461 return null; // not supported on all partitions; bail
462 }
463 } catch ( JobQueueError $e ) {
464 MWExceptionHandler::logException( $e );
465 }
466 }
467 return $result;
468 }
469
470 public function setTestingPrefix( $key ) {
471 foreach ( $this->partitionQueues as $queue ) {
472 $queue->setTestingPrefix( $key );
473 }
474 }
475
476 /**
477 * @return string
478 */
479 private function getCacheKey( $property ) {
480 list( $db, $prefix ) = wfSplitWikiID( $this->wiki );
481 return wfForeignMemcKey( $db, $prefix, 'jobqueue', $this->type, $property );
482 }
483 }