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)
38 const MAX_ATTEMPTS
= 3; // integer; number of times to try a job
42 * - redisConf : An array of parameters to RedisConnectionPool::__construct().
43 * - server : A hostname/port combination or the absolute path of a UNIX socket.
44 * If a hostname is specified but no port, the standard port number
45 * 6379 will be used. Required.
46 * @param array $params
48 public function __construct( array $params ) {
49 parent
::__construct( $params );
50 $this->server
= $params['redisConf']['server'];
51 $this->redisPool
= RedisConnectionPool
::singleton( $params['redisConf'] );
55 * @see JobQueue::doIsEmpty()
59 protected function doIsEmpty() {
60 if ( mt_rand( 0, 99 ) == 0 ) {
61 $this->doInternalMaintenance();
64 $conn = $this->getConnection();
66 return ( $conn->lSize( $this->getQueueKey( 'l-unclaimed' ) ) == 0 );
67 } catch ( RedisException
$e ) {
68 $this->throwRedisException( $this->server
, $conn, $e );
73 * @see JobQueue::doGetSize()
77 protected function doGetSize() {
78 if ( mt_rand( 0, 99 ) == 0 ) {
79 $this->doInternalMaintenance();
82 $conn = $this->getConnection();
84 return $conn->lSize( $this->getQueueKey( 'l-unclaimed' ) );
85 } catch ( RedisException
$e ) {
86 $this->throwRedisException( $this->server
, $conn, $e );
91 * @see JobQueue::doGetAcquiredCount()
95 protected function doGetAcquiredCount() {
96 if ( mt_rand( 0, 99 ) == 0 ) {
97 $this->doInternalMaintenance();
100 $conn = $this->getConnection();
102 if ( $this->claimTTL
> 0 ) {
103 return $conn->lSize( $this->getQueueKey( 'l-claimed' ) );
107 } catch ( RedisException
$e ) {
108 $this->throwRedisException( $this->server
, $conn, $e );
113 * @see JobQueue::doBatchPush()
117 * @throws MWException
119 protected function doBatchPush( array $jobs, $flags ) {
120 if ( !count( $jobs ) ) {
124 // Convert the jobs into a list of field maps
125 $items = array(); // (uid => job fields map)
126 foreach ( $jobs as $job ) {
127 $item = $this->getNewJobFields( $job );
128 $items[$item['uid']] = $item;
131 $dedupUids = array(); // list of uids to check for duplicates
132 foreach ( $items as $item ) {
133 if ( $this->isHashUid( $item['uid'] ) ) { // hash identifier => de-duplicate
134 $dedupUids[] = $item['uid'];
138 $conn = $this->getConnection();
140 // Find which of these jobs are duplicates unclaimed jobs in the queue...
141 if ( count( $dedupUids ) ) {
142 $conn->multi( Redis
::PIPELINE
);
143 foreach ( $dedupUids as $uid ) { // check if job data exists
144 $conn->exists( $this->prefixWithQueueKey( 'data', $uid ) );
146 if ( $this->claimTTL
> 0 ) { // check which jobs were claimed
147 foreach ( $dedupUids as $uid ) {
148 $conn->hExists( $this->prefixWithQueueKey( 'h-meta', $uid ), 'ctime' );
150 list( $exists, $claimed ) = array_chunk( $conn->exec(), count( $dedupUids ) );
152 $exists = $conn->exec();
153 $claimed = array(); // no claim system
155 // Remove the duplicate jobs to cut down on pushing duplicate uids...
156 foreach ( $dedupUids as $k => $uid ) {
157 if ( $exists[$k] && empty( $claimed[$k] ) ) {
158 unset( $items[$uid] );
162 // Actually push the non-duplicate jobs into the queue...
163 if ( count( $items ) ) {
164 $uids = array_keys( $items );
165 $conn->multi( Redis
::MULTI
); // begin (atomic trx)
166 $conn->mSet( $this->prefixKeysWithQueueKey( 'data', $items ) );
167 call_user_func_array(
168 array( $conn, 'lPush' ),
169 array_merge( array( $this->getQueueKey( 'l-unclaimed' ) ), $uids )
171 $res = $conn->exec(); // commit (atomic trx)
172 if ( in_array( false, $res, true ) ) {
173 wfDebugLog( 'JobQueueRedis', "Could not insert {$this->type} job(s)." );
177 wfIncrStats( 'job-insert', count( $items ) );
178 wfIncrStats( 'job-insert-duplicate', count( $jobs ) - count( $items ) );
179 } catch ( RedisException
$e ) {
180 $this->throwRedisException( $this->server
, $conn, $e );
187 * @see JobQueue::doPop()
189 * @throws MWException
191 protected function doPop() {
194 if ( mt_rand( 0, 99 ) == 0 ) {
195 $this->doInternalMaintenance();
198 $conn = $this->getConnection();
201 // Atomically pop an item off the queue and onto the "claimed" list
202 $uid = $conn->rpoplpush(
203 $this->getQueueKey( 'l-unclaimed' ),
204 $this->getQueueKey( 'l-claimed' )
206 if ( $uid === false ) {
207 break; // no jobs; nothing to do
210 wfIncrStats( 'job-pop' );
211 $conn->multi( Redis
::PIPELINE
);
212 $conn->get( $this->prefixWithQueueKey( 'data', $uid ) );
213 if ( $this->claimTTL
> 0 ) {
214 // Set the claim timestamp metadata. If this step fails, then
215 // the timestamp will be assumed to be the current timestamp by
216 // recycleAndDeleteStaleJobs() as of the next time that it runs.
217 // If two runners claim duplicate jobs, one will abort here.
218 $conn->hSetNx( $this->prefixWithQueueKey( 'h-meta', $uid ), 'ctime', time() );
220 // If this fails, the message key will be deleted in cleanupClaimedJobs().
221 // If two runners claim duplicate jobs, one of them will abort here.
223 $this->prefixWithQueueKey( 'h-meta', $uid ),
224 $this->prefixWithQueueKey( 'data', $uid ) );
226 list( $item, $ok ) = $conn->exec();
227 if ( $item === false ||
( $this->claimTTL
&& !$ok ) ) {
228 wfDebug( "Could not find or delete job $uid; probably was a duplicate." );
229 continue; // job was probably a duplicate
232 // If $item is invalid, recycleAndDeleteStaleJobs() will cleanup as needed
233 $job = $this->getJobFromFields( $item ); // may be false
234 } while ( !$job ); // job may be false if invalid
235 } catch ( RedisException
$e ) {
236 $this->throwRedisException( $this->server
, $conn, $e );
239 // Flag this job as an old duplicate based on its "root" job...
241 if ( $job && $this->isRootJobOldDuplicate( $job ) ) {
242 wfIncrStats( 'job-pop-duplicate' );
243 return DuplicateJob
::newFromJob( $job ); // convert to a no-op
245 } catch ( MWException
$e ) {} // don't lose jobs over this
251 * @see JobQueue::doAck()
254 * @throws MWException
256 protected function doAck( Job
$job ) {
257 if ( $this->claimTTL
> 0 ) {
258 $conn = $this->getConnection();
260 // Get the exact field map this Job came from, regardless of whether
261 // the job was transformed into a DuplicateJob or anything of the sort.
262 $item = $job->metadata
['sourceFields'];
264 $conn->multi( Redis
::MULTI
); // begin (atomic trx)
265 // Remove the first instance of this job scanning right-to-left.
266 // This is O(N) in the worst case, but is likely to be much faster since
267 // jobs are pushed to the left and we are starting from the right, where
268 // the longest running jobs are likely to be. These should be the first
269 // jobs to be acknowledged assuming that job run times are roughly equal.
270 $conn->lRem( $this->getQueueKey( 'l-claimed' ), $item['uid'], -1 );
271 // Delete the job data and its claim metadata
273 $this->prefixWithQueueKey( 'h-meta', $item['uid'] ),
274 $this->prefixWithQueueKey( 'data', $item['uid'] ) );
275 $res = $conn->exec(); // commit (atomic trx)
277 if ( in_array( false, $res, true ) ) {
278 wfDebugLog( 'JobQueueRedis', "Could not acknowledge {$this->type} job." );
281 } catch ( RedisException
$e ) {
282 $this->throwRedisException( $this->server
, $conn, $e );
289 * @see JobQueue::doDeduplicateRootJob()
292 * @throws MWException
294 protected function doDeduplicateRootJob( Job
$job ) {
295 $params = $job->getParams();
296 if ( !isset( $params['rootJobSignature'] ) ) {
297 throw new MWException( "Cannot register root job; missing 'rootJobSignature'." );
298 } elseif ( !isset( $params['rootJobTimestamp'] ) ) {
299 throw new MWException( "Cannot register root job; missing 'rootJobTimestamp'." );
301 $key = $this->getRootJobKey( $params['rootJobSignature'] );
303 $conn = $this->getConnection();
305 $timestamp = $conn->get( $key ); // current last timestamp of this job
306 if ( $timestamp && $timestamp >= $params['rootJobTimestamp'] ) {
307 return true; // a newer version of this root job was enqueued
309 // Update the timestamp of the last root job started at the location...
310 return $conn->set( $key, $params['rootJobTimestamp'], self
::ROOTJOB_TTL
); // 2 weeks
311 } catch ( RedisException
$e ) {
312 $this->throwRedisException( $this->server
, $conn, $e );
317 * Check if the "root" job of a given job has been superseded by a newer one
321 * @throws MWException
323 protected function isRootJobOldDuplicate( Job
$job ) {
324 $params = $job->getParams();
325 if ( !isset( $params['rootJobSignature'] ) ) {
326 return false; // job has no de-deplication info
327 } elseif ( !isset( $params['rootJobTimestamp'] ) ) {
328 wfDebugLog( 'JobQueueRedis', "Cannot check root job; missing 'rootJobTimestamp'." );
332 $conn = $this->getConnection();
334 // Get the last time this root job was enqueued
335 $timestamp = $conn->get( $this->getRootJobKey( $params['rootJobSignature'] ) );
336 } catch ( RedisException
$e ) {
337 $this->throwRedisException( $this->server
, $conn, $e );
340 // Check if a new root job was started at the location after this one's...
341 return ( $timestamp && $timestamp > $params['rootJobTimestamp'] );
345 * Do any job recycling or queue cleanup as needed
348 * @return integer Number of jobs recycled/deleted
349 * @throws MWException
351 protected function doInternalMaintenance() {
352 return ( $this->claimTTL
> 0 ) ?
353 $this->recycleAndDeleteStaleJobs() : $this->cleanupClaimedJobs();
357 * Recycle or destroy any jobs that have been claimed for too long
359 * @return integer Number of jobs recycled/deleted
360 * @throws MWException
362 protected function recycleAndDeleteStaleJobs() {
364 // For each job item that can be retried, we need to add it back to the
365 // main queue and remove it from the list of currenty claimed job items.
366 $conn = $this->getConnection();
368 // Avoid duplicate insertions of items to be re-enqueued
369 $conn->multi( Redis
::MULTI
);
370 $conn->setnx( $this->getQueueKey( 'lock' ), 1 );
371 $conn->expire( $this->getQueueKey( 'lock' ), 3600 );
372 if ( $conn->exec() !== array( true, true ) ) { // lock
373 return $count; // already in progress
377 $claimCutoff = $now - $this->claimTTL
;
378 $pruneCutoff = $now - self
::MAX_AGE_PRUNE
;
380 // Get the list of all claimed jobs
381 $claimedUids = $conn->lRange( $this->getQueueKey( 'l-claimed' ), 0, -1 );
382 // Get a map of (uid => claim metadata) for all claimed jobs
383 $metadata = $conn->mGet( $this->prefixValuesWithQueueKey( 'h-meta', $claimedUids ) );
385 $uidsPush = array(); // items IDs to move to the "unclaimed" queue
386 $uidsRemove = array(); // item IDs to remove from "claimed" queue
387 foreach ( $claimedUids as $i => $uid ) { // all claimed items
388 $info = $metadata[$i] ?
$metadata[$i] : array();
389 if ( isset( $info['ctime'] ) ||
isset( $info['rctime'] ) ) {
390 // Prefer "ctime" (set by pop()) over "rctime" (set by this function)
391 $ctime = isset( $info['ctime'] ) ?
$info['ctime'] : $info['rctime'];
392 // Claimed job claimed for too long?
393 if ( $ctime < $claimCutoff ) {
394 // Get the number of failed attempts
395 $attempts = isset( $info['attempts'] ) ?
$info['attempts'] : 0;
396 if ( $attempts < self
::MAX_ATTEMPTS
) {
397 $uidsPush[] = $uid; // retry it
398 } elseif ( $ctime < $pruneCutoff ) {
399 $uidsRemove[] = $uid; // just remove it
403 // If pop() failed to set the claim timestamp, set it to the current time.
404 // Since that function sets this non-atomically *after* moving the job to
405 // the "claimed" queue, it may be the case that it just didn't set it yet.
406 $conn->hSet( $this->prefixWithQueueKey( 'h-meta', $uid ), 'rctime', $now );
410 $conn->multi( Redis
::MULTI
); // begin (atomic trx)
411 if ( count( $uidsPush ) ) { // move from "l-claimed" to "l-unclaimed"
412 call_user_func_array(
413 array( $conn, 'lPush' ),
414 array_merge( array( $this->getQueueKey( 'l-unclaimed' ) ), $uidsPush )
416 foreach ( $uidsPush as $uid ) {
417 $conn->lRem( $this->getQueueKey( 'l-claimed' ), $uid, -1 );
418 $conn->hDel( $this->prefixWithQueueKey( 'h-meta', $uid ), 'ctime', 'rctime' );
419 $conn->hIncrBy( $this->prefixWithQueueKey( 'h-meta', $uid ), 'attempts', 1 );
422 foreach ( $uidsRemove as $uid ) { // remove from "l-claimed"
423 $conn->lRem( $this->getQueueKey( 'l-claimed' ), $uid, -1 );
424 $conn->delete( // delete job data and metadata
425 $this->prefixWithQueueKey( 'h-meta', $uid ),
426 $this->prefixWithQueueKey( 'data', $uid ) );
428 $res = $conn->exec(); // commit (atomic trx)
430 if ( in_array( false, $res, true ) ) {
431 wfDebugLog( 'JobQueueRedis', "Could not recycle {$this->type} job(s)." );
433 $count +
= ( count( $uidsPush ) +
count( $uidsRemove ) );
434 wfIncrStats( 'job-recycle', count( $uidsPush ) );
437 $conn->delete( $this->getQueueKey( 'lock' ) ); // unlock
438 } catch ( RedisException
$e ) {
439 $this->throwRedisException( $this->server
, $conn, $e );
446 * Destroy any jobs that have been claimed
448 * @return integer Number of jobs deleted
449 * @throws MWException
451 protected function cleanupClaimedJobs() {
453 // Make sure the message for claimed jobs was deleted
454 // and remove the claimed job IDs from the "claimed" list.
455 $conn = $this->getConnection();
457 // Avoid races and duplicate effort
458 $conn->multi( Redis
::MULTI
);
459 $conn->setnx( $this->getQueueKey( 'lock' ), 1 );
460 $conn->expire( $this->getQueueKey( 'lock' ), 3600 );
461 if ( $conn->exec() !== array( true, true ) ) { // lock
462 return $count; // already in progress
464 // Get the list of all claimed jobs
465 $uids = $conn->lRange( $this->getQueueKey( 'l-claimed' ), 0, -1 );
466 if ( count( $uids ) ) {
467 // Delete the message keys and delist the corresponding ids.
468 // Since the only other changes to "l-claimed" are left pushes, we can just strip
469 // off the elements read here using a right trim based on the number of ids read.
470 $conn->multi( Redis
::MULTI
); // begin (atomic trx)
471 $conn->lTrim( $this->getQueueKey( 'l-claimed' ), 0, -count( $uids ) - 1 );
472 $conn->delete( array_merge(
473 $this->prefixValuesWithQueueKey( 'h-meta', $uids ),
474 $this->prefixValuesWithQueueKey( 'data', $uids )
476 $res = $conn->exec(); // commit (atomic trx)
478 if ( in_array( false, $res, true ) ) {
479 wfDebugLog( 'JobQueueRedis', "Could not purge {$this->type} job(s)." );
481 $count +
= count( $uids );
484 $conn->delete( $this->getQueueKey( 'lock' ) ); // unlock
485 } catch ( RedisException
$e ) {
486 $this->throwRedisException( $this->server
, $conn, $e );
496 protected function getNewJobFields( Job
$job ) {
498 // Fields that describe the nature of the job
499 'type' => $job->getType(),
500 'namespace' => $job->getTitle()->getNamespace(),
501 'title' => $job->getTitle()->getDBkey(),
502 'params' => $job->getParams(),
503 // Additional metadata
504 'uid' => $job->ignoreDuplicates()
505 ?
wfBaseConvert( sha1( serialize( $job->getDeduplicationInfo() ) ), 16, 36, 31 )
506 : wfRandomString( 32 ),
507 'timestamp' => time() // UNIX timestamp
512 * @param $fields array
515 protected function getJobFromFields( array $fields ) {
516 $title = Title
::makeTitleSafe( $fields['namespace'], $fields['title'] );
518 $job = Job
::factory( $fields['type'], $title, $fields['params'] );
519 $job->metadata
['sourceFields'] = $fields;
526 * @param $uid string Job UID
527 * @return bool Whether $uid is a SHA-1 hash based identifier for de-duplication
529 protected function isHashUid( $uid ) {
530 return strlen( $uid ) == 31;
534 * Get a connection to the server that handles all sub-queues for this queue
536 * @return Array (server name, Redis instance)
537 * @throws MWException
539 protected function getConnection() {
540 $conn = $this->redisPool
->getConnection( $this->server
);
542 throw new MWException( "Unable to connect to redis server." );
548 * @param $server string
549 * @param $conn RedisConnRef
550 * @param $e RedisException
551 * @throws MWException
553 protected function throwRedisException( $server, RedisConnRef
$conn, $e ) {
554 $this->redisPool
->handleException( $server, $conn, $e );
555 throw new MWException( "Redis server error: {$e->getMessage()}\n" );
559 * @param $prop string
562 private function getQueueKey( $prop ) {
563 list( $db, $prefix ) = wfSplitWikiID( $this->wiki
);
564 return wfForeignMemcKey( $db, $prefix, 'jobqueue', $this->type
, $prop );
568 * @param string $signature Hash identifier of the root job
571 private function getRootJobKey( $signature ) {
572 list( $db, $prefix ) = wfSplitWikiID( $this->wiki
);
573 return wfForeignMemcKey( $db, $prefix, 'jobqueue', $this->type
, 'rootjob', $signature );
577 * @param $prop string
578 * @param $string string
581 private function prefixWithQueueKey( $prop, $string ) {
582 return $this->getQueueKey( $prop ) . ':' . $string;
586 * @param $prop string
587 * @param $items array
590 private function prefixValuesWithQueueKey( $prop, array $items ) {
592 foreach ( $items as $item ) {
593 $res[] = $this->prefixWithQueueKey( $prop, $item );
599 * @param $prop string
600 * @param $items array
603 private function prefixKeysWithQueueKey( $prop, array $items ) {
605 foreach ( $items as $key => $item ) {
606 $res[$this->prefixWithQueueKey( $prop, $key )] = $item;