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 eight main redis keys used to track jobs:
31 * - l-unclaimed : A list of job IDs used for ready unclaimed jobs
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 * - z-delayed : A sorted set of (job ID, UNIX timestamp as score) used for delayed jobs
35 * - h-idBySha1 : A hash of (SHA1 => job ID) for unclaimed jobs used for de-duplication
36 * - h-sha1ById : A hash of (job ID => SHA1) for unclaimed jobs used for de-duplication
37 * - h-attempts : A hash of (job ID => attempt count) used for job claiming/retries
38 * - h-data : A hash of (job ID => serialized blobs) for job storage
39 * A job ID can be in only one of z-delayed, l-unclaimed, z-claimed, and z-abandoned.
40 * If an ID appears in any of those lists, it should have a h-data entry for its ID.
41 * If a job has a SHA1 de-duplication value and its ID is in l-unclaimed or z-delayed, then
42 * there should be no other such jobs with that SHA1. Every h-idBySha1 entry has an h-sha1ById
43 * entry and every h-sha1ById must refer to an ID that is l-unclaimed. If a job has its
44 * ID in z-claimed or z-abandoned, then it must also have an h-attempts entry for its ID.
46 * Additionally, "rootjob:* keys track "root jobs" used for additional de-duplication.
47 * Aside from root job keys, all keys have no expiry, and are only removed when jobs are run.
48 * All the keys are prefixed with the relevant wiki ID information.
50 * This class requires Redis 2.6 as it makes use Lua scripts for fast atomic operations.
51 * Additionally, it should be noted that redis has different persistence modes, such
52 * as rdb snapshots, journaling, and no persistent. Appropriate configuration should be
53 * made on the servers based on what queues are using it and what tolerance they have.
59 class JobQueueRedis
extends JobQueue
{
60 /** @var RedisConnectionPool */
63 /** @var string Server address */
66 /** @var string Compression method to use */
67 protected $compression;
69 const MAX_AGE_PRUNE
= 604800; // integer; seconds a job can live once claimed (7 days)
71 /** @var string Key to prefix the queue keys with (used for testing) */
75 * @var null|int maximum seconds between execution of periodic tasks. Used to speed up
76 * testing but should otherwise be left unset.
78 protected $maximumPeriodicTaskSeconds;
82 * - redisConfig : An array of parameters to RedisConnectionPool::__construct().
83 * Note that the serializer option is ignored as "none" is always used.
84 * - redisServer : A hostname/port combination or the absolute path of a UNIX socket.
85 * If a hostname is specified but no port, the standard port number
86 * 6379 will be used. Required.
87 * - compression : The type of compression to use; one of (none,gzip).
88 * - maximumPeriodicTaskSeconds : Maximum seconds between check periodic tasks. Set to
89 * force faster execution of periodic tasks for inegration tests that
90 * rely on checkDelay. Without this the integration tests are very very
91 * slow. This really shouldn't be set in production.
92 * @param array $params
94 public function __construct( array $params ) {
95 parent
::__construct( $params );
96 $params['redisConfig']['serializer'] = 'none'; // make it easy to use Lua
97 $this->server
= $params['redisServer'];
98 $this->compression
= isset( $params['compression'] ) ?
$params['compression'] : 'none';
99 $this->redisPool
= RedisConnectionPool
::singleton( $params['redisConfig'] );
100 $this->maximumPeriodicTaskSeconds
= isset( $params['maximumPeriodicTaskSeconds'] ) ?
101 $params['maximumPeriodicTaskSeconds'] : null;
104 protected function supportedOrders() {
105 return array( 'timestamp', 'fifo' );
108 protected function optimalOrder() {
112 protected function supportsDelayedJobs() {
117 * @see JobQueue::doIsEmpty()
119 * @throws MWException
121 protected function doIsEmpty() {
122 return $this->doGetSize() == 0;
126 * @see JobQueue::doGetSize()
128 * @throws MWException
130 protected function doGetSize() {
131 $conn = $this->getConnection();
133 return $conn->lSize( $this->getQueueKey( 'l-unclaimed' ) );
134 } catch ( RedisException
$e ) {
135 $this->throwRedisException( $conn, $e );
140 * @see JobQueue::doGetAcquiredCount()
142 * @throws JobQueueError
144 protected function doGetAcquiredCount() {
145 if ( $this->claimTTL
<= 0 ) {
146 return 0; // no acknowledgements
148 $conn = $this->getConnection();
150 $conn->multi( Redis
::PIPELINE
);
151 $conn->zSize( $this->getQueueKey( 'z-claimed' ) );
152 $conn->zSize( $this->getQueueKey( 'z-abandoned' ) );
154 return array_sum( $conn->exec() );
155 } catch ( RedisException
$e ) {
156 $this->throwRedisException( $conn, $e );
161 * @see JobQueue::doGetDelayedCount()
163 * @throws JobQueueError
165 protected function doGetDelayedCount() {
166 if ( !$this->checkDelay
) {
167 return 0; // no delayed jobs
169 $conn = $this->getConnection();
171 return $conn->zSize( $this->getQueueKey( 'z-delayed' ) );
172 } catch ( RedisException
$e ) {
173 $this->throwRedisException( $conn, $e );
178 * @see JobQueue::doGetAbandonedCount()
180 * @throws JobQueueError
182 protected function doGetAbandonedCount() {
183 if ( $this->claimTTL
<= 0 ) {
184 return 0; // no acknowledgements
186 $conn = $this->getConnection();
188 return $conn->zSize( $this->getQueueKey( 'z-abandoned' ) );
189 } catch ( RedisException
$e ) {
190 $this->throwRedisException( $conn, $e );
195 * @see JobQueue::doBatchPush()
199 * @throws JobQueueError
201 protected function doBatchPush( array $jobs, $flags ) {
202 // Convert the jobs into field maps (de-duplicated against each other)
203 $items = array(); // (job ID => job fields map)
204 foreach ( $jobs as $job ) {
205 $item = $this->getNewJobFields( $job );
206 if ( strlen( $item['sha1'] ) ) { // hash identifier => de-duplicate
207 $items[$item['sha1']] = $item;
209 $items[$item['uuid']] = $item;
213 if ( !count( $items ) ) {
214 return true; // nothing to do
217 $conn = $this->getConnection();
219 // Actually push the non-duplicate jobs into the queue...
220 if ( $flags & self
::QOS_ATOMIC
) {
221 $batches = array( $items ); // all or nothing
223 $batches = array_chunk( $items, 500 ); // avoid tying up the server
227 foreach ( $batches as $itemBatch ) {
228 $added = $this->pushBlobs( $conn, $itemBatch );
229 if ( is_int( $added ) ) {
232 $failed +
= count( $itemBatch );
236 wfDebugLog( 'JobQueueRedis', "Could not insert {$failed} {$this->type} job(s)." );
240 JobQueue
::incrStats( 'job-insert', $this->type
, count( $items ), $this->wiki
);
241 JobQueue
::incrStats( 'job-insert-duplicate', $this->type
,
242 count( $items ) - $failed - $pushed, $this->wiki
);
243 } catch ( RedisException
$e ) {
244 $this->throwRedisException( $conn, $e );
251 * @param RedisConnRef $conn
252 * @param array $items List of results from JobQueueRedis::getNewJobFields()
253 * @return int Number of jobs inserted (duplicates are ignored)
254 * @throws RedisException
256 protected function pushBlobs( RedisConnRef
$conn, array $items ) {
257 $args = array(); // ([id, sha1, rtime, blob [, id, sha1, rtime, blob ... ] ] )
258 foreach ( $items as $item ) {
259 $args[] = (string)$item['uuid'];
260 $args[] = (string)$item['sha1'];
261 $args[] = (string)$item['rtimestamp'];
262 $args[] = (string)$this->serialize( $item );
266 local kUnclaimed, kSha1ById, kIdBySha1, kDelayed, kData = unpack(KEYS)
267 if #ARGV % 4 ~= 0 then return redis.error_reply('Unmatched arguments') end
270 local id,sha1,rtimestamp,blob = ARGV[i],ARGV[i+1],ARGV[i+2],ARGV[i+3]
271 if sha1 == '' or redis.call('hExists',kIdBySha1,sha1) == 0 then
272 if 1*rtimestamp > 0 then
273 -- Insert into delayed queue (release time as score)
274 redis.call('zAdd',kDelayed,rtimestamp,id)
276 -- Insert into unclaimed queue
277 redis.call('lPush',kUnclaimed,id)
280 redis.call('hSet',kSha1ById,id,sha1)
281 redis.call('hSet',kIdBySha1,sha1,id)
283 redis.call('hSet',kData,id,blob)
289 return $conn->luaEval( $script,
292 $this->getQueueKey( 'l-unclaimed' ), # KEYS[1]
293 $this->getQueueKey( 'h-sha1ById' ), # KEYS[2]
294 $this->getQueueKey( 'h-idBySha1' ), # KEYS[3]
295 $this->getQueueKey( 'z-delayed' ), # KEYS[4]
296 $this->getQueueKey( 'h-data' ), # KEYS[5]
300 5 # number of first argument(s) that are keys
305 * @see JobQueue::doPop()
307 * @throws JobQueueError
309 protected function doPop() {
312 // Push ready delayed jobs into the queue every 10 jobs to spread the load.
313 // This is also done as a periodic task, but we don't want too much done at once.
314 if ( $this->checkDelay
&& mt_rand( 0, 9 ) == 0 ) {
315 $this->recyclePruneAndUndelayJobs();
318 $conn = $this->getConnection();
321 if ( $this->claimTTL
> 0 ) {
322 // Keep the claimed job list down for high-traffic queues
323 if ( mt_rand( 0, 99 ) == 0 ) {
324 $this->recyclePruneAndUndelayJobs();
326 $blob = $this->popAndAcquireBlob( $conn );
328 $blob = $this->popAndDeleteBlob( $conn );
330 if ( $blob === false ) {
331 break; // no jobs; nothing to do
334 JobQueue
::incrStats( 'job-pop', $this->type
, 1, $this->wiki
);
335 $item = $this->unserialize( $blob );
336 if ( $item === false ) {
337 wfDebugLog( 'JobQueueRedis', "Could not unserialize {$this->type} job." );
341 // If $item is invalid, recyclePruneAndUndelayJobs() will cleanup as needed
342 $job = $this->getJobFromFields( $item ); // may be false
343 } while ( !$job ); // job may be false if invalid
344 } catch ( RedisException
$e ) {
345 $this->throwRedisException( $conn, $e );
352 * @param RedisConnRef $conn
353 * @return array serialized string or false
354 * @throws RedisException
356 protected function popAndDeleteBlob( RedisConnRef
$conn ) {
359 local kUnclaimed, kSha1ById, kIdBySha1, kData = unpack(KEYS)
360 -- Pop an item off the queue
361 local id = redis.call('rpop',kUnclaimed)
362 if not id then return false end
363 -- Get the job data and remove it
364 local item = redis.call('hGet',kData,id)
365 redis.call('hDel',kData,id)
366 -- Allow new duplicates of this job
367 local sha1 = redis.call('hGet',kSha1ById,id)
368 if sha1 then redis.call('hDel',kIdBySha1,sha1) end
369 redis.call('hDel',kSha1ById,id)
370 -- Return the job data
373 return $conn->luaEval( $script,
375 $this->getQueueKey( 'l-unclaimed' ), # KEYS[1]
376 $this->getQueueKey( 'h-sha1ById' ), # KEYS[2]
377 $this->getQueueKey( 'h-idBySha1' ), # KEYS[3]
378 $this->getQueueKey( 'h-data' ), # KEYS[4]
380 4 # number of first argument(s) that are keys
385 * @param RedisConnRef $conn
386 * @return array serialized string or false
387 * @throws RedisException
389 protected function popAndAcquireBlob( RedisConnRef
$conn ) {
392 local kUnclaimed, kSha1ById, kIdBySha1, kClaimed, kAttempts, kData = unpack(KEYS)
393 -- Pop an item off the queue
394 local id = redis.call('rPop',kUnclaimed)
395 if not id then return false end
396 -- Allow new duplicates of this job
397 local sha1 = redis.call('hGet',kSha1ById,id)
398 if sha1 then redis.call('hDel',kIdBySha1,sha1) end
399 redis.call('hDel',kSha1ById,id)
400 -- Mark the jobs as claimed and return it
401 redis.call('zAdd',kClaimed,ARGV[1],id)
402 redis.call('hIncrBy',kAttempts,id,1)
403 return redis.call('hGet',kData,id)
405 return $conn->luaEval( $script,
407 $this->getQueueKey( 'l-unclaimed' ), # KEYS[1]
408 $this->getQueueKey( 'h-sha1ById' ), # KEYS[2]
409 $this->getQueueKey( 'h-idBySha1' ), # KEYS[3]
410 $this->getQueueKey( 'z-claimed' ), # KEYS[4]
411 $this->getQueueKey( 'h-attempts' ), # KEYS[5]
412 $this->getQueueKey( 'h-data' ), # KEYS[6]
413 time(), # ARGV[1] (injected to be replication-safe)
415 6 # number of first argument(s) that are keys
420 * @see JobQueue::doAck()
423 * @throws MWException|JobQueueError
425 protected function doAck( Job
$job ) {
426 if ( !isset( $job->metadata
['uuid'] ) ) {
427 throw new MWException( "Job of type '{$job->getType()}' has no UUID." );
429 if ( $this->claimTTL
> 0 ) {
430 $conn = $this->getConnection();
434 local kClaimed, kAttempts, kData = unpack(KEYS)
435 -- Unmark the job as claimed
436 redis.call('zRem',kClaimed,ARGV[1])
437 redis.call('hDel',kAttempts,ARGV[1])
438 -- Delete the job data itself
439 return redis.call('hDel',kData,ARGV[1])
441 $res = $conn->luaEval( $script,
443 $this->getQueueKey( 'z-claimed' ), # KEYS[1]
444 $this->getQueueKey( 'h-attempts' ), # KEYS[2]
445 $this->getQueueKey( 'h-data' ), # KEYS[3]
446 $job->metadata
['uuid'] # ARGV[1]
448 3 # number of first argument(s) that are keys
452 wfDebugLog( 'JobQueueRedis', "Could not acknowledge {$this->type} job." );
456 } catch ( RedisException
$e ) {
457 $this->throwRedisException( $conn, $e );
465 * @see JobQueue::doDeduplicateRootJob()
468 * @throws MWException|JobQueueError
470 protected function doDeduplicateRootJob( Job
$job ) {
471 if ( !$job->hasRootJobParams() ) {
472 throw new MWException( "Cannot register root job; missing parameters." );
474 $params = $job->getRootJobParams();
476 $key = $this->getRootJobCacheKey( $params['rootJobSignature'] );
478 $conn = $this->getConnection();
480 $timestamp = $conn->get( $key ); // current last timestamp of this job
481 if ( $timestamp && $timestamp >= $params['rootJobTimestamp'] ) {
482 return true; // a newer version of this root job was enqueued
485 // Update the timestamp of the last root job started at the location...
486 return $conn->set( $key, $params['rootJobTimestamp'], self
::ROOTJOB_TTL
); // 2 weeks
487 } catch ( RedisException
$e ) {
488 $this->throwRedisException( $conn, $e );
493 * @see JobQueue::doIsRootJobOldDuplicate()
496 * @throws JobQueueError
498 protected function doIsRootJobOldDuplicate( Job
$job ) {
499 if ( !$job->hasRootJobParams() ) {
500 return false; // job has no de-deplication info
502 $params = $job->getRootJobParams();
504 $conn = $this->getConnection();
506 // Get the last time this root job was enqueued
507 $timestamp = $conn->get( $this->getRootJobCacheKey( $params['rootJobSignature'] ) );
508 } catch ( RedisException
$e ) {
509 $this->throwRedisException( $conn, $e );
512 // Check if a new root job was started at the location after this one's...
513 return ( $timestamp && $timestamp > $params['rootJobTimestamp'] );
517 * @see JobQueue::doDelete()
519 * @throws JobQueueError
521 protected function doDelete() {
522 static $props = array( 'l-unclaimed', 'z-claimed', 'z-abandoned',
523 'z-delayed', 'h-idBySha1', 'h-sha1ById', 'h-attempts', 'h-data' );
525 $conn = $this->getConnection();
528 foreach ( $props as $prop ) {
529 $keys[] = $this->getQueueKey( $prop );
532 return ( $conn->delete( $keys ) !== false );
533 } catch ( RedisException
$e ) {
534 $this->throwRedisException( $conn, $e );
539 * @see JobQueue::getAllQueuedJobs()
542 public function getAllQueuedJobs() {
543 $conn = $this->getConnection();
547 return new MappedIterator(
548 $conn->lRange( $this->getQueueKey( 'l-unclaimed' ), 0, -1 ),
549 function ( $uid ) use ( $that, $conn ) {
550 return $that->getJobFromUidInternal( $uid, $conn );
552 array( 'accept' => function ( $job ) {
553 return is_object( $job );
556 } catch ( RedisException
$e ) {
557 $this->throwRedisException( $conn, $e );
562 * @see JobQueue::getAllQueuedJobs()
565 public function getAllDelayedJobs() {
566 $conn = $this->getConnection();
570 return new MappedIterator( // delayed jobs
571 $conn->zRange( $this->getQueueKey( 'z-delayed' ), 0, -1 ),
572 function ( $uid ) use ( $that, $conn ) {
573 return $that->getJobFromUidInternal( $uid, $conn );
575 array( 'accept' => function ( $job ) {
576 return is_object( $job );
579 } catch ( RedisException
$e ) {
580 $this->throwRedisException( $conn, $e );
584 public function getCoalesceLocationInternal() {
585 return "RedisServer:" . $this->server
;
588 protected function doGetSiblingQueuesWithJobs( array $types ) {
589 return array_keys( array_filter( $this->doGetSiblingQueueSizes( $types ) ) );
592 protected function doGetSiblingQueueSizes( array $types ) {
593 $sizes = array(); // (type => size)
594 $types = array_values( $types ); // reindex
595 $conn = $this->getConnection();
597 $conn->multi( Redis
::PIPELINE
);
598 foreach ( $types as $type ) {
599 $conn->lSize( $this->getQueueKey( 'l-unclaimed', $type ) );
601 $res = $conn->exec();
602 if ( is_array( $res ) ) {
603 foreach ( $res as $i => $size ) {
604 $sizes[$types[$i]] = $size;
607 } catch ( RedisException
$e ) {
608 $this->throwRedisException( $conn, $e );
615 * This function should not be called outside JobQueueRedis
618 * @param $conn RedisConnRef
619 * @return Job|bool Returns false if the job does not exist
620 * @throws MWException|JobQueueError
622 public function getJobFromUidInternal( $uid, RedisConnRef
$conn ) {
624 $data = $conn->hGet( $this->getQueueKey( 'h-data' ), $uid );
625 if ( $data === false ) {
626 return false; // not found
628 $item = $this->unserialize( $conn->hGet( $this->getQueueKey( 'h-data' ), $uid ) );
629 if ( !is_array( $item ) ) { // this shouldn't happen
630 throw new MWException( "Could not find job with ID '$uid'." );
632 $title = Title
::makeTitle( $item['namespace'], $item['title'] );
633 $job = Job
::factory( $item['type'], $title, $item['params'] );
634 $job->metadata
['uuid'] = $item['uuid'];
637 } catch ( RedisException
$e ) {
638 $this->throwRedisException( $conn, $e );
643 * Recycle or destroy any jobs that have been claimed for too long
644 * and release any ready delayed jobs into the queue
646 * @return int Number of jobs recycled/deleted/undelayed
647 * @throws MWException|JobQueueError
649 public function recyclePruneAndUndelayJobs() {
651 // For each job item that can be retried, we need to add it back to the
652 // main queue and remove it from the list of currenty claimed job items.
653 // For those that cannot, they are marked as dead and kept around for
654 // investigation and manual job restoration but are eventually deleted.
655 $conn = $this->getConnection();
660 local kClaimed, kAttempts, kUnclaimed, kData, kAbandoned, kDelayed = unpack(KEYS)
661 local released,abandoned,pruned,undelayed = 0,0,0,0
662 -- Get all non-dead jobs that have an expired claim on them.
663 -- The score for each item is the last claim timestamp (UNIX).
664 local staleClaims = redis.call('zRangeByScore',kClaimed,0,ARGV[1])
665 for k,id in ipairs(staleClaims) do
666 local timestamp = redis.call('zScore',kClaimed,id)
667 local attempts = redis.call('hGet',kAttempts,id)
668 if attempts < ARGV[3] then
669 -- Claim expired and retries left: re-enqueue the job
670 redis.call('lPush',kUnclaimed,id)
671 redis.call('hIncrBy',kAttempts,id,1)
672 released = released + 1
674 -- Claim expired and no retries left: mark the job as dead
675 redis.call('zAdd',kAbandoned,timestamp,id)
676 abandoned = abandoned + 1
678 redis.call('zRem',kClaimed,id)
680 -- Get all of the dead jobs that have been marked as dead for too long.
681 -- The score for each item is the last claim timestamp (UNIX).
682 local deadClaims = redis.call('zRangeByScore',kAbandoned,0,ARGV[2])
683 for k,id in ipairs(deadClaims) do
684 -- Stale and out of retries: remove any traces of the job
685 redis.call('zRem',kAbandoned,id)
686 redis.call('hDel',kAttempts,id)
687 redis.call('hDel',kData,id)
690 -- Get the list of ready delayed jobs, sorted by readiness (UNIX timestamp)
691 local ids = redis.call('zRangeByScore',kDelayed,0,ARGV[4])
692 -- Migrate the jobs from the "delayed" set to the "unclaimed" list
693 for k,id in ipairs(ids) do
694 redis.call('lPush',kUnclaimed,id)
695 redis.call('zRem',kDelayed,id)
698 return {released,abandoned,pruned,undelayed}
700 $res = $conn->luaEval( $script,
702 $this->getQueueKey( 'z-claimed' ), # KEYS[1]
703 $this->getQueueKey( 'h-attempts' ), # KEYS[2]
704 $this->getQueueKey( 'l-unclaimed' ), # KEYS[3]
705 $this->getQueueKey( 'h-data' ), # KEYS[4]
706 $this->getQueueKey( 'z-abandoned' ), # KEYS[5]
707 $this->getQueueKey( 'z-delayed' ), # KEYS[6]
708 $now - $this->claimTTL
, # ARGV[1]
709 $now - self
::MAX_AGE_PRUNE
, # ARGV[2]
710 $this->maxTries
, # ARGV[3]
713 6 # number of first argument(s) that are keys
716 list( $released, $abandoned, $pruned, $undelayed ) = $res;
717 $count +
= $released +
$pruned +
$undelayed;
718 JobQueue
::incrStats( 'job-recycle', $this->type
, $released, $this->wiki
);
719 JobQueue
::incrStats( 'job-abandon', $this->type
, $abandoned, $this->wiki
);
721 } catch ( RedisException
$e ) {
722 $this->throwRedisException( $conn, $e );
731 protected function doGetPeriodicTasks() {
732 $periods = array( 3600 ); // standard cleanup (useful on config change)
733 if ( $this->claimTTL
> 0 ) {
734 $periods[] = ceil( $this->claimTTL
/ 2 ); // avoid bad timing
736 if ( $this->checkDelay
) {
737 $periods[] = 300; // 5 minutes
739 $period = min( $periods );
740 $period = max( $period, 30 ); // sanity
741 // Support override for faster testing
742 if ( $this->maximumPeriodicTaskSeconds
!== null ) {
743 $period = min( $period, $this->maximumPeriodicTaskSeconds
);
746 'recyclePruneAndUndelayJobs' => array(
747 'callback' => array( $this, 'recyclePruneAndUndelayJobs' ),
754 * @param IJobSpecification $job
757 protected function getNewJobFields( IJobSpecification
$job ) {
759 // Fields that describe the nature of the job
760 'type' => $job->getType(),
761 'namespace' => $job->getTitle()->getNamespace(),
762 'title' => $job->getTitle()->getDBkey(),
763 'params' => $job->getParams(),
764 // Some jobs cannot run until a "release timestamp"
765 'rtimestamp' => $job->getReleaseTimestamp() ?
: 0,
766 // Additional job metadata
767 'uuid' => UIDGenerator
::newRawUUIDv4( UIDGenerator
::QUICK_RAND
),
768 'sha1' => $job->ignoreDuplicates()
769 ?
wfBaseConvert( sha1( serialize( $job->getDeduplicationInfo() ) ), 16, 36, 31 )
771 'timestamp' => time() // UNIX timestamp
776 * @param $fields array
779 protected function getJobFromFields( array $fields ) {
780 $title = Title
::makeTitleSafe( $fields['namespace'], $fields['title'] );
782 $job = Job
::factory( $fields['type'], $title, $fields['params'] );
783 $job->metadata
['uuid'] = $fields['uuid'];
792 * @param array $fields
793 * @return string Serialized and possibly compressed version of $fields
795 protected function serialize( array $fields ) {
796 $blob = serialize( $fields );
797 if ( $this->compression
=== 'gzip'
798 && strlen( $blob ) >= 1024
799 && function_exists( 'gzdeflate' )
801 $object = (object)array( 'blob' => gzdeflate( $blob ), 'enc' => 'gzip' );
802 $blobz = serialize( $object );
804 return ( strlen( $blobz ) < strlen( $blob ) ) ?
$blobz : $blob;
811 * @param string $blob
812 * @return array|bool Unserialized version of $blob or false
814 protected function unserialize( $blob ) {
815 $fields = unserialize( $blob );
816 if ( is_object( $fields ) ) {
817 if ( $fields->enc
=== 'gzip' && function_exists( 'gzinflate' ) ) {
818 $fields = unserialize( gzinflate( $fields->blob
) );
824 return is_array( $fields ) ?
$fields : false;
828 * Get a connection to the server that handles all sub-queues for this queue
830 * @return RedisConnRef
831 * @throws JobQueueConnectionError
833 protected function getConnection() {
834 $conn = $this->redisPool
->getConnection( $this->server
);
836 throw new JobQueueConnectionError( "Unable to connect to redis server." );
843 * @param $conn RedisConnRef
844 * @param $e RedisException
845 * @throws JobQueueError
847 protected function throwRedisException( RedisConnRef
$conn, $e ) {
848 $this->redisPool
->handleError( $conn, $e );
849 throw new JobQueueError( "Redis server error: {$e->getMessage()}\n" );
853 * @param $prop string
854 * @param $type string|null
857 private function getQueueKey( $prop, $type = null ) {
858 $type = is_string( $type ) ?
$type : $this->type
;
859 list( $db, $prefix ) = wfSplitWikiID( $this->wiki
);
860 if ( strlen( $this->key
) ) { // namespaced queue (for testing)
861 return wfForeignMemcKey( $db, $prefix, 'jobqueue', $type, $this->key
, $prop );
863 return wfForeignMemcKey( $db, $prefix, 'jobqueue', $type, $prop );
871 public function setTestingPrefix( $key ) {