Merge "Deleting a page and then immediately create-protecting it caused a PHP Fatal...
[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 foreach ( $this->partitionQueues as $queue ) {
154 try {
155 if ( !$queue->doIsEmpty() ) {
156 $this->cache->add( $key, 'false', self::CACHE_TTL_LONG );
157
158 return false;
159 }
160 } catch ( JobQueueError $e ) {
161 MWExceptionHandler::logException( $e );
162 }
163 }
164
165 $this->cache->add( $key, 'true', self::CACHE_TTL_LONG );
166
167 return true;
168 }
169
170 protected function doGetSize() {
171 return $this->getCrossPartitionSum( 'size', 'doGetSize' );
172 }
173
174 protected function doGetAcquiredCount() {
175 return $this->getCrossPartitionSum( 'acquiredcount', 'doGetAcquiredCount' );
176 }
177
178 protected function doGetDelayedCount() {
179 return $this->getCrossPartitionSum( 'delayedcount', 'doGetDelayedCount' );
180 }
181
182 protected function doGetAbandonedCount() {
183 return $this->getCrossPartitionSum( 'abandonedcount', 'doGetAbandonedCount' );
184 }
185
186 /**
187 * @param string $type
188 * @param string $method
189 * @return int
190 */
191 protected function getCrossPartitionSum( $type, $method ) {
192 $key = $this->getCacheKey( $type );
193
194 $count = $this->cache->get( $key );
195 if ( is_int( $count ) ) {
196 return $count;
197 }
198
199 $count = 0;
200 foreach ( $this->partitionQueues as $queue ) {
201 try {
202 $count += $queue->$method();
203 } catch ( JobQueueError $e ) {
204 MWExceptionHandler::logException( $e );
205 }
206 }
207
208 $this->cache->set( $key, $count, self::CACHE_TTL_SHORT );
209
210 return $count;
211 }
212
213 protected function doBatchPush( array $jobs, $flags ) {
214 // Local ring variable that may be changed to point to a new ring on failure
215 $partitionRing = $this->partitionPushRing;
216 // Try to insert the jobs and update $partitionsTry on any failures.
217 // Retry to insert any remaning jobs again, ignoring the bad partitions.
218 $jobsLeft = $jobs;
219 for ( $i = $this->maxPartitionsTry; $i > 0 && count( $jobsLeft ); --$i ) {
220 $jobsLeft = $this->tryJobInsertions( $jobsLeft, $partitionRing, $flags );
221 }
222 if ( count( $jobsLeft ) ) {
223 throw new JobQueueError(
224 "Could not insert job(s), {$this->maxPartitionsTry} partitions tried." );
225 }
226
227 return true;
228 }
229
230 /**
231 * @param array $jobs
232 * @param HashRing $partitionRing
233 * @param int $flags
234 * @throws JobQueueError
235 * @return array List of Job object that could not be inserted
236 */
237 protected function tryJobInsertions( array $jobs, HashRing &$partitionRing, $flags ) {
238 $jobsLeft = array();
239
240 // Because jobs are spread across partitions, per-job de-duplication needs
241 // to use a consistent hash to avoid allowing duplicate jobs per partition.
242 // When inserting a batch of de-duplicated jobs, QOS_ATOMIC is disregarded.
243 $uJobsByPartition = array(); // (partition name => job list)
244 /** @var Job $job */
245 foreach ( $jobs as $key => $job ) {
246 if ( $job->ignoreDuplicates() ) {
247 $sha1 = sha1( serialize( $job->getDeduplicationInfo() ) );
248 $uJobsByPartition[$partitionRing->getLocation( $sha1 )][] = $job;
249 unset( $jobs[$key] );
250 }
251 }
252 // Get the batches of jobs that are not de-duplicated
253 if ( $flags & self::QOS_ATOMIC ) {
254 $nuJobBatches = array( $jobs ); // all or nothing
255 } else {
256 // Split the jobs into batches and spread them out over servers if there
257 // are many jobs. This helps keep the partitions even. Otherwise, send all
258 // the jobs to a single partition queue to avoids the extra connections.
259 $nuJobBatches = array_chunk( $jobs, 300 );
260 }
261
262 // Insert the de-duplicated jobs into the queues...
263 foreach ( $uJobsByPartition as $partition => $jobBatch ) {
264 /** @var JobQueue $queue */
265 $queue = $this->partitionQueues[$partition];
266 try {
267 $ok = $queue->doBatchPush( $jobBatch, $flags | self::QOS_ATOMIC );
268 } catch ( JobQueueError $e ) {
269 $ok = false;
270 MWExceptionHandler::logException( $e );
271 }
272 if ( $ok ) {
273 $key = $this->getCacheKey( 'empty' );
274 $this->cache->set( $key, 'false', JobQueueDB::CACHE_TTL_LONG );
275 } else {
276 $partitionRing = $partitionRing->newWithoutLocation( $partition ); // blacklist
277 if ( !$partitionRing ) {
278 throw new JobQueueError( "Could not insert job(s), all partitions are down." );
279 }
280 $jobsLeft = array_merge( $jobsLeft, $jobBatch ); // not inserted
281 }
282 }
283
284 // Insert the jobs that are not de-duplicated into the queues...
285 foreach ( $nuJobBatches as $jobBatch ) {
286 $partition = ArrayUtils::pickRandom( $partitionRing->getLocationWeights() );
287 $queue = $this->partitionQueues[$partition];
288 try {
289 $ok = $queue->doBatchPush( $jobBatch, $flags | self::QOS_ATOMIC );
290 } catch ( JobQueueError $e ) {
291 $ok = false;
292 MWExceptionHandler::logException( $e );
293 }
294 if ( $ok ) {
295 $key = $this->getCacheKey( 'empty' );
296 $this->cache->set( $key, 'false', JobQueueDB::CACHE_TTL_LONG );
297 } else {
298 $partitionRing = $partitionRing->newWithoutLocation( $partition ); // blacklist
299 if ( !$partitionRing ) {
300 throw new JobQueueError( "Could not insert job(s), all partitions are down." );
301 }
302 $jobsLeft = array_merge( $jobsLeft, $jobBatch ); // not inserted
303 }
304 }
305
306 return $jobsLeft;
307 }
308
309 protected function doPop() {
310 $key = $this->getCacheKey( 'empty' );
311
312 $isEmpty = $this->cache->get( $key );
313 if ( $isEmpty === 'true' ) {
314 return false;
315 }
316
317 $partitionsTry = $this->partitionMap; // (partition => weight)
318
319 while ( count( $partitionsTry ) ) {
320 $partition = ArrayUtils::pickRandom( $partitionsTry );
321 if ( $partition === false ) {
322 break; // all partitions at 0 weight
323 }
324
325 /** @var JobQueue $queue */
326 $queue = $this->partitionQueues[$partition];
327 try {
328 $job = $queue->pop();
329 } catch ( JobQueueError $e ) {
330 $job = false;
331 MWExceptionHandler::logException( $e );
332 }
333 if ( $job ) {
334 $job->metadata['QueuePartition'] = $partition;
335
336 return $job;
337 } else {
338 unset( $partitionsTry[$partition] ); // blacklist partition
339 }
340 }
341
342 $this->cache->set( $key, 'true', JobQueueDB::CACHE_TTL_LONG );
343
344 return false;
345 }
346
347 protected function doAck( Job $job ) {
348 if ( !isset( $job->metadata['QueuePartition'] ) ) {
349 throw new MWException( "The given job has no defined partition name." );
350 }
351
352 return $this->partitionQueues[$job->metadata['QueuePartition']]->ack( $job );
353 }
354
355 protected function doIsRootJobOldDuplicate( Job $job ) {
356 $params = $job->getRootJobParams();
357 $partitions = $this->partitionPushRing->getLocations( $params['rootJobSignature'], 2 );
358 try {
359 return $this->partitionQueues[$partitions[0]]->doIsRootJobOldDuplicate( $job );
360 } catch ( JobQueueError $e ) {
361 if ( isset( $partitions[1] ) ) { // check fallback partition
362 return $this->partitionQueues[$partitions[1]]->doIsRootJobOldDuplicate( $job );
363 }
364 }
365
366 return false;
367 }
368
369 protected function doDeduplicateRootJob( Job $job ) {
370 $params = $job->getRootJobParams();
371 $partitions = $this->partitionPushRing->getLocations( $params['rootJobSignature'], 2 );
372 try {
373 return $this->partitionQueues[$partitions[0]]->doDeduplicateRootJob( $job );
374 } catch ( JobQueueError $e ) {
375 if ( isset( $partitions[1] ) ) { // check fallback partition
376 return $this->partitionQueues[$partitions[1]]->doDeduplicateRootJob( $job );
377 }
378 }
379
380 return false;
381 }
382
383 protected function doDelete() {
384 /** @var JobQueue $queue */
385 foreach ( $this->partitionQueues as $queue ) {
386 try {
387 $queue->doDelete();
388 } catch ( JobQueueError $e ) {
389 MWExceptionHandler::logException( $e );
390 }
391 }
392 }
393
394 protected function doWaitForBackups() {
395 /** @var JobQueue $queue */
396 foreach ( $this->partitionQueues as $queue ) {
397 try {
398 $queue->waitForBackups();
399 } catch ( JobQueueError $e ) {
400 MWExceptionHandler::logException( $e );
401 }
402 }
403 }
404
405 protected function doGetPeriodicTasks() {
406 $tasks = array();
407 /** @var JobQueue $queue */
408 foreach ( $this->partitionQueues as $partition => $queue ) {
409 foreach ( $queue->getPeriodicTasks() as $task => $def ) {
410 $tasks["{$partition}:{$task}"] = $def;
411 }
412 }
413
414 return $tasks;
415 }
416
417 protected function doFlushCaches() {
418 static $types = array(
419 'empty',
420 'size',
421 'acquiredcount',
422 'delayedcount',
423 'abandonedcount'
424 );
425
426 foreach ( $types as $type ) {
427 $this->cache->delete( $this->getCacheKey( $type ) );
428 }
429
430 /** @var JobQueue $queue */
431 foreach ( $this->partitionQueues as $queue ) {
432 $queue->doFlushCaches();
433 }
434 }
435
436 public function getAllQueuedJobs() {
437 $iterator = new AppendIterator();
438
439 /** @var JobQueue $queue */
440 foreach ( $this->partitionQueues as $queue ) {
441 $iterator->append( $queue->getAllQueuedJobs() );
442 }
443
444 return $iterator;
445 }
446
447 public function getAllDelayedJobs() {
448 $iterator = new AppendIterator();
449
450 /** @var JobQueue $queue */
451 foreach ( $this->partitionQueues as $queue ) {
452 $iterator->append( $queue->getAllDelayedJobs() );
453 }
454
455 return $iterator;
456 }
457
458 public function getCoalesceLocationInternal() {
459 return "JobQueueFederated:wiki:{$this->wiki}" .
460 sha1( serialize( array_keys( $this->partitionMap ) ) );
461 }
462
463 protected function doGetSiblingQueuesWithJobs( array $types ) {
464 $result = array();
465
466 /** @var JobQueue $queue */
467 foreach ( $this->partitionQueues as $queue ) {
468 try {
469 $nonEmpty = $queue->doGetSiblingQueuesWithJobs( $types );
470 if ( is_array( $nonEmpty ) ) {
471 $result = array_unique( array_merge( $result, $nonEmpty ) );
472 } else {
473 return null; // not supported on all partitions; bail
474 }
475 if ( count( $result ) == count( $types ) ) {
476 break; // short-circuit
477 }
478 } catch ( JobQueueError $e ) {
479 MWExceptionHandler::logException( $e );
480 }
481 }
482
483 return array_values( $result );
484 }
485
486 protected function doGetSiblingQueueSizes( array $types ) {
487 $result = array();
488
489 /** @var JobQueue $queue */
490 foreach ( $this->partitionQueues as $queue ) {
491 try {
492 $sizes = $queue->doGetSiblingQueueSizes( $types );
493 if ( is_array( $sizes ) ) {
494 foreach ( $sizes as $type => $size ) {
495 $result[$type] = isset( $result[$type] ) ? $result[$type] + $size : $size;
496 }
497 } else {
498 return null; // not supported on all partitions; bail
499 }
500 } catch ( JobQueueError $e ) {
501 MWExceptionHandler::logException( $e );
502 }
503 }
504
505 return $result;
506 }
507
508 public function setTestingPrefix( $key ) {
509 /** @var JobQueue $queue */
510 foreach ( $this->partitionQueues as $queue ) {
511 $queue->setTestingPrefix( $key );
512 }
513 }
514
515 /**
516 * @param $property
517 * @return string
518 */
519 private function getCacheKey( $property ) {
520 list( $db, $prefix ) = wfSplitWikiID( $this->wiki );
521
522 return wfForeignMemcKey( $db, $prefix, 'jobqueue', $this->type, $property );
523 }
524 }