Merge "Improve documentation for $wgRecentChangesFlags"
[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".
44 *
45 * @ingroup JobQueue
46 * @since 1.22
47 */
48 class JobQueueFederated extends JobQueue {
49 /** @var Array (wiki ID => section name) */
50 protected $sectionsByWiki = array();
51 /** @var Array (section name => (partition name => weight)) */
52 protected $partitionsBySection = array();
53 /** @var Array (section name => config array) */
54 protected $configByPartition = array();
55 /** @var Array (partition names => integer) */
56 protected $partitionsNoPush = array();
57
58 /** @var HashRing */
59 protected $partitionRing;
60 /** @var Array (partition name => JobQueue) */
61 protected $partitionQueues = array();
62 /** @var BagOStuff */
63 protected $cache;
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 * @param array $params
82 */
83 protected function __construct( array $params ) {
84 parent::__construct( $params );
85 $this->sectionsByWiki = isset( $params['sectionsByWiki'] )
86 ? $params['sectionsByWiki']
87 : array(); // all in "default" section
88 $this->partitionsBySection = $params['partitionsBySection'];
89 $this->configByPartition = $params['configByPartition'];
90 if ( isset( $params['partitionsNoPush'] ) ) {
91 $this->partitionsNoPush = array_flip( $params['partitionsNoPush'] );
92 }
93 $baseConfig = $params;
94 foreach ( array( 'class', 'sectionsByWiki',
95 'partitionsBySection', 'configByPartition', 'partitionsNoPush' ) as $o )
96 {
97 unset( $baseConfig[$o] );
98 }
99 foreach ( $this->getPartitionMap() as $partition => $w ) {
100 if ( !isset( $this->configByPartition[$partition] ) ) {
101 throw new MWException( "No configuration for partition '$partition'." );
102 }
103 $this->partitionQueues[$partition] = JobQueue::factory(
104 $baseConfig + $this->configByPartition[$partition]
105 );
106 }
107 // Get the ring of partitions to push job de-duplication information into
108 $partitionsTry = array_diff_key(
109 $this->getPartitionMap(),
110 $this->partitionsNoPush
111 ); // (partition => weight)
112 $this->partitionRing = new HashRing( $partitionsTry );
113 // Aggregate cache some per-queue values if there are multiple partition queues
114 $this->cache = $this->isFederated() ? wfGetMainCache() : new EmptyBagOStuff();
115 }
116
117 protected function supportedOrders() {
118 // No FIFO due to partitioning, though "rough timestamp order" is supported
119 return array( 'undefined', 'random', 'timestamp' );
120 }
121
122 protected function optimalOrder() {
123 return 'undefined'; // defer to the partitions
124 }
125
126 protected function supportsDelayedJobs() {
127 return true; // defer checks to the partitions
128 }
129
130 protected function doIsEmpty() {
131 $key = $this->getCacheKey( 'empty' );
132
133 $isEmpty = $this->cache->get( $key );
134 if ( $isEmpty === 'true' ) {
135 return true;
136 } elseif ( $isEmpty === 'false' ) {
137 return false;
138 }
139
140 foreach ( $this->partitionQueues as $queue ) {
141 if ( !$queue->doIsEmpty() ) {
142 $this->cache->add( $key, 'false', self::CACHE_TTL_LONG );
143 return false;
144 }
145 }
146
147 $this->cache->add( $key, 'true', self::CACHE_TTL_LONG );
148 return true;
149 }
150
151 protected function doGetSize() {
152 return $this->getCrossPartitionSum( 'size', 'doGetSize' );
153 }
154
155 protected function doGetAcquiredCount() {
156 return $this->getCrossPartitionSum( 'acquiredcount', 'doGetAcquiredCount' );
157 }
158
159 protected function doGetDelayedCount() {
160 return $this->getCrossPartitionSum( 'delayedcount', 'doGetDelayedCount' );
161 }
162
163 protected function doGetAbandonedCount() {
164 return $this->getCrossPartitionSum( 'abandonedcount', 'doGetAbandonedCount' );
165 }
166
167 /**
168 * @param string $type
169 * @param string $method
170 * @return integer
171 */
172 protected function getCrossPartitionSum( $type, $method ) {
173 $key = $this->getCacheKey( $type );
174
175 $count = $this->cache->get( $key );
176 if ( is_int( $count ) ) {
177 return $count;
178 }
179
180 $count = 0;
181 foreach ( $this->partitionQueues as $queue ) {
182 $count += $queue->$method();
183 }
184
185 $this->cache->set( $key, $count, self::CACHE_TTL_SHORT );
186 return $count;
187 }
188
189 protected function doBatchPush( array $jobs, $flags ) {
190 if ( !count( $jobs ) ) {
191 return true; // nothing to do
192 }
193
194 $partitionsTry = array_diff_key(
195 $this->getPartitionMap(),
196 $this->partitionsNoPush
197 ); // (partition => weight)
198
199 // Try to insert the jobs and update $partitionsTry on any failures
200 $jobsLeft = $this->tryJobInsertions( $jobs, $partitionsTry, $flags );
201 if ( count( $jobsLeft ) ) { // some jobs failed to insert?
202 // Try to insert the remaning jobs once more, ignoring the bad partitions
203 return !count( $this->tryJobInsertions( $jobsLeft, $partitionsTry, $flags ) );
204 } else {
205 return true;
206 }
207 }
208
209 /**
210 * @param array $jobs
211 * @param array $partitionsTry
212 * @param integer $flags
213 * @return array List of Job object that could not be inserted
214 */
215 protected function tryJobInsertions( array $jobs, array &$partitionsTry, $flags ) {
216 if ( !count( $partitionsTry ) ) {
217 return $jobs; // can't insert anything
218 }
219
220 $jobsLeft = array();
221
222 $partitionRing = new HashRing( $partitionsTry );
223 // Because jobs are spread across partitions, per-job de-duplication needs
224 // to use a consistent hash to avoid allowing duplicate jobs per partition.
225 // When inserting a batch of de-duplicated jobs, QOS_ATOMIC is disregarded.
226 $uJobsByPartition = array(); // (partition name => job list)
227 foreach ( $jobs as $key => $job ) {
228 if ( $job->ignoreDuplicates() ) {
229 $sha1 = sha1( serialize( $job->getDeduplicationInfo() ) );
230 $uJobsByPartition[$partitionRing->getLocation( $sha1 )][] = $job;
231 unset( $jobs[$key] );
232 }
233 }
234 // Get the batches of jobs that are not de-duplicated
235 if ( $flags & self::QOS_ATOMIC ) {
236 $nuJobBatches = array( $jobs ); // all or nothing
237 } else {
238 // Split the jobs into batches and spread them out over servers if there
239 // are many jobs. This helps keep the partitions even. Otherwise, send all
240 // the jobs to a single partition queue to avoids the extra connections.
241 $nuJobBatches = array_chunk( $jobs, 300 );
242 }
243
244 // Insert the de-duplicated jobs into the queues...
245 foreach ( $uJobsByPartition as $partition => $jobBatch ) {
246 $queue = $this->partitionQueues[$partition];
247 if ( $queue->doBatchPush( $jobBatch, $flags ) ) {
248 $key = $this->getCacheKey( 'empty' );
249 $this->cache->set( $key, 'false', JobQueueDB::CACHE_TTL_LONG );
250 } else {
251 unset( $partitionsTry[$partition] ); // blacklist partition
252 $jobsLeft = array_merge( $jobsLeft, $jobBatch ); // not inserted
253 }
254 }
255 // Insert the jobs that are not de-duplicated into the queues...
256 foreach ( $nuJobBatches as $jobBatch ) {
257 $partition = ArrayUtils::pickRandom( $partitionsTry );
258 if ( $partition === false ) { // all partitions at 0 weight?
259 $jobsLeft = array_merge( $jobsLeft, $jobBatch ); // not inserted
260 } else {
261 $queue = $this->partitionQueues[$partition];
262 if ( $queue->doBatchPush( $jobBatch, $flags ) ) {
263 $key = $this->getCacheKey( 'empty' );
264 $this->cache->set( $key, 'false', JobQueueDB::CACHE_TTL_LONG );
265 } else {
266 unset( $partitionsTry[$partition] ); // blacklist partition
267 $jobsLeft = array_merge( $jobsLeft, $jobBatch ); // not inserted
268 }
269 }
270 }
271
272 return $jobsLeft;
273 }
274
275 protected function doPop() {
276 $key = $this->getCacheKey( 'empty' );
277
278 $isEmpty = $this->cache->get( $key );
279 if ( $isEmpty === 'true' ) {
280 return false;
281 }
282
283 $partitionsTry = $this->getPartitionMap(); // (partition => weight)
284
285 while ( count( $partitionsTry ) ) {
286 $partition = ArrayUtils::pickRandom( $partitionsTry );
287 if ( $partition === false ) {
288 break; // all partitions at 0 weight
289 }
290 $queue = $this->partitionQueues[$partition];
291 $job = $queue->pop();
292 if ( $job ) {
293 $job->metadata['QueuePartition'] = $partition;
294 return $job;
295 } else {
296 unset( $partitionsTry[$partition] ); // blacklist partition
297 }
298 }
299
300 $this->cache->set( $key, 'true', JobQueueDB::CACHE_TTL_LONG );
301 return false;
302 }
303
304 protected function doAck( Job $job ) {
305 if ( !isset( $job->metadata['QueuePartition'] ) ) {
306 throw new MWException( "The given job has no defined partition name." );
307 }
308 return $this->partitionQueues[$job->metadata['QueuePartition']]->ack( $job );
309 }
310
311 protected function doIsRootJobOldDuplicate( Job $job ) {
312 $params = $job->getRootJobParams();
313 $partitions = $this->partitionRing->getLocations( $params['rootJobSignature'], 2 );
314 try {
315 return $this->partitionQueues[$partitions[0]]->doIsRootJobOldDuplicate( $job );
316 } catch ( MWException $e ) {
317 if ( isset( $partitions[1] ) ) { // check fallback partition
318 return $this->partitionQueues[$partitions[1]]->doIsRootJobOldDuplicate( $job );
319 }
320 }
321 return false;
322 }
323
324 protected function doDeduplicateRootJob( Job $job ) {
325 $params = $job->getRootJobParams();
326 $partitions = $this->partitionRing->getLocations( $params['rootJobSignature'], 2 );
327 try {
328 return $this->partitionQueues[$partitions[0]]->doDeduplicateRootJob( $job );
329 } catch ( MWException $e ) {
330 if ( isset( $partitions[1] ) ) { // check fallback partition
331 return $this->partitionQueues[$partitions[1]]->doDeduplicateRootJob( $job );
332 }
333 }
334 return false;
335 }
336
337 protected function doDelete() {
338 foreach ( $this->partitionQueues as $queue ) {
339 $queue->doDelete();
340 }
341 }
342
343 protected function doWaitForBackups() {
344 foreach ( $this->partitionQueues as $queue ) {
345 $queue->waitForBackups();
346 }
347 }
348
349 protected function doGetPeriodicTasks() {
350 $tasks = array();
351 foreach ( $this->partitionQueues as $partition => $queue ) {
352 foreach ( $queue->getPeriodicTasks() as $task => $def ) {
353 $tasks["{$partition}:{$task}"] = $def;
354 }
355 }
356 return $tasks;
357 }
358
359 protected function doFlushCaches() {
360 static $types = array(
361 'empty',
362 'size',
363 'acquiredcount',
364 'delayedcount',
365 'abandonedcount'
366 );
367 foreach ( $types as $type ) {
368 $this->cache->delete( $this->getCacheKey( $type ) );
369 }
370 foreach ( $this->partitionQueues as $queue ) {
371 $queue->doFlushCaches();
372 }
373 }
374
375 public function getAllQueuedJobs() {
376 $iterator = new AppendIterator();
377 foreach ( $this->partitionQueues as $queue ) {
378 $iterator->append( $queue->getAllQueuedJobs() );
379 }
380 return $iterator;
381 }
382
383 public function getAllDelayedJobs() {
384 $iterator = new AppendIterator();
385 foreach ( $this->partitionQueues as $queue ) {
386 $iterator->append( $queue->getAllDelayedJobs() );
387 }
388 return $iterator;
389 }
390
391 public function setTestingPrefix( $key ) {
392 foreach ( $this->partitionQueues as $queue ) {
393 $queue->setTestingPrefix( $key );
394 }
395 }
396
397 /**
398 * @return Array Map of (partition name => weight)
399 */
400 protected function getPartitionMap() {
401 $section = isset( $this->sectionsByWiki[$this->wiki] )
402 ? $this->sectionsByWiki[$this->wiki]
403 : 'default';
404 if ( !isset( $this->partitionsBySection[$section] ) ) {
405 throw new MWException( "No configuration for section '$section'." );
406 }
407 return $this->partitionsBySection[$section];
408 }
409
410 /**
411 * @return bool The queue is actually split up across multiple queue partitions
412 */
413 protected function isFederated() {
414 return ( count( $this->getPartitionMap() ) > 1 );
415 }
416
417 /**
418 * @return string
419 */
420 private function getCacheKey( $property ) {
421 list( $db, $prefix ) = wfSplitWikiID( $this->wiki );
422 return wfForeignMemcKey( $db, $prefix, 'jobqueue', $this->type, $property );
423 }
424 }