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