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