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 */
65 /** @var string Compression method to use */
66 protected $compression;
68 protected $daemonized;
70 const MAX_AGE_PRUNE
= 604800; // integer; seconds a job can live once claimed (7 days)
72 /** @var string Key to prefix the queue keys with (used for testing) */
77 * - redisConfig : An array of parameters to RedisConnectionPool::__construct().
78 * Note that the serializer option is ignored as "none" is always used.
79 * - redisServer : A hostname/port combination or the absolute path of a UNIX socket.
80 * If a hostname is specified but no port, the standard port number
81 * 6379 will be used. Required.
82 * - compression : The type of compression to use; one of (none,gzip).
83 * - daemonized : Set to true if the redisJobRunnerService runs in the background.
84 * This will disable job recycling/undelaying from the MediaWiki side
85 * to avoid redundance and out-of-sync configuration.
86 * @param array $params
88 public function __construct( array $params ) {
89 parent
::__construct( $params );
90 $params['redisConfig']['serializer'] = 'none'; // make it easy to use Lua
91 $this->server
= $params['redisServer'];
92 $this->compression
= isset( $params['compression'] ) ?
$params['compression'] : 'none';
93 $this->redisPool
= RedisConnectionPool
::singleton( $params['redisConfig'] );
94 $this->daemonized
= !empty( $params['daemonized'] );
97 protected function supportedOrders() {
98 return array( 'timestamp', 'fifo' );
101 protected function optimalOrder() {
105 protected function supportsDelayedJobs() {
110 * @see JobQueue::doIsEmpty()
112 * @throws MWException
114 protected function doIsEmpty() {
115 return $this->doGetSize() == 0;
119 * @see JobQueue::doGetSize()
121 * @throws MWException
123 protected function doGetSize() {
124 $conn = $this->getConnection();
126 return $conn->lSize( $this->getQueueKey( 'l-unclaimed' ) );
127 } catch ( RedisException
$e ) {
128 $this->throwRedisException( $conn, $e );
133 * @see JobQueue::doGetAcquiredCount()
135 * @throws JobQueueError
137 protected function doGetAcquiredCount() {
138 if ( $this->claimTTL
<= 0 ) {
139 return 0; // no acknowledgements
141 $conn = $this->getConnection();
143 $conn->multi( Redis
::PIPELINE
);
144 $conn->zSize( $this->getQueueKey( 'z-claimed' ) );
145 $conn->zSize( $this->getQueueKey( 'z-abandoned' ) );
147 return array_sum( $conn->exec() );
148 } catch ( RedisException
$e ) {
149 $this->throwRedisException( $conn, $e );
154 * @see JobQueue::doGetDelayedCount()
156 * @throws JobQueueError
158 protected function doGetDelayedCount() {
159 if ( !$this->checkDelay
) {
160 return 0; // no delayed jobs
162 $conn = $this->getConnection();
164 return $conn->zSize( $this->getQueueKey( 'z-delayed' ) );
165 } catch ( RedisException
$e ) {
166 $this->throwRedisException( $conn, $e );
171 * @see JobQueue::doGetAbandonedCount()
173 * @throws JobQueueError
175 protected function doGetAbandonedCount() {
176 if ( $this->claimTTL
<= 0 ) {
177 return 0; // no acknowledgements
179 $conn = $this->getConnection();
181 return $conn->zSize( $this->getQueueKey( 'z-abandoned' ) );
182 } catch ( RedisException
$e ) {
183 $this->throwRedisException( $conn, $e );
188 * @see JobQueue::doBatchPush()
192 * @throws JobQueueError
194 protected function doBatchPush( array $jobs, $flags ) {
195 // Convert the jobs into field maps (de-duplicated against each other)
196 $items = array(); // (job ID => job fields map)
197 foreach ( $jobs as $job ) {
198 $item = $this->getNewJobFields( $job );
199 if ( strlen( $item['sha1'] ) ) { // hash identifier => de-duplicate
200 $items[$item['sha1']] = $item;
202 $items[$item['uuid']] = $item;
206 if ( !count( $items ) ) {
207 return; // nothing to do
210 $conn = $this->getConnection();
212 // Actually push the non-duplicate jobs into the queue...
213 if ( $flags & self
::QOS_ATOMIC
) {
214 $batches = array( $items ); // all or nothing
216 $batches = array_chunk( $items, 500 ); // avoid tying up the server
220 foreach ( $batches as $itemBatch ) {
221 $added = $this->pushBlobs( $conn, $itemBatch );
222 if ( is_int( $added ) ) {
225 $failed +
= count( $itemBatch );
229 wfDebugLog( 'JobQueueRedis', "Could not insert {$failed} {$this->type} job(s)." );
231 throw new RedisException( "Could not insert {$failed} {$this->type} job(s)." );
233 JobQueue
::incrStats( 'job-insert', $this->type
, count( $items ), $this->wiki
);
234 JobQueue
::incrStats( 'job-insert-duplicate', $this->type
,
235 count( $items ) - $failed - $pushed, $this->wiki
);
236 } catch ( RedisException
$e ) {
237 $this->throwRedisException( $conn, $e );
242 * @param RedisConnRef $conn
243 * @param array $items List of results from JobQueueRedis::getNewJobFields()
244 * @return int Number of jobs inserted (duplicates are ignored)
245 * @throws RedisException
247 protected function pushBlobs( RedisConnRef
$conn, array $items ) {
248 $args = array(); // ([id, sha1, rtime, blob [, id, sha1, rtime, blob ... ] ] )
249 foreach ( $items as $item ) {
250 $args[] = (string)$item['uuid'];
251 $args[] = (string)$item['sha1'];
252 $args[] = (string)$item['rtimestamp'];
253 $args[] = (string)$this->serialize( $item );
257 local kUnclaimed, kSha1ById, kIdBySha1, kDelayed, kData = unpack(KEYS)
258 if #ARGV % 4 ~= 0 then return redis.error_reply('Unmatched arguments') end
261 local id,sha1,rtimestamp,blob = ARGV[i],ARGV[i+1],ARGV[i+2],ARGV[i+3]
262 if sha1 == '' or redis.call('hExists',kIdBySha1,sha1) == 0 then
263 if 1*rtimestamp > 0 then
264 -- Insert into delayed queue (release time as score)
265 redis.call('zAdd',kDelayed,rtimestamp,id)
267 -- Insert into unclaimed queue
268 redis.call('lPush',kUnclaimed,id)
271 redis.call('hSet',kSha1ById,id,sha1)
272 redis.call('hSet',kIdBySha1,sha1,id)
274 redis.call('hSet',kData,id,blob)
280 return $conn->luaEval( $script,
283 $this->getQueueKey( 'l-unclaimed' ), # KEYS[1]
284 $this->getQueueKey( 'h-sha1ById' ), # KEYS[2]
285 $this->getQueueKey( 'h-idBySha1' ), # KEYS[3]
286 $this->getQueueKey( 'z-delayed' ), # KEYS[4]
287 $this->getQueueKey( 'h-data' ), # KEYS[5]
291 5 # number of first argument(s) that are keys
296 * @see JobQueue::doPop()
298 * @throws JobQueueError
300 protected function doPop() {
303 // Push ready delayed jobs into the queue every 10 jobs to spread the load.
304 // This is also done as a periodic task, but we don't want too much done at once.
305 if ( $this->checkDelay
&& mt_rand( 0, 9 ) == 0 ) {
306 $this->recyclePruneAndUndelayJobs();
309 $conn = $this->getConnection();
312 if ( $this->claimTTL
> 0 ) {
313 // Keep the claimed job list down for high-traffic queues
314 if ( mt_rand( 0, 99 ) == 0 ) {
315 $this->recyclePruneAndUndelayJobs();
317 $blob = $this->popAndAcquireBlob( $conn );
319 $blob = $this->popAndDeleteBlob( $conn );
321 if ( !is_string( $blob ) ) {
322 break; // no jobs; nothing to do
325 JobQueue
::incrStats( 'job-pop', $this->type
, 1, $this->wiki
);
326 $item = $this->unserialize( $blob );
327 if ( $item === false ) {
328 wfDebugLog( 'JobQueueRedis', "Could not unserialize {$this->type} job." );
332 // If $item is invalid, recyclePruneAndUndelayJobs() will cleanup as needed
333 $job = $this->getJobFromFields( $item ); // may be false
334 } while ( !$job ); // job may be false if invalid
335 } catch ( RedisException
$e ) {
336 $this->throwRedisException( $conn, $e );
343 * @param RedisConnRef $conn
344 * @return array Serialized string or false
345 * @throws RedisException
347 protected function popAndDeleteBlob( RedisConnRef
$conn ) {
350 local kUnclaimed, kSha1ById, kIdBySha1, kData = unpack(KEYS)
351 -- Pop an item off the queue
352 local id = redis.call('rpop',kUnclaimed)
353 if not id then return false end
354 -- Get the job data and remove it
355 local item = redis.call('hGet',kData,id)
356 redis.call('hDel',kData,id)
357 -- Allow new duplicates of this job
358 local sha1 = redis.call('hGet',kSha1ById,id)
359 if sha1 then redis.call('hDel',kIdBySha1,sha1) end
360 redis.call('hDel',kSha1ById,id)
361 -- Return the job data
364 return $conn->luaEval( $script,
366 $this->getQueueKey( 'l-unclaimed' ), # KEYS[1]
367 $this->getQueueKey( 'h-sha1ById' ), # KEYS[2]
368 $this->getQueueKey( 'h-idBySha1' ), # KEYS[3]
369 $this->getQueueKey( 'h-data' ), # KEYS[4]
371 4 # number of first argument(s) that are keys
376 * @param RedisConnRef $conn
377 * @return array Serialized string or false
378 * @throws RedisException
380 protected function popAndAcquireBlob( RedisConnRef
$conn ) {
383 local kUnclaimed, kSha1ById, kIdBySha1, kClaimed, kAttempts, kData = unpack(KEYS)
384 -- Pop an item off the queue
385 local id = redis.call('rPop',kUnclaimed)
386 if not id then return false end
387 -- Allow new duplicates of this job
388 local sha1 = redis.call('hGet',kSha1ById,id)
389 if sha1 then redis.call('hDel',kIdBySha1,sha1) end
390 redis.call('hDel',kSha1ById,id)
391 -- Mark the jobs as claimed and return it
392 redis.call('zAdd',kClaimed,ARGV[1],id)
393 redis.call('hIncrBy',kAttempts,id,1)
394 return redis.call('hGet',kData,id)
396 return $conn->luaEval( $script,
398 $this->getQueueKey( 'l-unclaimed' ), # KEYS[1]
399 $this->getQueueKey( 'h-sha1ById' ), # KEYS[2]
400 $this->getQueueKey( 'h-idBySha1' ), # KEYS[3]
401 $this->getQueueKey( 'z-claimed' ), # KEYS[4]
402 $this->getQueueKey( 'h-attempts' ), # KEYS[5]
403 $this->getQueueKey( 'h-data' ), # KEYS[6]
404 time(), # ARGV[1] (injected to be replication-safe)
406 6 # number of first argument(s) that are keys
411 * @see JobQueue::doAck()
414 * @throws MWException|JobQueueError
416 protected function doAck( Job
$job ) {
417 if ( !isset( $job->metadata
['uuid'] ) ) {
418 throw new MWException( "Job of type '{$job->getType()}' has no UUID." );
420 if ( $this->claimTTL
> 0 ) {
421 $conn = $this->getConnection();
425 local kClaimed, kAttempts, kData = unpack(KEYS)
426 -- Unmark the job as claimed
427 redis.call('zRem',kClaimed,ARGV[1])
428 redis.call('hDel',kAttempts,ARGV[1])
429 -- Delete the job data itself
430 return redis.call('hDel',kData,ARGV[1])
432 $res = $conn->luaEval( $script,
434 $this->getQueueKey( 'z-claimed' ), # KEYS[1]
435 $this->getQueueKey( 'h-attempts' ), # KEYS[2]
436 $this->getQueueKey( 'h-data' ), # KEYS[3]
437 $job->metadata
['uuid'] # ARGV[1]
439 3 # number of first argument(s) that are keys
443 wfDebugLog( 'JobQueueRedis', "Could not acknowledge {$this->type} job." );
447 } catch ( RedisException
$e ) {
448 $this->throwRedisException( $conn, $e );
456 * @see JobQueue::doDeduplicateRootJob()
459 * @throws MWException|JobQueueError
461 protected function doDeduplicateRootJob( Job
$job ) {
462 if ( !$job->hasRootJobParams() ) {
463 throw new MWException( "Cannot register root job; missing parameters." );
465 $params = $job->getRootJobParams();
467 $key = $this->getRootJobCacheKey( $params['rootJobSignature'] );
469 $conn = $this->getConnection();
471 $timestamp = $conn->get( $key ); // current last timestamp of this job
472 if ( $timestamp && $timestamp >= $params['rootJobTimestamp'] ) {
473 return true; // a newer version of this root job was enqueued
476 // Update the timestamp of the last root job started at the location...
477 return $conn->set( $key, $params['rootJobTimestamp'], self
::ROOTJOB_TTL
); // 2 weeks
478 } catch ( RedisException
$e ) {
479 $this->throwRedisException( $conn, $e );
484 * @see JobQueue::doIsRootJobOldDuplicate()
487 * @throws JobQueueError
489 protected function doIsRootJobOldDuplicate( Job
$job ) {
490 if ( !$job->hasRootJobParams() ) {
491 return false; // job has no de-deplication info
493 $params = $job->getRootJobParams();
495 $conn = $this->getConnection();
497 // Get the last time this root job was enqueued
498 $timestamp = $conn->get( $this->getRootJobCacheKey( $params['rootJobSignature'] ) );
499 } catch ( RedisException
$e ) {
500 $this->throwRedisException( $conn, $e );
503 // Check if a new root job was started at the location after this one's...
504 return ( $timestamp && $timestamp > $params['rootJobTimestamp'] );
508 * @see JobQueue::doDelete()
510 * @throws JobQueueError
512 protected function doDelete() {
513 static $props = array( 'l-unclaimed', 'z-claimed', 'z-abandoned',
514 'z-delayed', 'h-idBySha1', 'h-sha1ById', 'h-attempts', 'h-data' );
516 $conn = $this->getConnection();
519 foreach ( $props as $prop ) {
520 $keys[] = $this->getQueueKey( $prop );
523 return ( $conn->delete( $keys ) !== false );
524 } catch ( RedisException
$e ) {
525 $this->throwRedisException( $conn, $e );
530 * @see JobQueue::getAllQueuedJobs()
533 public function getAllQueuedJobs() {
534 $conn = $this->getConnection();
538 return new MappedIterator(
539 $conn->lRange( $this->getQueueKey( 'l-unclaimed' ), 0, -1 ),
540 function ( $uid ) use ( $that, $conn ) {
541 return $that->getJobFromUidInternal( $uid, $conn );
543 array( 'accept' => function ( $job ) {
544 return is_object( $job );
547 } catch ( RedisException
$e ) {
548 $this->throwRedisException( $conn, $e );
553 * @see JobQueue::getAllQueuedJobs()
556 public function getAllDelayedJobs() {
557 $conn = $this->getConnection();
561 return new MappedIterator( // delayed jobs
562 $conn->zRange( $this->getQueueKey( 'z-delayed' ), 0, -1 ),
563 function ( $uid ) use ( $that, $conn ) {
564 return $that->getJobFromUidInternal( $uid, $conn );
566 array( 'accept' => function ( $job ) {
567 return is_object( $job );
570 } catch ( RedisException
$e ) {
571 $this->throwRedisException( $conn, $e );
575 public function getCoalesceLocationInternal() {
576 return "RedisServer:" . $this->server
;
579 protected function doGetSiblingQueuesWithJobs( array $types ) {
580 return array_keys( array_filter( $this->doGetSiblingQueueSizes( $types ) ) );
583 protected function doGetSiblingQueueSizes( array $types ) {
584 $sizes = array(); // (type => size)
585 $types = array_values( $types ); // reindex
586 $conn = $this->getConnection();
588 $conn->multi( Redis
::PIPELINE
);
589 foreach ( $types as $type ) {
590 $conn->lSize( $this->getQueueKey( 'l-unclaimed', $type ) );
592 $res = $conn->exec();
593 if ( is_array( $res ) ) {
594 foreach ( $res as $i => $size ) {
595 $sizes[$types[$i]] = $size;
598 } catch ( RedisException
$e ) {
599 $this->throwRedisException( $conn, $e );
606 * This function should not be called outside JobQueueRedis
609 * @param RedisConnRef $conn
610 * @return Job|bool Returns false if the job does not exist
611 * @throws MWException|JobQueueError
613 public function getJobFromUidInternal( $uid, RedisConnRef
$conn ) {
615 $data = $conn->hGet( $this->getQueueKey( 'h-data' ), $uid );
616 if ( $data === false ) {
617 return false; // not found
619 $item = $this->unserialize( $conn->hGet( $this->getQueueKey( 'h-data' ), $uid ) );
620 if ( !is_array( $item ) ) { // this shouldn't happen
621 throw new MWException( "Could not find job with ID '$uid'." );
623 $title = Title
::makeTitle( $item['namespace'], $item['title'] );
624 $job = Job
::factory( $item['type'], $title, $item['params'] );
625 $job->metadata
['uuid'] = $item['uuid'];
628 } catch ( RedisException
$e ) {
629 $this->throwRedisException( $conn, $e );
634 * Recycle or destroy any jobs that have been claimed for too long
635 * and release any ready delayed jobs into the queue
637 * @return int Number of jobs recycled/deleted/undelayed
638 * @throws MWException|JobQueueError
640 public function recyclePruneAndUndelayJobs() {
642 // For each job item that can be retried, we need to add it back to the
643 // main queue and remove it from the list of currenty claimed job items.
644 // For those that cannot, they are marked as dead and kept around for
645 // investigation and manual job restoration but are eventually deleted.
646 $conn = $this->getConnection();
651 local kClaimed, kAttempts, kUnclaimed, kData, kAbandoned, kDelayed = unpack(KEYS)
652 local released,abandoned,pruned,undelayed = 0,0,0,0
653 -- Get all non-dead jobs that have an expired claim on them.
654 -- The score for each item is the last claim timestamp (UNIX).
655 local staleClaims = redis.call('zRangeByScore',kClaimed,0,ARGV[1])
656 for k,id in ipairs(staleClaims) do
657 local timestamp = redis.call('zScore',kClaimed,id)
658 local attempts = redis.call('hGet',kAttempts,id)
659 if attempts < ARGV[3] then
660 -- Claim expired and retries left: re-enqueue the job
661 redis.call('lPush',kUnclaimed,id)
662 redis.call('hIncrBy',kAttempts,id,1)
663 released = released + 1
665 -- Claim expired and no retries left: mark the job as dead
666 redis.call('zAdd',kAbandoned,timestamp,id)
667 abandoned = abandoned + 1
669 redis.call('zRem',kClaimed,id)
671 -- Get all of the dead jobs that have been marked as dead for too long.
672 -- The score for each item is the last claim timestamp (UNIX).
673 local deadClaims = redis.call('zRangeByScore',kAbandoned,0,ARGV[2])
674 for k,id in ipairs(deadClaims) do
675 -- Stale and out of retries: remove any traces of the job
676 redis.call('zRem',kAbandoned,id)
677 redis.call('hDel',kAttempts,id)
678 redis.call('hDel',kData,id)
681 -- Get the list of ready delayed jobs, sorted by readiness (UNIX timestamp)
682 local ids = redis.call('zRangeByScore',kDelayed,0,ARGV[4])
683 -- Migrate the jobs from the "delayed" set to the "unclaimed" list
684 for k,id in ipairs(ids) do
685 redis.call('lPush',kUnclaimed,id)
686 redis.call('zRem',kDelayed,id)
689 return {released,abandoned,pruned,undelayed}
691 $res = $conn->luaEval( $script,
693 $this->getQueueKey( 'z-claimed' ), # KEYS[1]
694 $this->getQueueKey( 'h-attempts' ), # KEYS[2]
695 $this->getQueueKey( 'l-unclaimed' ), # KEYS[3]
696 $this->getQueueKey( 'h-data' ), # KEYS[4]
697 $this->getQueueKey( 'z-abandoned' ), # KEYS[5]
698 $this->getQueueKey( 'z-delayed' ), # KEYS[6]
699 $now - $this->claimTTL
, # ARGV[1]
700 $now - self
::MAX_AGE_PRUNE
, # ARGV[2]
701 $this->maxTries
, # ARGV[3]
704 6 # number of first argument(s) that are keys
707 list( $released, $abandoned, $pruned, $undelayed ) = $res;
708 $count +
= $released +
$pruned +
$undelayed;
709 JobQueue
::incrStats( 'job-recycle', $this->type
, $released, $this->wiki
);
710 JobQueue
::incrStats( 'job-abandon', $this->type
, $abandoned, $this->wiki
);
711 JobQueue
::incrStats( 'job-undelay', $this->type
, $undelayed, $this->wiki
);
713 } catch ( RedisException
$e ) {
714 $this->throwRedisException( $conn, $e );
723 protected function doGetPeriodicTasks() {
724 if ( $this->daemonized
) {
725 return array(); // managed in the runner loop
727 $periods = array( 3600 ); // standard cleanup (useful on config change)
728 if ( $this->claimTTL
> 0 ) {
729 $periods[] = ceil( $this->claimTTL
/ 2 ); // avoid bad timing
731 if ( $this->checkDelay
) {
732 $periods[] = 300; // 5 minutes
734 $period = min( $periods );
735 $period = max( $period, 30 ); // sanity
738 'recyclePruneAndUndelayJobs' => array(
739 'callback' => array( $this, 'recyclePruneAndUndelayJobs' ),
746 * @param IJobSpecification $job
749 protected function getNewJobFields( IJobSpecification
$job ) {
751 // Fields that describe the nature of the job
752 'type' => $job->getType(),
753 'namespace' => $job->getTitle()->getNamespace(),
754 'title' => $job->getTitle()->getDBkey(),
755 'params' => $job->getParams(),
756 // Some jobs cannot run until a "release timestamp"
757 'rtimestamp' => $job->getReleaseTimestamp() ?
: 0,
758 // Additional job metadata
759 'uuid' => UIDGenerator
::newRawUUIDv4( UIDGenerator
::QUICK_RAND
),
760 'sha1' => $job->ignoreDuplicates()
761 ?
wfBaseConvert( sha1( serialize( $job->getDeduplicationInfo() ) ), 16, 36, 31 )
763 'timestamp' => time() // UNIX timestamp
768 * @param array $fields
771 protected function getJobFromFields( array $fields ) {
772 $title = Title
::makeTitleSafe( $fields['namespace'], $fields['title'] );
774 $job = Job
::factory( $fields['type'], $title, $fields['params'] );
775 $job->metadata
['uuid'] = $fields['uuid'];
784 * @param array $fields
785 * @return string Serialized and possibly compressed version of $fields
787 protected function serialize( array $fields ) {
788 $blob = serialize( $fields );
789 if ( $this->compression
=== 'gzip'
790 && strlen( $blob ) >= 1024
791 && function_exists( 'gzdeflate' )
793 $object = (object)array( 'blob' => gzdeflate( $blob ), 'enc' => 'gzip' );
794 $blobz = serialize( $object );
796 return ( strlen( $blobz ) < strlen( $blob ) ) ?
$blobz : $blob;
803 * @param string $blob
804 * @return array|bool Unserialized version of $blob or false
806 protected function unserialize( $blob ) {
807 $fields = unserialize( $blob );
808 if ( is_object( $fields ) ) {
809 if ( $fields->enc
=== 'gzip' && function_exists( 'gzinflate' ) ) {
810 $fields = unserialize( gzinflate( $fields->blob
) );
816 return is_array( $fields ) ?
$fields : false;
820 * Get a connection to the server that handles all sub-queues for this queue
822 * @return RedisConnRef
823 * @throws JobQueueConnectionError
825 protected function getConnection() {
826 $conn = $this->redisPool
->getConnection( $this->server
);
828 throw new JobQueueConnectionError( "Unable to connect to redis server." );
835 * @param RedisConnRef $conn
836 * @param RedisException $e
837 * @throws JobQueueError
839 protected function throwRedisException( RedisConnRef
$conn, $e ) {
840 $this->redisPool
->handleError( $conn, $e );
841 throw new JobQueueError( "Redis server error: {$e->getMessage()}\n" );
845 * @param string $prop
846 * @param string|null $type
849 private function getQueueKey( $prop, $type = null ) {
850 $type = is_string( $type ) ?
$type : $this->type
;
851 list( $db, $prefix ) = wfSplitWikiID( $this->wiki
);
852 if ( strlen( $this->key
) ) { // namespaced queue (for testing)
853 return wfForeignMemcKey( $db, $prefix, 'jobqueue', $type, $this->key
, $prop );
855 return wfForeignMemcKey( $db, $prefix, 'jobqueue', $type, $prop );
863 public function setTestingPrefix( $key ) {