3 * Redis-backed job queue code.
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.
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.
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
21 * @author Aaron Schulz
25 * Class to handle job queues stored in Redis
27 * This is faster, less resource intensive, queue that JobQueueDB.
28 * All data for a queue using this class is placed into one redis server.
30 * There are seven main redis keys used to track jobs:
31 * - l-unclaimed : A list of job IDs used for push/pop
32 * - z-claimed : A sorted set of (job ID, UNIX timestamp as score) used for job retries
33 * - z-abandoned : A sorted set of (job ID, UNIX timestamp as score) used for broken jobs
34 * - h-idBySha1 : A hash of (SHA1 => job ID) for unclaimed jobs used for de-duplication
35 * - h-sha1Byid : A hash of (job ID => SHA1) for unclaimed jobs used for de-duplication
36 * - h-attempts : A hash of (job ID => attempt count) used for job claiming/retries
37 * - h-data : A hash of (job ID => serialized blobs) for job storage
38 * Any given job ID can be in only one of l-unclaimed, z-claimed, and z-abandoned.
39 * If an ID appears in any of those lists, it should have a h-data entry for its ID.
40 * If a job has a non-empty SHA1 de-duplication value and its ID is in l-unclaimed,
41 * then there should be no other such jobs. Every h-idBySha1 entry has an h-sha1Byid
42 * entry and every h-sha1Byid must refer to an ID that is l-unclaimed. If a job has its
43 * ID in z-claimed or z-abandoned, then it must also have an h-attempts entry for its ID.
45 * Additionally, "rootjob:* keys to track "root jobs" used for additional de-duplication.
46 * Aside from root job keys, all keys have no expiry, and are only removed when jobs are run.
47 * All the keys are prefixed with the relevant wiki ID information.
49 * This class requires Redis 2.6 as it makes use Lua scripts for fast atomic operations.
50 * Additionally, it should be noted that redis has different persistence modes, such
51 * as rdb snapshots, journaling, and no persistent. Appropriate configuration should be
52 * made on the servers based on what queues are using it and what tolerance they have.
58 class JobQueueRedis
extends JobQueue
{
59 /** @var RedisConnectionPool */
62 protected $server; // string; server address
64 const MAX_AGE_PRUNE
= 604800; // integer; seconds a job can live once claimed (7 days)
66 protected $key; // string; key to prefix the queue keys with (used for testing)
70 * - redisConfig : An array of parameters to RedisConnectionPool::__construct().
71 * Note that the serializer option is ignored "none" is always used.
72 * - redisServer : A hostname/port combination or the absolute path of a UNIX socket.
73 * If a hostname is specified but no port, the standard port number
74 * 6379 will be used. Required.
75 * @param array $params
77 public function __construct( array $params ) {
78 parent
::__construct( $params );
79 $params['redisConfig']['serializer'] = 'none'; // make it easy to use Lua
80 $this->server
= $params['redisServer'];
81 $this->redisPool
= RedisConnectionPool
::singleton( $params['redisConfig'] );
84 protected function supportedOrders() {
85 return array( 'timestamp', 'fifo' );
88 protected function optimalOrder() {
93 * @see JobQueue::doIsEmpty()
97 protected function doIsEmpty() {
98 return $this->doGetSize() == 0;
102 * @see JobQueue::doGetSize()
104 * @throws MWException
106 protected function doGetSize() {
107 $conn = $this->getConnection();
109 return $conn->lSize( $this->getQueueKey( 'l-unclaimed' ) );
110 } catch ( RedisException
$e ) {
111 $this->throwRedisException( $this->server
, $conn, $e );
116 * @see JobQueue::doGetAcquiredCount()
118 * @throws MWException
120 protected function doGetAcquiredCount() {
121 if ( $this->claimTTL
<= 0 ) {
122 return 0; // no acknowledgements
124 $conn = $this->getConnection();
126 $conn->multi( Redis
::PIPELINE
);
127 $conn->zSize( $this->getQueueKey( 'z-claimed' ) );
128 $conn->zSize( $this->getQueueKey( 'z-abandoned' ) );
129 return array_sum( $conn->exec() );
130 } catch ( RedisException
$e ) {
131 $this->throwRedisException( $this->server
, $conn, $e );
136 * @see JobQueue::doBatchPush()
140 * @throws MWException
142 protected function doBatchPush( array $jobs, $flags ) {
143 // Convert the jobs into field maps (de-duplicated against each other)
144 $items = array(); // (job ID => job fields map)
145 foreach ( $jobs as $job ) {
146 $item = $this->getNewJobFields( $job );
147 if ( strlen( $item['sha1'] ) ) { // hash identifier => de-duplicate
148 $items[$item['sha1']] = $item;
150 $items[$item['uuid']] = $item;
153 // Convert the field maps into serialized blobs
155 foreach ( $items as $item ) {
156 $tuples[] = array( $item['uuid'], $item['sha1'], serialize( $item ) );
159 if ( !count( $tuples ) ) {
160 return true; // nothing to do
163 $conn = $this->getConnection();
165 // Actually push the non-duplicate jobs into the queue...
166 if ( $flags & self
::QoS_Atomic
) {
167 $batches = array( $tuples ); // all or nothing
169 $batches = array_chunk( $tuples, 500 ); // avoid tying up the server
173 foreach ( $batches as $tupleBatch ) {
174 $added = $this->pushBlobs( $conn, $tupleBatch );
175 if ( is_int( $added ) ) {
178 $failed +
= count( $tupleBatch );
182 wfDebugLog( 'JobQueueRedis', "Could not insert {$failed} {$this->type} job(s)." );
185 wfIncrStats( 'job-insert', count( $tuples ) );
186 wfIncrStats( 'job-insert-duplicate', count( $tuples ) - $failed - $pushed );
187 } catch ( RedisException
$e ) {
188 $this->throwRedisException( $this->server
, $conn, $e );
195 * @param RedisConnRef $conn
196 * @param array $tuples List of tuples of (job ID, job SHA1 or '', serialized blob)
197 * @return integer Number of jobs inserted (duplicates are ignored)
198 * @throws RedisException
200 protected function pushBlobs( RedisConnRef
$conn, array $tuples ) {
201 $args = array(); // ([id, sha1, blob [, id, sha1, blob ... ] ] )
202 foreach ( $tuples as $tuple ) {
203 $args[] = $tuple[0]; // id
204 $args[] = $tuple[1]; // sha1
205 $args[] = $tuple[2]; // blob
209 if #ARGV % 3 ~= 0 then return redis.error_reply('Unmatched arguments') end
212 local id,sha1,blob = ARGV[i],ARGV[i+1],ARGV[i+2]
213 if sha1 == '' or redis.call('hExists',KEYS[3],sha1) == 0 then
214 redis.call('lPush',KEYS[1],id)
216 redis.call('hSet',KEYS[2],id,sha1)
217 redis.call('hSet',KEYS[3],sha1,id)
219 redis.call('hSet',KEYS[4],id,blob)
225 return $this->redisEval( $conn, $script,
228 $this->getQueueKey( 'l-unclaimed' ), # KEYS[1]
229 $this->getQueueKey( 'h-sha1ById' ), # KEYS[2]
230 $this->getQueueKey( 'h-idBySha1' ), # KEYS[3]
231 $this->getQueueKey( 'h-data' ), # KEYS[4]
235 4 # number of first argument(s) that are keys
240 * @see JobQueue::doPop()
242 * @throws MWException
244 protected function doPop() {
247 $conn = $this->getConnection();
250 if ( $this->claimTTL
> 0 ) {
251 // Keep the claimed job list down for high-traffic queues
252 if ( mt_rand( 0, 99 ) == 0 ) {
253 $this->recycleAndDeleteStaleJobs();
255 $blob = $this->popAndAcquireBlob( $conn );
257 $blob = $this->popAndDeleteBlob( $conn );
259 if ( $blob === false ) {
260 break; // no jobs; nothing to do
263 wfIncrStats( 'job-pop' );
264 $item = unserialize( $blob );
265 if ( $item === false ) {
266 wfDebugLog( 'JobQueueRedis', "Could not unserialize {$this->type} job." );
270 // If $item is invalid, recycleAndDeleteStaleJobs() will cleanup as needed
271 $job = $this->getJobFromFields( $item ); // may be false
272 } while ( !$job ); // job may be false if invalid
273 } catch ( RedisException
$e ) {
274 $this->throwRedisException( $this->server
, $conn, $e );
281 * @param RedisConnRef $conn
282 * @return array serialized string or false
283 * @throws RedisException
285 protected function popAndDeleteBlob( RedisConnRef
$conn ) {
288 -- Pop an item off the queue
289 local id = redis.call('rpop',KEYS[1])
290 if not id then return false end
291 -- Get the job data and remove it
292 local item = redis.call('hGet',KEYS[4],id)
293 redis.call('hDel',KEYS[4],id)
294 -- Allow new duplicates of this job
295 local sha1 = redis.call('hGet',KEYS[2],id)
296 if sha1 then redis.call('hDel',KEYS[3],sha1) end
297 redis.call('hDel',KEYS[2],id)
298 -- Return the job data
301 return $this->redisEval( $conn, $script,
303 $this->getQueueKey( 'l-unclaimed' ), # KEYS[1]
304 $this->getQueueKey( 'h-sha1ById' ), # KEYS[2]
305 $this->getQueueKey( 'h-idBySha1' ), # KEYS[3]
306 $this->getQueueKey( 'h-data' ), # KEYS[4]
308 4 # number of first argument(s) that are keys
313 * @param RedisConnRef $conn
314 * @return array serialized string or false
315 * @throws RedisException
317 protected function popAndAcquireBlob( RedisConnRef
$conn ) {
320 -- Pop an item off the queue
321 local id = redis.call('rPop',KEYS[1])
322 if not id then return false end
323 -- Allow new duplicates of this job
324 local sha1 = redis.call('hGet',KEYS[2],id)
325 if sha1 then redis.call('hDel',KEYS[3],sha1) end
326 redis.call('hDel',KEYS[2],id)
327 -- Mark the jobs as claimed and return it
328 redis.call('zAdd',KEYS[4],ARGV[1],id)
329 redis.call('hIncrBy',KEYS[5],id,1)
330 return redis.call('hGet',KEYS[6],id)
332 return $this->redisEval( $conn, $script,
334 $this->getQueueKey( 'l-unclaimed' ), # KEYS[1]
335 $this->getQueueKey( 'h-sha1ById' ), # KEYS[2]
336 $this->getQueueKey( 'h-idBySha1' ), # KEYS[3]
337 $this->getQueueKey( 'z-claimed' ), # KEYS[4]
338 $this->getQueueKey( 'h-attempts' ), # KEYS[5]
339 $this->getQueueKey( 'h-data' ), # KEYS[6]
340 time(), # ARGV[1] (injected to be replication-safe)
342 6 # number of first argument(s) that are keys
347 * @see JobQueue::doAck()
350 * @throws MWException
352 protected function doAck( Job
$job ) {
353 if ( $this->claimTTL
> 0 ) {
354 $conn = $this->getConnection();
356 // Get the exact field map this Job came from, regardless of whether
357 // the job was transformed into a DuplicateJob or anything of the sort.
358 $item = $job->metadata
['sourceFields'];
362 -- Unmark the job as claimed
363 redis.call('zRem',KEYS[1],ARGV[1])
364 redis.call('hDel',KEYS[2],ARGV[1])
365 -- Delete the job data itself
366 return redis.call('hDel',KEYS[3],ARGV[1])
368 $res = $this->redisEval( $conn, $script,
370 $this->getQueueKey( 'z-claimed' ), # KEYS[1]
371 $this->getQueueKey( 'h-attempts' ), # KEYS[2]
372 $this->getQueueKey( 'h-data' ), # KEYS[3]
373 $item['uuid'] # ARGV[1]
375 3 # number of first argument(s) that are keys
379 wfDebugLog( 'JobQueueRedis', "Could not acknowledge {$this->type} job." );
382 } catch ( RedisException
$e ) {
383 $this->throwRedisException( $this->server
, $conn, $e );
390 * @see JobQueue::doDeduplicateRootJob()
393 * @throws MWException
395 protected function doDeduplicateRootJob( Job
$job ) {
396 $params = $job->getParams();
397 if ( !isset( $params['rootJobSignature'] ) ) {
398 throw new MWException( "Cannot register root job; missing 'rootJobSignature'." );
399 } elseif ( !isset( $params['rootJobTimestamp'] ) ) {
400 throw new MWException( "Cannot register root job; missing 'rootJobTimestamp'." );
402 $key = $this->getRootJobCacheKey( $params['rootJobSignature'] );
404 $conn = $this->getConnection();
406 $timestamp = $conn->get( $key ); // current last timestamp of this job
407 if ( $timestamp && $timestamp >= $params['rootJobTimestamp'] ) {
408 return true; // a newer version of this root job was enqueued
410 // Update the timestamp of the last root job started at the location...
411 return $conn->set( $key, $params['rootJobTimestamp'], self
::ROOTJOB_TTL
); // 2 weeks
412 } catch ( RedisException
$e ) {
413 $this->throwRedisException( $this->server
, $conn, $e );
418 * @see JobQueue::doIsRootJobOldDuplicate()
422 protected function doIsRootJobOldDuplicate( Job
$job ) {
423 $params = $job->getParams();
424 if ( !isset( $params['rootJobSignature'] ) ) {
425 return false; // job has no de-deplication info
426 } elseif ( !isset( $params['rootJobTimestamp'] ) ) {
427 wfDebugLog( 'JobQueueRedis', "Cannot check root job; missing 'rootJobTimestamp'." );
431 $conn = $this->getConnection();
433 // Get the last time this root job was enqueued
434 $timestamp = $conn->get( $this->getRootJobCacheKey( $params['rootJobSignature'] ) );
435 } catch ( RedisException
$e ) {
436 $this->throwRedisException( $this->server
, $conn, $e );
439 // Check if a new root job was started at the location after this one's...
440 return ( $timestamp && $timestamp > $params['rootJobTimestamp'] );
444 * @see JobQueue::getAllQueuedJobs()
447 public function getAllQueuedJobs() {
448 $conn = $this->getConnection();
450 throw new MWException( "Unable to connect to redis server." );
454 return new MappedIterator(
455 $conn->lRange( $this->getQueueKey( 'l-unclaimed' ), 0, -1 ),
456 function( $uid ) use ( $that, $conn ) {
457 return $that->getJobFromUidInternal( $uid, $conn );
460 } catch ( RedisException
$e ) {
461 $this->throwRedisException( $this->server
, $conn, $e );
466 * This function should not be called outside RedisJobQueue
469 * @param $conn RedisConnRef
471 * @throws MWException
473 public function getJobFromUidInternal( $uid, RedisConnRef
$conn ) {
475 $item = unserialize( $conn->hGet( $this->getQueueKey( 'h-data' ), $uid ) );
476 if ( !is_array( $item ) ) { // this shouldn't happen
477 throw new MWException( "Could not find job with ID '$uid'." );
479 $title = Title
::makeTitle( $item['namespace'], $item['title'] );
480 $job = Job
::factory( $item['type'], $title, $item['params'] );
481 $job->metadata
['sourceFields'] = $item;
483 } catch ( RedisException
$e ) {
484 $this->throwRedisException( $this->server
, $conn, $e );
489 * Recycle or destroy any jobs that have been claimed for too long
491 * @return integer Number of jobs recycled/deleted
492 * @throws MWException
494 public function recycleAndDeleteStaleJobs() {
495 if ( $this->claimTTL
<= 0 ) { // sanity
496 throw new MWException( "Cannot recycle jobs since acknowledgements are disabled." );
499 // For each job item that can be retried, we need to add it back to the
500 // main queue and remove it from the list of currenty claimed job items.
501 // For those that cannot, they are marked as dead and kept around for
502 // investigation and manual job restoration but are eventually deleted.
503 $conn = $this->getConnection();
508 local released,abandoned,pruned = 0,0,0
509 -- Get all non-dead jobs that have an expired claim on them.
510 -- The score for each item is the last claim timestamp (UNIX).
511 local staleClaims = redis.call('zRangeByScore',KEYS[1],0,ARGV[1],'WITHSCORES')
512 for id,timestamp in ipairs(staleClaims) do
513 local attempts = redis.call('hGet',KEYS[2],id)
514 if attempts < ARGV[3] then
515 -- Claim expired and retries left: re-enqueue the job
516 redis.call('lPush',KEYS[3],id)
517 redis.call('hIncrBy',KEYS[2],id,1)
518 released = released + 1
520 -- Claim expired and no retries left: mark the job as dead
521 redis.call('zAdd',KEYS[5],timestamp,id)
522 abandoned = abandoned + 1
524 redis.call('zRem',KEYS[1],id)
526 -- Get all of the dead jobs that have been marked as dead for too long.
527 -- The score for each item is the last claim timestamp (UNIX).
528 local deadClaims = redis.call('zRangeByScore',KEYS[5],0,ARGV[2],'WITHSCORES')
529 for id,timestamp in ipairs(deadClaims) do
530 -- Stale and out of retries: remove any traces of the job
531 redis.call('zRem',KEYS[5],id)
532 redis.call('hDel',KEYS[2],id)
533 redis.call('hDel',KEYS[4],id)
536 return {released,abandoned,pruned}
538 $res = $this->redisEval( $conn, $script,
540 $this->getQueueKey( 'z-claimed' ), # KEYS[1]
541 $this->getQueueKey( 'h-attempts' ), # KEYS[2]
542 $this->getQueueKey( 'l-unclaimed' ), # KEYS[3]
543 $this->getQueueKey( 'h-data' ), # KEYS[4]
544 $this->getQueueKey( 'z-abandoned' ), # KEYS[5]
545 $now - $this->claimTTL
, # ARGV[1]
546 $now - self
::MAX_AGE_PRUNE
, # ARGV[2]
547 $this->maxTries
# ARGV[3]
549 5 # number of first argument(s) that are keys
552 list( $released, $abandoned, $pruned ) = $res;
553 $count +
= $released +
$pruned;
554 wfIncrStats( 'job-recycle', count( $released ) );
556 } catch ( RedisException
$e ) {
557 $this->throwRedisException( $this->server
, $conn, $e );
566 protected function doGetPeriodicTasks() {
567 if ( $this->claimTTL
> 0 ) {
569 'recycleAndDeleteStaleJobs' => array(
570 'callback' => array( $this, 'recycleAndDeleteStaleJobs' ),
571 'period' => ceil( $this->claimTTL
/ 2 )
580 * @param RedisConnRef $conn
581 * @param string $script
582 * @param array $params
583 * @param integer $numKeys
586 protected function redisEval( RedisConnRef
$conn, $script, array $params, $numKeys ) {
587 $res = $conn->evalSha( sha1( $script ), $params, $numKeys );
588 if ( $res === false && $conn->getLastError() != '' ) { // not in script cache?
589 wfDebugLog( 'JobQueueRedis', "Lua script error: " . $conn->getLastError() );
590 $res = $conn->eval( $script, $params, $numKeys );
599 protected function getNewJobFields( Job
$job ) {
601 // Fields that describe the nature of the job
602 'type' => $job->getType(),
603 'namespace' => $job->getTitle()->getNamespace(),
604 'title' => $job->getTitle()->getDBkey(),
605 'params' => $job->getParams(),
606 // Additional job metadata
607 'uuid' => UIDGenerator
::newRawUUIDv4( UIDGenerator
::QUICK_RAND
),
608 'sha1' => $job->ignoreDuplicates()
609 ?
wfBaseConvert( sha1( serialize( $job->getDeduplicationInfo() ) ), 16, 36, 31 )
611 'timestamp' => time() // UNIX timestamp
616 * @param $fields array
619 protected function getJobFromFields( array $fields ) {
620 $title = Title
::makeTitleSafe( $fields['namespace'], $fields['title'] );
622 $job = Job
::factory( $fields['type'], $title, $fields['params'] );
623 $job->metadata
['sourceFields'] = $fields;
630 * Get a connection to the server that handles all sub-queues for this queue
632 * @return Array (server name, Redis instance)
633 * @throws MWException
635 protected function getConnection() {
636 $conn = $this->redisPool
->getConnection( $this->server
);
638 throw new MWException( "Unable to connect to redis server." );
644 * @param $server string
645 * @param $conn RedisConnRef
646 * @param $e RedisException
647 * @throws MWException
649 protected function throwRedisException( $server, RedisConnRef
$conn, $e ) {
650 $this->redisPool
->handleException( $server, $conn, $e );
651 throw new MWException( "Redis server error: {$e->getMessage()}\n" );
655 * @param $prop string
658 private function getQueueKey( $prop ) {
659 list( $db, $prefix ) = wfSplitWikiID( $this->wiki
);
660 if ( strlen( $this->key
) ) { // namespaced queue (for testing)
661 return wfForeignMemcKey( $db, $prefix, 'jobqueue', $this->type
, $this->key
, $prop );
663 return wfForeignMemcKey( $db, $prefix, 'jobqueue', $this->type
, $prop );
671 public function setTestingPrefix( $key ) {