summaryrefslogtreecommitdiff
path: root/includes/jobqueue/JobQueueFederated.php
blob: c4301eed9df229dc9268b804e6dbb0d13c28cfad (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
<?php
/**
 * Job queue code for federated queues.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 * http://www.gnu.org/copyleft/gpl.html
 *
 * @file
 * @author Aaron Schulz
 */

/**
 * Class to handle enqueueing and running of background jobs for federated queues
 *
 * This class allows for queues to be partitioned into smaller queues.
 * A partition is defined by the configuration for a JobQueue instance.
 * For example, one can set $wgJobTypeConf['refreshLinks'] to point to a
 * JobQueueFederated instance, which itself would consist of three JobQueueRedis
 * instances, each using their own redis server. This would allow for the jobs
 * to be split (evenly or based on weights) accross multiple servers if a single
 * server becomes impractical or expensive. Different JobQueue classes can be mixed.
 *
 * The basic queue configuration (e.g. "order", "claimTTL") of a federated queue
 * is inherited by the partition queues. Additional configuration defines what
 * section each wiki is in, what partition queues each section uses (and their weight),
 * and the JobQueue configuration for each partition. Some sections might only need a
 * single queue partition, like the sections for groups of small wikis.
 *
 * If used for performance, then $wgMainCacheType should be set to memcached/redis.
 * Note that "fifo" cannot be used for the ordering, since the data is distributed.
 * One can still use "timestamp" instead, as in "roughly timestamp ordered". Also,
 * queue classes used by this should ignore down servers (with TTL) to avoid slowness.
 *
 * @ingroup JobQueue
 * @since 1.22
 */
class JobQueueFederated extends JobQueue {
	/** @var HashRing */
	protected $partitionRing;
	/** @var HashRing */
	protected $partitionPushRing;
	/** @var array (partition name => JobQueue) reverse sorted by weight */
	protected $partitionQueues = array();

	/** @var BagOStuff */
	protected $cache;

	/** @var int Maximum number of partitions to try */
	protected $maxPartitionsTry;

	const CACHE_TTL_SHORT = 30; // integer; seconds to cache info without re-validating
	const CACHE_TTL_LONG = 300; // integer; seconds to cache info that is kept up to date

	/**
	 * @param array $params Possible keys:
	 *  - sectionsByWiki      : A map of wiki IDs to section names.
	 *                          Wikis will default to using the section "default".
	 *  - partitionsBySection : Map of section names to maps of (partition name => weight).
	 *                          A section called 'default' must be defined if not all wikis
	 *                          have explicitly defined sections.
	 *  - configByPartition   : Map of queue partition names to configuration arrays.
	 *                          These configuration arrays are passed to JobQueue::factory().
	 *                          The options set here are overriden by those passed to this
	 *                          the federated queue itself (e.g. 'order' and 'claimTTL').
	 *  - partitionsNoPush    : List of partition names that can handle pop() but not push().
	 *                          This can be used to migrate away from a certain partition.
	 *  - maxPartitionsTry    : Maximum number of times to attempt job insertion using
	 *                          different partition queues. This improves availability
	 *                          during failure, at the cost of added latency and somewhat
	 *                          less reliable job de-duplication mechanisms.
	 * @throws MWException
	 */
	protected function __construct( array $params ) {
		parent::__construct( $params );
		$section = isset( $params['sectionsByWiki'][$this->wiki] )
			? $params['sectionsByWiki'][$this->wiki]
			: 'default';
		if ( !isset( $params['partitionsBySection'][$section] ) ) {
			throw new MWException( "No configuration for section '$section'." );
		}
		$this->maxPartitionsTry = isset( $params['maxPartitionsTry'] )
			? $params['maxPartitionsTry']
			: 2;
		// Get the full partition map
		$partitionMap = $params['partitionsBySection'][$section];
		arsort( $partitionMap, SORT_NUMERIC );
		// Get the partitions jobs can actually be pushed to
		$partitionPushMap = $partitionMap;
		if ( isset( $params['partitionsNoPush'] ) ) {
			foreach ( $params['partitionsNoPush'] as $partition ) {
				unset( $partitionPushMap[$partition] );
			}
		}
		// Get the config to pass to merge into each partition queue config
		$baseConfig = $params;
		foreach ( array( 'class', 'sectionsByWiki', 'maxPartitionsTry',
			'partitionsBySection', 'configByPartition', 'partitionsNoPush' ) as $o
		) {
			unset( $baseConfig[$o] ); // partition queue doesn't care about this
		}
		// Get the partition queue objects
		foreach ( $partitionMap as $partition => $w ) {
			if ( !isset( $params['configByPartition'][$partition] ) ) {
				throw new MWException( "No configuration for partition '$partition'." );
			}
			$this->partitionQueues[$partition] = JobQueue::factory(
				$baseConfig + $params['configByPartition'][$partition] );
		}
		// Ring of all partitions
		$this->partitionRing = new HashRing( $partitionMap );
		// Get the ring of partitions to push jobs into
		if ( count( $partitionPushMap ) === count( $partitionMap ) ) {
			$this->partitionPushRing = clone $this->partitionRing; // faster
		} else {
			$this->partitionPushRing = new HashRing( $partitionPushMap );
		}
		// Aggregate cache some per-queue values if there are multiple partition queues
		$this->cache = count( $partitionMap ) > 1 ? wfGetMainCache() : new EmptyBagOStuff();
	}

	protected function supportedOrders() {
		// No FIFO due to partitioning, though "rough timestamp order" is supported
		return array( 'undefined', 'random', 'timestamp' );
	}

	protected function optimalOrder() {
		return 'undefined'; // defer to the partitions
	}

	protected function supportsDelayedJobs() {
		return true; // defer checks to the partitions
	}

	protected function doIsEmpty() {
		$key = $this->getCacheKey( 'empty' );

		$isEmpty = $this->cache->get( $key );
		if ( $isEmpty === 'true' ) {
			return true;
		} elseif ( $isEmpty === 'false' ) {
			return false;
		}

		$empty = true;
		$failed = 0;
		foreach ( $this->partitionQueues as $queue ) {
			try {
				$empty = $empty && $queue->doIsEmpty();
			} catch ( JobQueueError $e ) {
				++$failed;
				MWExceptionHandler::logException( $e );
			}
		}
		$this->throwErrorIfAllPartitionsDown( $failed );

		$this->cache->add( $key, $empty ? 'true' : 'false', self::CACHE_TTL_LONG );
		return $empty;
	}

	protected function doGetSize() {
		return $this->getCrossPartitionSum( 'size', 'doGetSize' );
	}

	protected function doGetAcquiredCount() {
		return $this->getCrossPartitionSum( 'acquiredcount', 'doGetAcquiredCount' );
	}

	protected function doGetDelayedCount() {
		return $this->getCrossPartitionSum( 'delayedcount', 'doGetDelayedCount' );
	}

	protected function doGetAbandonedCount() {
		return $this->getCrossPartitionSum( 'abandonedcount', 'doGetAbandonedCount' );
	}

	/**
	 * @param string $type
	 * @param string $method
	 * @return int
	 */
	protected function getCrossPartitionSum( $type, $method ) {
		$key = $this->getCacheKey( $type );

		$count = $this->cache->get( $key );
		if ( $count !== false ) {
			return $count;
		}

		$failed = 0;
		foreach ( $this->partitionQueues as $queue ) {
			try {
				$count += $queue->$method();
			} catch ( JobQueueError $e ) {
				++$failed;
				MWExceptionHandler::logException( $e );
			}
		}
		$this->throwErrorIfAllPartitionsDown( $failed );

		$this->cache->set( $key, $count, self::CACHE_TTL_SHORT );

		return $count;
	}

	protected function doBatchPush( array $jobs, $flags ) {
		// Local ring variable that may be changed to point to a new ring on failure
		$partitionRing = $this->partitionPushRing;
		// Try to insert the jobs and update $partitionsTry on any failures.
		// Retry to insert any remaning jobs again, ignoring the bad partitions.
		$jobsLeft = $jobs;
		// @codingStandardsIgnoreStart Generic.CodeAnalysis.ForLoopWithTestFunctionCall.NotAllowed
		for ( $i = $this->maxPartitionsTry; $i > 0 && count( $jobsLeft ); --$i ) {
			// @codingStandardsIgnoreEnd
			try {
				$partitionRing->getLiveRing();
			} catch ( UnexpectedValueException $e ) {
				break; // all servers down; nothing to insert to
			}
			$jobsLeft = $this->tryJobInsertions( $jobsLeft, $partitionRing, $flags );
		}
		if ( count( $jobsLeft ) ) {
			throw new JobQueueError(
				"Could not insert job(s), {$this->maxPartitionsTry} partitions tried." );
		}
	}

	/**
	 * @param array $jobs
	 * @param HashRing $partitionRing
	 * @param int $flags
	 * @throws JobQueueError
	 * @return array List of Job object that could not be inserted
	 */
	protected function tryJobInsertions( array $jobs, HashRing &$partitionRing, $flags ) {
		$jobsLeft = array();

		// Because jobs are spread across partitions, per-job de-duplication needs
		// to use a consistent hash to avoid allowing duplicate jobs per partition.
		// When inserting a batch of de-duplicated jobs, QOS_ATOMIC is disregarded.
		$uJobsByPartition = array(); // (partition name => job list)
		/** @var Job $job */
		foreach ( $jobs as $key => $job ) {
			if ( $job->ignoreDuplicates() ) {
				$sha1 = sha1( serialize( $job->getDeduplicationInfo() ) );
				$uJobsByPartition[$partitionRing->getLiveLocation( $sha1 )][] = $job;
				unset( $jobs[$key] );
			}
		}
		// Get the batches of jobs that are not de-duplicated
		if ( $flags & self::QOS_ATOMIC ) {
			$nuJobBatches = array( $jobs ); // all or nothing
		} else {
			// Split the jobs into batches and spread them out over servers if there
			// are many jobs. This helps keep the partitions even. Otherwise, send all
			// the jobs to a single partition queue to avoids the extra connections.
			$nuJobBatches = array_chunk( $jobs, 300 );
		}

		// Insert the de-duplicated jobs into the queues...
		foreach ( $uJobsByPartition as $partition => $jobBatch ) {
			/** @var JobQueue $queue */
			$queue = $this->partitionQueues[$partition];
			try {
				$ok = true;
				$queue->doBatchPush( $jobBatch, $flags | self::QOS_ATOMIC );
			} catch ( JobQueueError $e ) {
				$ok = false;
				MWExceptionHandler::logException( $e );
			}
			if ( $ok ) {
				$key = $this->getCacheKey( 'empty' );
				$this->cache->set( $key, 'false', self::CACHE_TTL_LONG );
			} else {
				if ( !$partitionRing->ejectFromLiveRing( $partition, 5 ) ) { // blacklist
					throw new JobQueueError( "Could not insert job(s), no partitions available." );
				}
				$jobsLeft = array_merge( $jobsLeft, $jobBatch ); // not inserted
			}
		}

		// Insert the jobs that are not de-duplicated into the queues...
		foreach ( $nuJobBatches as $jobBatch ) {
			$partition = ArrayUtils::pickRandom( $partitionRing->getLiveLocationWeights() );
			$queue = $this->partitionQueues[$partition];
			try {
				$ok = true;
				$queue->doBatchPush( $jobBatch, $flags | self::QOS_ATOMIC );
			} catch ( JobQueueError $e ) {
				$ok = false;
				MWExceptionHandler::logException( $e );
			}
			if ( $ok ) {
				$key = $this->getCacheKey( 'empty' );
				$this->cache->set( $key, 'false', self::CACHE_TTL_LONG );
			} else {
				if ( !$partitionRing->ejectFromLiveRing( $partition, 5 ) ) { // blacklist
					throw new JobQueueError( "Could not insert job(s), no partitions available." );
				}
				$jobsLeft = array_merge( $jobsLeft, $jobBatch ); // not inserted
			}
		}

		return $jobsLeft;
	}

	protected function doPop() {
		$partitionsTry = $this->partitionRing->getLiveLocationWeights(); // (partition => weight)

		$failed = 0;
		while ( count( $partitionsTry ) ) {
			$partition = ArrayUtils::pickRandom( $partitionsTry );
			if ( $partition === false ) {
				break; // all partitions at 0 weight
			}

			/** @var JobQueue $queue */
			$queue = $this->partitionQueues[$partition];
			try {
				$job = $queue->pop();
			} catch ( JobQueueError $e ) {
				++$failed;
				MWExceptionHandler::logException( $e );
				$job = false;
			}
			if ( $job ) {
				$job->metadata['QueuePartition'] = $partition;

				return $job;
			} else {
				unset( $partitionsTry[$partition] ); // blacklist partition
			}
		}
		$this->throwErrorIfAllPartitionsDown( $failed );

		$key = $this->getCacheKey( 'empty' );
		$this->cache->set( $key, 'true', self::CACHE_TTL_LONG );

		return false;
	}

	protected function doAck( Job $job ) {
		if ( !isset( $job->metadata['QueuePartition'] ) ) {
			throw new MWException( "The given job has no defined partition name." );
		}

		return $this->partitionQueues[$job->metadata['QueuePartition']]->ack( $job );
	}

	protected function doIsRootJobOldDuplicate( Job $job ) {
		$params = $job->getRootJobParams();
		$sigature = $params['rootJobSignature'];
		$partition = $this->partitionPushRing->getLiveLocation( $sigature );
		try {
			return $this->partitionQueues[$partition]->doIsRootJobOldDuplicate( $job );
		} catch ( JobQueueError $e ) {
			if ( $this->partitionPushRing->ejectFromLiveRing( $partition, 5 ) ) {
				$partition = $this->partitionPushRing->getLiveLocation( $sigature );
				return $this->partitionQueues[$partition]->doIsRootJobOldDuplicate( $job );
			}
		}

		return false;
	}

	protected function doDeduplicateRootJob( Job $job ) {
		$params = $job->getRootJobParams();
		$sigature = $params['rootJobSignature'];
		$partition = $this->partitionPushRing->getLiveLocation( $sigature );
		try {
			return $this->partitionQueues[$partition]->doDeduplicateRootJob( $job );
		} catch ( JobQueueError $e ) {
			if ( $this->partitionPushRing->ejectFromLiveRing( $partition, 5 ) ) {
				$partition = $this->partitionPushRing->getLiveLocation( $sigature );
				return $this->partitionQueues[$partition]->doDeduplicateRootJob( $job );
			}
		}

		return false;
	}

	protected function doDelete() {
		$failed = 0;
		/** @var JobQueue $queue */
		foreach ( $this->partitionQueues as $queue ) {
			try {
				$queue->doDelete();
			} catch ( JobQueueError $e ) {
				++$failed;
				MWExceptionHandler::logException( $e );
			}
		}
		$this->throwErrorIfAllPartitionsDown( $failed );
		return true;
	}

	protected function doWaitForBackups() {
		$failed = 0;
		/** @var JobQueue $queue */
		foreach ( $this->partitionQueues as $queue ) {
			try {
				$queue->waitForBackups();
			} catch ( JobQueueError $e ) {
				++$failed;
				MWExceptionHandler::logException( $e );
			}
		}
		$this->throwErrorIfAllPartitionsDown( $failed );
	}

	protected function doGetPeriodicTasks() {
		$tasks = array();
		/** @var JobQueue $queue */
		foreach ( $this->partitionQueues as $partition => $queue ) {
			foreach ( $queue->getPeriodicTasks() as $task => $def ) {
				$tasks["{$partition}:{$task}"] = $def;
			}
		}

		return $tasks;
	}

	protected function doFlushCaches() {
		static $types = array(
			'empty',
			'size',
			'acquiredcount',
			'delayedcount',
			'abandonedcount'
		);

		foreach ( $types as $type ) {
			$this->cache->delete( $this->getCacheKey( $type ) );
		}

		/** @var JobQueue $queue */
		foreach ( $this->partitionQueues as $queue ) {
			$queue->doFlushCaches();
		}
	}

	public function getAllQueuedJobs() {
		$iterator = new AppendIterator();

		/** @var JobQueue $queue */
		foreach ( $this->partitionQueues as $queue ) {
			$iterator->append( $queue->getAllQueuedJobs() );
		}

		return $iterator;
	}

	public function getAllDelayedJobs() {
		$iterator = new AppendIterator();

		/** @var JobQueue $queue */
		foreach ( $this->partitionQueues as $queue ) {
			$iterator->append( $queue->getAllDelayedJobs() );
		}

		return $iterator;
	}

	public function getCoalesceLocationInternal() {
		return "JobQueueFederated:wiki:{$this->wiki}" .
			sha1( serialize( array_keys( $this->partitionQueues ) ) );
	}

	protected function doGetSiblingQueuesWithJobs( array $types ) {
		$result = array();

		$failed = 0;
		/** @var JobQueue $queue */
		foreach ( $this->partitionQueues as $queue ) {
			try {
				$nonEmpty = $queue->doGetSiblingQueuesWithJobs( $types );
				if ( is_array( $nonEmpty ) ) {
					$result = array_unique( array_merge( $result, $nonEmpty ) );
				} else {
					return null; // not supported on all partitions; bail
				}
				if ( count( $result ) == count( $types ) ) {
					break; // short-circuit
				}
			} catch ( JobQueueError $e ) {
				++$failed;
				MWExceptionHandler::logException( $e );
			}
		}
		$this->throwErrorIfAllPartitionsDown( $failed );

		return array_values( $result );
	}

	protected function doGetSiblingQueueSizes( array $types ) {
		$result = array();
		$failed = 0;
		/** @var JobQueue $queue */
		foreach ( $this->partitionQueues as $queue ) {
			try {
				$sizes = $queue->doGetSiblingQueueSizes( $types );
				if ( is_array( $sizes ) ) {
					foreach ( $sizes as $type => $size ) {
						$result[$type] = isset( $result[$type] ) ? $result[$type] + $size : $size;
					}
				} else {
					return null; // not supported on all partitions; bail
				}
			} catch ( JobQueueError $e ) {
				++$failed;
				MWExceptionHandler::logException( $e );
			}
		}
		$this->throwErrorIfAllPartitionsDown( $failed );

		return $result;
	}

	/**
	 * Throw an error if no partitions available
	 *
	 * @param int $down The number of up partitions down
	 * @return void
	 * @throws JobQueueError
	 */
	protected function throwErrorIfAllPartitionsDown( $down ) {
		if ( $down >= count( $this->partitionQueues ) ) {
			throw new JobQueueError( 'No queue partitions available.' );
		}
	}

	public function setTestingPrefix( $key ) {
		/** @var JobQueue $queue */
		foreach ( $this->partitionQueues as $queue ) {
			$queue->setTestingPrefix( $key );
		}
	}

	/**
	 * @param string $property
	 * @return string
	 */
	private function getCacheKey( $property ) {
		list( $db, $prefix ) = wfSplitWikiID( $this->wiki );

		return wfForeignMemcKey( $db, $prefix, 'jobqueue', $this->type, $property );
	}
}