mediawiki.searchSuggest: Show full article title as a tooltip for each suggestion
[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 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 = true;
269 $queue->doBatchPush( $jobBatch, $flags | self::QOS_ATOMIC );
270 } catch ( JobQueueError $e ) {
271 $ok = false;
272 MWExceptionHandler::logException( $e );
273 }
274 if ( $ok ) {
275 $key = $this->getCacheKey( 'empty' );
276 $this->cache->set( $key, 'false', JobQueueDB::CACHE_TTL_LONG );
277 } else {
278 $partitionRing = $partitionRing->newWithoutLocation( $partition ); // blacklist
279 if ( !$partitionRing ) {
280 throw new JobQueueError( "Could not insert job(s), no partitions available." );
281 }
282 $jobsLeft = array_merge( $jobsLeft, $jobBatch ); // not inserted
283 }
284 }
285
286 // Insert the jobs that are not de-duplicated into the queues...
287 foreach ( $nuJobBatches as $jobBatch ) {
288 $partition = ArrayUtils::pickRandom( $partitionRing->getLocationWeights() );
289 $queue = $this->partitionQueues[$partition];
290 try {
291 $ok = true;
292 $queue->doBatchPush( $jobBatch, $flags | self::QOS_ATOMIC );
293 } catch ( JobQueueError $e ) {
294 $ok = false;
295 MWExceptionHandler::logException( $e );
296 }
297 if ( $ok ) {
298 $key = $this->getCacheKey( 'empty' );
299 $this->cache->set( $key, 'false', JobQueueDB::CACHE_TTL_LONG );
300 } else {
301 $partitionRing = $partitionRing->newWithoutLocation( $partition ); // blacklist
302 if ( !$partitionRing ) {
303 throw new JobQueueError( "Could not insert job(s), no partitions available." );
304 }
305 $jobsLeft = array_merge( $jobsLeft, $jobBatch ); // not inserted
306 }
307 }
308
309 return $jobsLeft;
310 }
311
312 protected function doPop() {
313 $key = $this->getCacheKey( 'empty' );
314
315 $isEmpty = $this->cache->get( $key );
316 if ( $isEmpty === 'true' ) {
317 return false;
318 }
319
320 $partitionsTry = $this->partitionMap; // (partition => weight)
321
322 $failed = 0;
323 while ( count( $partitionsTry ) ) {
324 $partition = ArrayUtils::pickRandom( $partitionsTry );
325 if ( $partition === false ) {
326 break; // all partitions at 0 weight
327 }
328
329 /** @var JobQueue $queue */
330 $queue = $this->partitionQueues[$partition];
331 try {
332 $job = $queue->pop();
333 } catch ( JobQueueError $e ) {
334 ++$failed;
335 MWExceptionHandler::logException( $e );
336 $job = false;
337 }
338 if ( $job ) {
339 $job->metadata['QueuePartition'] = $partition;
340
341 return $job;
342 } else {
343 unset( $partitionsTry[$partition] ); // blacklist partition
344 }
345 }
346 $this->throwErrorIfAllPartitionsDown( $failed );
347
348 $this->cache->set( $key, 'true', JobQueueDB::CACHE_TTL_LONG );
349
350 return false;
351 }
352
353 protected function doAck( Job $job ) {
354 if ( !isset( $job->metadata['QueuePartition'] ) ) {
355 throw new MWException( "The given job has no defined partition name." );
356 }
357
358 return $this->partitionQueues[$job->metadata['QueuePartition']]->ack( $job );
359 }
360
361 protected function doIsRootJobOldDuplicate( Job $job ) {
362 $params = $job->getRootJobParams();
363 $partitions = $this->partitionPushRing->getLocations( $params['rootJobSignature'], 2 );
364 try {
365 return $this->partitionQueues[$partitions[0]]->doIsRootJobOldDuplicate( $job );
366 } catch ( JobQueueError $e ) {
367 if ( isset( $partitions[1] ) ) { // check fallback partition
368 return $this->partitionQueues[$partitions[1]]->doIsRootJobOldDuplicate( $job );
369 }
370 }
371
372 return false;
373 }
374
375 protected function doDeduplicateRootJob( Job $job ) {
376 $params = $job->getRootJobParams();
377 $partitions = $this->partitionPushRing->getLocations( $params['rootJobSignature'], 2 );
378 try {
379 return $this->partitionQueues[$partitions[0]]->doDeduplicateRootJob( $job );
380 } catch ( JobQueueError $e ) {
381 if ( isset( $partitions[1] ) ) { // check fallback partition
382 return $this->partitionQueues[$partitions[1]]->doDeduplicateRootJob( $job );
383 }
384 }
385
386 return false;
387 }
388
389 protected function doDelete() {
390 $failed = 0;
391 /** @var JobQueue $queue */
392 foreach ( $this->partitionQueues as $queue ) {
393 try {
394 $queue->doDelete();
395 } catch ( JobQueueError $e ) {
396 ++$failed;
397 MWExceptionHandler::logException( $e );
398 }
399 }
400 $this->throwErrorIfAllPartitionsDown( $failed );
401 return true;
402 }
403
404 protected function doWaitForBackups() {
405 $failed = 0;
406 /** @var JobQueue $queue */
407 foreach ( $this->partitionQueues as $queue ) {
408 try {
409 $queue->waitForBackups();
410 } catch ( JobQueueError $e ) {
411 ++$failed;
412 MWExceptionHandler::logException( $e );
413 }
414 }
415 $this->throwErrorIfAllPartitionsDown( $failed );
416 }
417
418 protected function doGetPeriodicTasks() {
419 $tasks = array();
420 /** @var JobQueue $queue */
421 foreach ( $this->partitionQueues as $partition => $queue ) {
422 foreach ( $queue->getPeriodicTasks() as $task => $def ) {
423 $tasks["{$partition}:{$task}"] = $def;
424 }
425 }
426
427 return $tasks;
428 }
429
430 protected function doFlushCaches() {
431 static $types = array(
432 'empty',
433 'size',
434 'acquiredcount',
435 'delayedcount',
436 'abandonedcount'
437 );
438
439 foreach ( $types as $type ) {
440 $this->cache->delete( $this->getCacheKey( $type ) );
441 }
442
443 /** @var JobQueue $queue */
444 foreach ( $this->partitionQueues as $queue ) {
445 $queue->doFlushCaches();
446 }
447 }
448
449 public function getAllQueuedJobs() {
450 $iterator = new AppendIterator();
451
452 /** @var JobQueue $queue */
453 foreach ( $this->partitionQueues as $queue ) {
454 $iterator->append( $queue->getAllQueuedJobs() );
455 }
456
457 return $iterator;
458 }
459
460 public function getAllDelayedJobs() {
461 $iterator = new AppendIterator();
462
463 /** @var JobQueue $queue */
464 foreach ( $this->partitionQueues as $queue ) {
465 $iterator->append( $queue->getAllDelayedJobs() );
466 }
467
468 return $iterator;
469 }
470
471 public function getCoalesceLocationInternal() {
472 return "JobQueueFederated:wiki:{$this->wiki}" .
473 sha1( serialize( array_keys( $this->partitionMap ) ) );
474 }
475
476 protected function doGetSiblingQueuesWithJobs( array $types ) {
477 $result = array();
478
479 $failed = 0;
480 /** @var JobQueue $queue */
481 foreach ( $this->partitionQueues as $queue ) {
482 try {
483 $nonEmpty = $queue->doGetSiblingQueuesWithJobs( $types );
484 if ( is_array( $nonEmpty ) ) {
485 $result = array_unique( array_merge( $result, $nonEmpty ) );
486 } else {
487 return null; // not supported on all partitions; bail
488 }
489 if ( count( $result ) == count( $types ) ) {
490 break; // short-circuit
491 }
492 } catch ( JobQueueError $e ) {
493 ++$failed;
494 MWExceptionHandler::logException( $e );
495 }
496 }
497 $this->throwErrorIfAllPartitionsDown( $failed );
498
499 return array_values( $result );
500 }
501
502 protected function doGetSiblingQueueSizes( array $types ) {
503 $result = array();
504 $failed = 0;
505 /** @var JobQueue $queue */
506 foreach ( $this->partitionQueues as $queue ) {
507 try {
508 $sizes = $queue->doGetSiblingQueueSizes( $types );
509 if ( is_array( $sizes ) ) {
510 foreach ( $sizes as $type => $size ) {
511 $result[$type] = isset( $result[$type] ) ? $result[$type] + $size : $size;
512 }
513 } else {
514 return null; // not supported on all partitions; bail
515 }
516 } catch ( JobQueueError $e ) {
517 ++$failed;
518 MWExceptionHandler::logException( $e );
519 }
520 }
521 $this->throwErrorIfAllPartitionsDown( $failed );
522
523 return $result;
524 }
525
526 /**
527 * Throw an error if no partitions available
528 *
529 * @param int $down The number of up partitions down
530 * @return void
531 * @throws JobQueueError
532 */
533 protected function throwErrorIfAllPartitionsDown( $down ) {
534 if ( $down >= count( $this->partitionQueues ) ) {
535 throw new JobQueueError( 'No queue partitions available.' );
536 }
537 }
538
539 public function setTestingPrefix( $key ) {
540 /** @var JobQueue $queue */
541 foreach ( $this->partitionQueues as $queue ) {
542 $queue->setTestingPrefix( $key );
543 }
544 }
545
546 /**
547 * @param $property
548 * @return string
549 */
550 private function getCacheKey( $property ) {
551 list( $db, $prefix ) = wfSplitWikiID( $this->wiki );
552
553 return wfForeignMemcKey( $db, $prefix, 'jobqueue', $this->type, $property );
554 }
555 }