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
30 class JobQueueRedis
extends JobQueue
{
31 /** @var RedisConnectionPool */
34 protected $server; // string; server address
36 const ROOTJOB_TTL
= 1209600; // integer; seconds to remember root jobs (14 days)
37 const MAX_AGE_PRUNE
= 604800; // integer; seconds a job can live once claimed (7 days)
39 protected $key; // string; key to prefix the queue keys with (used for testing)
43 * - redisConfig : An array of parameters to RedisConnectionPool::__construct().
44 * - redisServer : A hostname/port combination or the absolute path of a UNIX socket.
45 * If a hostname is specified but no port, the standard port number
46 * 6379 will be used. Required.
47 * @param array $params
49 public function __construct( array $params ) {
50 parent
::__construct( $params );
51 $this->server
= $params['redisServer'];
52 $this->redisPool
= RedisConnectionPool
::singleton( $params['redisConfig'] );
56 * @see JobQueue::doIsEmpty()
60 protected function doIsEmpty() {
61 $conn = $this->getConnection();
63 return ( $conn->lSize( $this->getQueueKey( 'l-unclaimed' ) ) == 0 );
64 } catch ( RedisException
$e ) {
65 $this->throwRedisException( $this->server
, $conn, $e );
70 * @see JobQueue::doGetSize()
74 protected function doGetSize() {
75 $conn = $this->getConnection();
77 return $conn->lSize( $this->getQueueKey( 'l-unclaimed' ) );
78 } catch ( RedisException
$e ) {
79 $this->throwRedisException( $this->server
, $conn, $e );
84 * @see JobQueue::doGetAcquiredCount()
88 protected function doGetAcquiredCount() {
89 if ( $this->claimTTL
<= 0 ) {
90 return 0; // no acknowledgements
92 $conn = $this->getConnection();
94 return $conn->lSize( $this->getQueueKey( 'l-claimed' ) );
95 } catch ( RedisException
$e ) {
96 $this->throwRedisException( $this->server
, $conn, $e );
101 * @see JobQueue::doBatchPush()
105 * @throws MWException
107 protected function doBatchPush( array $jobs, $flags ) {
108 if ( !count( $jobs ) ) {
112 // Convert the jobs into a list of field maps
113 $items = array(); // (uid => job fields map)
114 foreach ( $jobs as $job ) {
115 $item = $this->getNewJobFields( $job );
116 $items[$item['uid']] = $item;
119 $dedupUids = array(); // list of uids to check for duplicates
120 foreach ( $items as $item ) {
121 if ( $this->isHashUid( $item['uid'] ) ) { // hash identifier => de-duplicate
122 $dedupUids[] = $item['uid'];
126 $conn = $this->getConnection();
128 // Find which of these jobs are duplicates of unclaimed jobs in the queue...
129 if ( count( $dedupUids ) ) {
130 $conn->multi( Redis
::PIPELINE
);
131 foreach ( $dedupUids as $uid ) { // check if job data exists
132 $conn->exists( $this->prefixWithQueueKey( 'data', $uid ) );
134 if ( $this->claimTTL
> 0 ) { // check which jobs were claimed
135 foreach ( $dedupUids as $uid ) {
136 $conn->hExists( $this->prefixWithQueueKey( 'h-meta', $uid ), 'ctime' );
138 list( $exists, $claimed ) = array_chunk( $conn->exec(), count( $dedupUids ) );
140 $exists = $conn->exec();
141 $claimed = array(); // no claim system
143 // Remove the duplicate jobs to cut down on pushing duplicate uids...
144 foreach ( $dedupUids as $k => $uid ) {
145 if ( $exists[$k] && empty( $claimed[$k] ) ) {
146 unset( $items[$uid] );
150 // Actually push the non-duplicate jobs into the queue...
151 if ( count( $items ) ) {
152 $uids = array_keys( $items );
153 $conn->multi( Redis
::MULTI
); // begin (atomic trx)
154 $conn->mSet( $this->prefixKeysWithQueueKey( 'data', $items ) );
155 call_user_func_array(
156 array( $conn, 'lPush' ),
157 array_merge( array( $this->getQueueKey( 'l-unclaimed' ) ), $uids )
159 $res = $conn->exec(); // commit (atomic trx)
160 if ( in_array( false, $res, true ) ) {
161 wfDebugLog( 'JobQueueRedis', "Could not insert {$this->type} job(s)." );
165 wfIncrStats( 'job-insert', count( $items ) );
166 wfIncrStats( 'job-insert-duplicate', count( $jobs ) - count( $items ) );
167 } catch ( RedisException
$e ) {
168 $this->throwRedisException( $this->server
, $conn, $e );
175 * @see JobQueue::doPop()
177 * @throws MWException
179 protected function doPop() {
182 if ( $this->claimTTL
<= 0 && mt_rand( 0, 99 ) == 0 ) {
183 $this->cleanupClaimedJobs(); // prune jobs and IDs from the "garbage" list
186 $conn = $this->getConnection();
189 // Atomically pop an item off the queue and onto the "claimed" list
190 $uid = $conn->rpoplpush(
191 $this->getQueueKey( 'l-unclaimed' ),
192 $this->getQueueKey( 'l-claimed' )
194 if ( $uid === false ) {
195 break; // no jobs; nothing to do
198 wfIncrStats( 'job-pop' );
199 $conn->multi( Redis
::PIPELINE
);
200 $conn->get( $this->prefixWithQueueKey( 'data', $uid ) );
201 if ( $this->claimTTL
> 0 ) {
202 // Set the claim timestamp metadata. If this step fails, then
203 // the timestamp will be assumed to be the current timestamp by
204 // recycleAndDeleteStaleJobs() as of the next time that it runs.
205 // If two runners claim duplicate jobs, one will abort here.
206 $conn->hSetNx( $this->prefixWithQueueKey( 'h-meta', $uid ), 'ctime', time() );
208 // If this fails, the message key will be deleted in cleanupClaimedJobs().
209 // If two runners claim duplicate jobs, one of them will abort here.
211 $this->prefixWithQueueKey( 'h-meta', $uid ),
212 $this->prefixWithQueueKey( 'data', $uid ) );
214 list( $item, $ok ) = $conn->exec();
215 if ( $item === false ||
( $this->claimTTL
&& !$ok ) ) {
216 wfDebug( "Could not find or delete job $uid; probably was a duplicate." );
217 continue; // job was probably a duplicate
220 // If $item is invalid, recycleAndDeleteStaleJobs() will cleanup as needed
221 $job = $this->getJobFromFields( $item ); // may be false
222 } while ( !$job ); // job may be false if invalid
223 } catch ( RedisException
$e ) {
224 $this->throwRedisException( $this->server
, $conn, $e );
227 // Flag this job as an old duplicate based on its "root" job...
229 if ( $job && $this->isRootJobOldDuplicate( $job ) ) {
230 wfIncrStats( 'job-pop-duplicate' );
231 return DuplicateJob
::newFromJob( $job ); // convert to a no-op
233 } catch ( MWException
$e ) {} // don't lose jobs over this
239 * @see JobQueue::doAck()
242 * @throws MWException
244 protected function doAck( Job
$job ) {
245 if ( $this->claimTTL
> 0 ) {
246 $conn = $this->getConnection();
248 // Get the exact field map this Job came from, regardless of whether
249 // the job was transformed into a DuplicateJob or anything of the sort.
250 $item = $job->metadata
['sourceFields'];
252 $conn->multi( Redis
::MULTI
); // begin (atomic trx)
253 // Remove the first instance of this job scanning right-to-left.
254 // This is O(N) in the worst case, but is likely to be much faster since
255 // jobs are pushed to the left and we are starting from the right, where
256 // the longest running jobs are likely to be. These should be the first
257 // jobs to be acknowledged assuming that job run times are roughly equal.
258 $conn->lRem( $this->getQueueKey( 'l-claimed' ), $item['uid'], -1 );
259 // Delete the job data and its claim metadata
261 $this->prefixWithQueueKey( 'h-meta', $item['uid'] ),
262 $this->prefixWithQueueKey( 'data', $item['uid'] ) );
263 $res = $conn->exec(); // commit (atomic trx)
265 if ( in_array( false, $res, true ) ) {
266 wfDebugLog( 'JobQueueRedis', "Could not acknowledge {$this->type} job." );
269 } catch ( RedisException
$e ) {
270 $this->throwRedisException( $this->server
, $conn, $e );
277 * @see JobQueue::doDeduplicateRootJob()
280 * @throws MWException
282 protected function doDeduplicateRootJob( Job
$job ) {
283 $params = $job->getParams();
284 if ( !isset( $params['rootJobSignature'] ) ) {
285 throw new MWException( "Cannot register root job; missing 'rootJobSignature'." );
286 } elseif ( !isset( $params['rootJobTimestamp'] ) ) {
287 throw new MWException( "Cannot register root job; missing 'rootJobTimestamp'." );
289 $key = $this->getRootJobKey( $params['rootJobSignature'] );
291 $conn = $this->getConnection();
293 $timestamp = $conn->get( $key ); // current last timestamp of this job
294 if ( $timestamp && $timestamp >= $params['rootJobTimestamp'] ) {
295 return true; // a newer version of this root job was enqueued
297 // Update the timestamp of the last root job started at the location...
298 return $conn->set( $key, $params['rootJobTimestamp'], self
::ROOTJOB_TTL
); // 2 weeks
299 } catch ( RedisException
$e ) {
300 $this->throwRedisException( $this->server
, $conn, $e );
305 * Check if the "root" job of a given job has been superseded by a newer one
309 * @throws MWException
311 protected function isRootJobOldDuplicate( Job
$job ) {
312 $params = $job->getParams();
313 if ( !isset( $params['rootJobSignature'] ) ) {
314 return false; // job has no de-deplication info
315 } elseif ( !isset( $params['rootJobTimestamp'] ) ) {
316 wfDebugLog( 'JobQueueRedis', "Cannot check root job; missing 'rootJobTimestamp'." );
320 $conn = $this->getConnection();
322 // Get the last time this root job was enqueued
323 $timestamp = $conn->get( $this->getRootJobKey( $params['rootJobSignature'] ) );
324 } catch ( RedisException
$e ) {
325 $this->throwRedisException( $this->server
, $conn, $e );
328 // Check if a new root job was started at the location after this one's...
329 return ( $timestamp && $timestamp > $params['rootJobTimestamp'] );
333 * Recycle or destroy any jobs that have been claimed for too long
335 * @return integer Number of jobs recycled/deleted
336 * @throws MWException
338 public function recycleAndDeleteStaleJobs() {
339 if ( $this->claimTTL
<= 0 ) { // sanity
340 throw new MWException( "Cannot recycle jobs since acknowledgements are disabled." );
343 // For each job item that can be retried, we need to add it back to the
344 // main queue and remove it from the list of currenty claimed job items.
345 $conn = $this->getConnection();
347 // Avoid duplicate insertions of items to be re-enqueued
348 $conn->multi( Redis
::MULTI
);
349 $conn->setnx( $this->getQueueKey( 'lock' ), 1 );
350 $conn->expire( $this->getQueueKey( 'lock' ), 3600 );
351 if ( $conn->exec() !== array( true, true ) ) { // lock
352 return $count; // already in progress
356 $claimCutoff = $now - $this->claimTTL
;
357 $pruneCutoff = $now - self
::MAX_AGE_PRUNE
;
359 // Get the list of all claimed jobs
360 $claimedUids = $conn->lRange( $this->getQueueKey( 'l-claimed' ), 0, -1 );
361 // Get a map of (uid => claim metadata) for all claimed jobs
362 $metadata = $conn->mGet( $this->prefixValuesWithQueueKey( 'h-meta', $claimedUids ) );
364 $uidsPush = array(); // items IDs to move to the "unclaimed" queue
365 $uidsRemove = array(); // item IDs to remove from "claimed" queue
366 foreach ( $claimedUids as $i => $uid ) { // all claimed items
367 $info = $metadata[$i] ?
$metadata[$i] : array();
368 if ( isset( $info['ctime'] ) ||
isset( $info['rctime'] ) ) {
369 // Prefer "ctime" (set by pop()) over "rctime" (set by this function)
370 $ctime = isset( $info['ctime'] ) ?
$info['ctime'] : $info['rctime'];
371 // Claimed job claimed for too long?
372 if ( $ctime < $claimCutoff ) {
373 // Get the number of failed attempts
374 $attempts = isset( $info['attempts'] ) ?
$info['attempts'] : 0;
375 if ( $attempts < $this->maxTries
) {
376 $uidsPush[] = $uid; // retry it
377 } elseif ( $ctime < $pruneCutoff ) {
378 $uidsRemove[] = $uid; // just remove it
382 // If pop() failed to set the claim timestamp, set it to the current time.
383 // Since that function sets this non-atomically *after* moving the job to
384 // the "claimed" queue, it may be the case that it just didn't set it yet.
385 $conn->hSet( $this->prefixWithQueueKey( 'h-meta', $uid ), 'rctime', $now );
389 $conn->multi( Redis
::MULTI
); // begin (atomic trx)
390 if ( count( $uidsPush ) ) { // move from "l-claimed" to "l-unclaimed"
391 call_user_func_array(
392 array( $conn, 'lPush' ),
393 array_merge( array( $this->getQueueKey( 'l-unclaimed' ) ), $uidsPush )
395 foreach ( $uidsPush as $uid ) {
396 $conn->lRem( $this->getQueueKey( 'l-claimed' ), $uid, -1 );
397 $conn->hDel( $this->prefixWithQueueKey( 'h-meta', $uid ), 'ctime', 'rctime' );
398 $conn->hIncrBy( $this->prefixWithQueueKey( 'h-meta', $uid ), 'attempts', 1 );
401 foreach ( $uidsRemove as $uid ) { // remove from "l-claimed"
402 $conn->lRem( $this->getQueueKey( 'l-claimed' ), $uid, -1 );
403 $conn->delete( // delete job data and metadata
404 $this->prefixWithQueueKey( 'h-meta', $uid ),
405 $this->prefixWithQueueKey( 'data', $uid ) );
407 $res = $conn->exec(); // commit (atomic trx)
409 if ( in_array( false, $res, true ) ) {
410 wfDebugLog( 'JobQueueRedis', "Could not recycle {$this->type} job(s)." );
412 $count +
= ( count( $uidsPush ) +
count( $uidsRemove ) );
413 wfIncrStats( 'job-recycle', count( $uidsPush ) );
416 $conn->delete( $this->getQueueKey( 'lock' ) ); // unlock
417 } catch ( RedisException
$e ) {
418 $this->throwRedisException( $this->server
, $conn, $e );
425 * Destroy any jobs that have been claimed
427 * @return integer Number of jobs deleted
428 * @throws MWException
430 protected function cleanupClaimedJobs() {
432 // Make sure the message for claimed jobs was deleted
433 // and remove the claimed job IDs from the "claimed" list.
434 $conn = $this->getConnection();
436 // Avoid races and duplicate effort
437 $conn->multi( Redis
::MULTI
);
438 $conn->setnx( $this->getQueueKey( 'lock' ), 1 );
439 $conn->expire( $this->getQueueKey( 'lock' ), 3600 );
440 if ( $conn->exec() !== array( true, true ) ) { // lock
441 return $count; // already in progress
443 // Get the list of all claimed jobs
444 $uids = $conn->lRange( $this->getQueueKey( 'l-claimed' ), 0, -1 );
445 if ( count( $uids ) ) {
446 // Delete the message keys and delist the corresponding ids.
447 // Since the only other changes to "l-claimed" are left pushes, we can just strip
448 // off the elements read here using a right trim based on the number of ids read.
449 $conn->multi( Redis
::MULTI
); // begin (atomic trx)
450 $conn->lTrim( $this->getQueueKey( 'l-claimed' ), 0, -count( $uids ) - 1 );
451 $conn->delete( array_merge(
452 $this->prefixValuesWithQueueKey( 'h-meta', $uids ),
453 $this->prefixValuesWithQueueKey( 'data', $uids )
455 $res = $conn->exec(); // commit (atomic trx)
457 if ( in_array( false, $res, true ) ) {
458 wfDebugLog( 'JobQueueRedis', "Could not purge {$this->type} job(s)." );
460 $count +
= count( $uids );
463 $conn->delete( $this->getQueueKey( 'lock' ) ); // unlock
464 } catch ( RedisException
$e ) {
465 $this->throwRedisException( $this->server
, $conn, $e );
474 protected function doGetPeriodicTasks() {
475 if ( $this->claimTTL
> 0 ) {
477 'recycleAndDeleteStaleJobs' => array(
478 'callback' => array( $this, 'recycleAndDeleteStaleJobs' ),
479 'period' => ceil( $this->claimTTL
/ 2 )
491 protected function getNewJobFields( Job
$job ) {
493 // Fields that describe the nature of the job
494 'type' => $job->getType(),
495 'namespace' => $job->getTitle()->getNamespace(),
496 'title' => $job->getTitle()->getDBkey(),
497 'params' => $job->getParams(),
498 // Additional metadata
499 'uid' => $job->ignoreDuplicates()
500 ?
wfBaseConvert( sha1( serialize( $job->getDeduplicationInfo() ) ), 16, 36, 31 )
501 : wfRandomString( 32 ),
502 'timestamp' => time() // UNIX timestamp
507 * @param $fields array
510 protected function getJobFromFields( array $fields ) {
511 $title = Title
::makeTitleSafe( $fields['namespace'], $fields['title'] );
513 $job = Job
::factory( $fields['type'], $title, $fields['params'] );
514 $job->metadata
['sourceFields'] = $fields;
521 * @param $uid string Job UID
522 * @return bool Whether $uid is a SHA-1 hash based identifier for de-duplication
524 protected function isHashUid( $uid ) {
525 return strlen( $uid ) == 31;
529 * Get a connection to the server that handles all sub-queues for this queue
531 * @return Array (server name, Redis instance)
532 * @throws MWException
534 protected function getConnection() {
535 $conn = $this->redisPool
->getConnection( $this->server
);
537 throw new MWException( "Unable to connect to redis server." );
543 * @param $server string
544 * @param $conn RedisConnRef
545 * @param $e RedisException
546 * @throws MWException
548 protected function throwRedisException( $server, RedisConnRef
$conn, $e ) {
549 $this->redisPool
->handleException( $server, $conn, $e );
550 throw new MWException( "Redis server error: {$e->getMessage()}\n" );
554 * @param $prop string
557 private function getQueueKey( $prop ) {
558 list( $db, $prefix ) = wfSplitWikiID( $this->wiki
);
559 if ( strlen( $this->key
) ) { // namespaced queue (for testing)
560 return wfForeignMemcKey( $db, $prefix, 'jobqueue', $this->type
, $this->key
, $prop );
562 return wfForeignMemcKey( $db, $prefix, 'jobqueue', $this->type
, $prop );
567 * @param string $signature Hash identifier of the root job
570 private function getRootJobKey( $signature ) {
571 list( $db, $prefix ) = wfSplitWikiID( $this->wiki
);
572 return wfForeignMemcKey( $db, $prefix, 'jobqueue', $this->type
, 'rootjob', $signature );
576 * @param $prop string
577 * @param $string string
580 private function prefixWithQueueKey( $prop, $string ) {
581 return $this->getQueueKey( $prop ) . ':' . $string;
585 * @param $prop string
586 * @param $items array
589 private function prefixValuesWithQueueKey( $prop, array $items ) {
591 foreach ( $items as $item ) {
592 $res[] = $this->prefixWithQueueKey( $prop, $item );
598 * @param $prop string
599 * @param $items array
602 private function prefixKeysWithQueueKey( $prop, array $items ) {
604 foreach ( $items as $key => $item ) {
605 $res[$this->prefixWithQueueKey( $prop, $key )] = $item;
614 public function setTestingPrefix( $key ) {