Merge "Whitelist the <wbr> element."
[mediawiki.git] / includes / job / JobQueueRedis.php
blob939fa42c17d172a7a1ac96984dfe94da4afb170a
1 <?php
2 /**
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
20 * @file
21 * @author Aaron Schulz
24 /**
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.
55 * @ingroup JobQueue
56 * @ingroup Redis
57 * @since 1.22
59 class JobQueueRedis extends JobQueue {
60 /** @var RedisConnectionPool */
61 protected $redisPool;
63 protected $server; // string; server address
64 protected $compression; // string; compression method to use
66 const MAX_AGE_PRUNE = 604800; // integer; seconds a job can live once claimed (7 days)
68 protected $key; // string; key to prefix the queue keys with (used for testing)
70 /**
71 * @params include:
72 * - redisConfig : An array of parameters to RedisConnectionPool::__construct().
73 * Note that the serializer option is ignored "none" is always used.
74 * - redisServer : A hostname/port combination or the absolute path of a UNIX socket.
75 * If a hostname is specified but no port, the standard port number
76 * 6379 will be used. Required.
77 * - compression : The type of compression to use; one of (none,gzip).
78 * @param array $params
80 public function __construct( array $params ) {
81 parent::__construct( $params );
82 $params['redisConfig']['serializer'] = 'none'; // make it easy to use Lua
83 $this->server = $params['redisServer'];
84 $this->compression = isset( $params['compression'] ) ? $params['compression'] : 'none';
85 $this->redisPool = RedisConnectionPool::singleton( $params['redisConfig'] );
88 protected function supportedOrders() {
89 return array( 'timestamp', 'fifo' );
92 protected function optimalOrder() {
93 return 'fifo';
96 protected function supportsDelayedJobs() {
97 return true;
101 * @see JobQueue::doIsEmpty()
102 * @return bool
103 * @throws MWException
105 protected function doIsEmpty() {
106 return $this->doGetSize() == 0;
110 * @see JobQueue::doGetSize()
111 * @return integer
112 * @throws MWException
114 protected function doGetSize() {
115 $conn = $this->getConnection();
116 try {
117 return $conn->lSize( $this->getQueueKey( 'l-unclaimed' ) );
118 } catch ( RedisException $e ) {
119 $this->throwRedisException( $this->server, $conn, $e );
124 * @see JobQueue::doGetAcquiredCount()
125 * @return integer
126 * @throws MWException
128 protected function doGetAcquiredCount() {
129 if ( $this->claimTTL <= 0 ) {
130 return 0; // no acknowledgements
132 $conn = $this->getConnection();
133 try {
134 $conn->multi( Redis::PIPELINE );
135 $conn->zSize( $this->getQueueKey( 'z-claimed' ) );
136 $conn->zSize( $this->getQueueKey( 'z-abandoned' ) );
137 return array_sum( $conn->exec() );
138 } catch ( RedisException $e ) {
139 $this->throwRedisException( $this->server, $conn, $e );
144 * @see JobQueue::doGetDelayedCount()
145 * @return integer
146 * @throws MWException
148 protected function doGetDelayedCount() {
149 if ( !$this->checkDelay ) {
150 return 0; // no delayed jobs
152 $conn = $this->getConnection();
153 try {
154 return $conn->zSize( $this->getQueueKey( 'z-delayed' ) );
155 } catch ( RedisException $e ) {
156 $this->throwRedisException( $this->server, $conn, $e );
161 * @see JobQueue::doGetAbandonedCount()
162 * @return integer
163 * @throws MWException
165 protected function doGetAbandonedCount() {
166 if ( $this->claimTTL <= 0 ) {
167 return 0; // no acknowledgements
169 $conn = $this->getConnection();
170 try {
171 return $conn->zSize( $this->getQueueKey( 'z-abandoned' ) );
172 } catch ( RedisException $e ) {
173 $this->throwRedisException( $this->server, $conn, $e );
178 * @see JobQueue::doBatchPush()
179 * @param array $jobs
180 * @param $flags
181 * @return bool
182 * @throws MWException
184 protected function doBatchPush( array $jobs, $flags ) {
185 // Convert the jobs into field maps (de-duplicated against each other)
186 $items = array(); // (job ID => job fields map)
187 foreach ( $jobs as $job ) {
188 $item = $this->getNewJobFields( $job );
189 if ( strlen( $item['sha1'] ) ) { // hash identifier => de-duplicate
190 $items[$item['sha1']] = $item;
191 } else {
192 $items[$item['uuid']] = $item;
196 if ( !count( $items ) ) {
197 return true; // nothing to do
200 $conn = $this->getConnection();
201 try {
202 // Actually push the non-duplicate jobs into the queue...
203 if ( $flags & self::QOS_ATOMIC ) {
204 $batches = array( $items ); // all or nothing
205 } else {
206 $batches = array_chunk( $items, 500 ); // avoid tying up the server
208 $failed = 0;
209 $pushed = 0;
210 foreach ( $batches as $itemBatch ) {
211 $added = $this->pushBlobs( $conn, $itemBatch );
212 if ( is_int( $added ) ) {
213 $pushed += $added;
214 } else {
215 $failed += count( $itemBatch );
218 if ( $failed > 0 ) {
219 wfDebugLog( 'JobQueueRedis', "Could not insert {$failed} {$this->type} job(s)." );
220 return false;
222 JobQueue::incrStats( 'job-insert', $this->type, count( $items ) );
223 JobQueue::incrStats( 'job-insert-duplicate', $this->type,
224 count( $items ) - $failed - $pushed );
225 } catch ( RedisException $e ) {
226 $this->throwRedisException( $this->server, $conn, $e );
229 return true;
233 * @param RedisConnRef $conn
234 * @param array $items List of results from JobQueueRedis::getNewJobFields()
235 * @return integer Number of jobs inserted (duplicates are ignored)
236 * @throws RedisException
238 protected function pushBlobs( RedisConnRef $conn, array $items ) {
239 $args = array(); // ([id, sha1, rtime, blob [, id, sha1, rtime, blob ... ] ] )
240 foreach ( $items as $item ) {
241 $args[] = (string)$item['uuid'];
242 $args[] = (string)$item['sha1'];
243 $args[] = (string)$item['rtimestamp'];
244 $args[] = (string)$this->serialize( $item );
246 static $script =
247 <<<LUA
248 if #ARGV % 4 ~= 0 then return redis.error_reply('Unmatched arguments') end
249 local pushed = 0
250 for i = 1,#ARGV,4 do
251 local id,sha1,rtimestamp,blob = ARGV[i],ARGV[i+1],ARGV[i+2],ARGV[i+3]
252 if sha1 == '' or redis.call('hExists',KEYS[3],sha1) == 0 then
253 if 1*rtimestamp > 0 then
254 -- Insert into delayed queue (release time as score)
255 redis.call('zAdd',KEYS[4],rtimestamp,id)
256 else
257 -- Insert into unclaimed queue
258 redis.call('lPush',KEYS[1],id)
260 if sha1 ~= '' then
261 redis.call('hSet',KEYS[2],id,sha1)
262 redis.call('hSet',KEYS[3],sha1,id)
264 redis.call('hSet',KEYS[5],id,blob)
265 pushed = pushed + 1
268 return pushed
269 LUA;
270 return $conn->luaEval( $script,
271 array_merge(
272 array(
273 $this->getQueueKey( 'l-unclaimed' ), # KEYS[1]
274 $this->getQueueKey( 'h-sha1ById' ), # KEYS[2]
275 $this->getQueueKey( 'h-idBySha1' ), # KEYS[3]
276 $this->getQueueKey( 'z-delayed' ), # KEYS[4]
277 $this->getQueueKey( 'h-data' ), # KEYS[5]
279 $args
281 5 # number of first argument(s) that are keys
286 * @see JobQueue::doPop()
287 * @return Job|bool
288 * @throws MWException
290 protected function doPop() {
291 $job = false;
293 // Push ready delayed jobs into the queue every 10 jobs to spread the load.
294 // This is also done as a periodic task, but we don't want too much done at once.
295 if ( $this->checkDelay && mt_rand( 0, 9 ) == 0 ) {
296 $this->releaseReadyDelayedJobs();
299 $conn = $this->getConnection();
300 try {
301 do {
302 if ( $this->claimTTL > 0 ) {
303 // Keep the claimed job list down for high-traffic queues
304 if ( mt_rand( 0, 99 ) == 0 ) {
305 $this->recycleAndDeleteStaleJobs();
307 $blob = $this->popAndAcquireBlob( $conn );
308 } else {
309 $blob = $this->popAndDeleteBlob( $conn );
311 if ( $blob === false ) {
312 break; // no jobs; nothing to do
315 JobQueue::incrStats( 'job-pop', $this->type );
316 $item = $this->unserialize( $blob );
317 if ( $item === false ) {
318 wfDebugLog( 'JobQueueRedis', "Could not unserialize {$this->type} job." );
319 continue;
322 // If $item is invalid, recycleAndDeleteStaleJobs() will cleanup as needed
323 $job = $this->getJobFromFields( $item ); // may be false
324 } while ( !$job ); // job may be false if invalid
325 } catch ( RedisException $e ) {
326 $this->throwRedisException( $this->server, $conn, $e );
329 return $job;
333 * @param RedisConnRef $conn
334 * @return array serialized string or false
335 * @throws RedisException
337 protected function popAndDeleteBlob( RedisConnRef $conn ) {
338 static $script =
339 <<<LUA
340 -- Pop an item off the queue
341 local id = redis.call('rpop',KEYS[1])
342 if not id then return false end
343 -- Get the job data and remove it
344 local item = redis.call('hGet',KEYS[4],id)
345 redis.call('hDel',KEYS[4],id)
346 -- Allow new duplicates of this job
347 local sha1 = redis.call('hGet',KEYS[2],id)
348 if sha1 then redis.call('hDel',KEYS[3],sha1) end
349 redis.call('hDel',KEYS[2],id)
350 -- Return the job data
351 return item
352 LUA;
353 return $conn->luaEval( $script,
354 array(
355 $this->getQueueKey( 'l-unclaimed' ), # KEYS[1]
356 $this->getQueueKey( 'h-sha1ById' ), # KEYS[2]
357 $this->getQueueKey( 'h-idBySha1' ), # KEYS[3]
358 $this->getQueueKey( 'h-data' ), # KEYS[4]
360 4 # number of first argument(s) that are keys
365 * @param RedisConnRef $conn
366 * @return array serialized string or false
367 * @throws RedisException
369 protected function popAndAcquireBlob( RedisConnRef $conn ) {
370 static $script =
371 <<<LUA
372 -- Pop an item off the queue
373 local id = redis.call('rPop',KEYS[1])
374 if not id then return false end
375 -- Allow new duplicates of this job
376 local sha1 = redis.call('hGet',KEYS[2],id)
377 if sha1 then redis.call('hDel',KEYS[3],sha1) end
378 redis.call('hDel',KEYS[2],id)
379 -- Mark the jobs as claimed and return it
380 redis.call('zAdd',KEYS[4],ARGV[1],id)
381 redis.call('hIncrBy',KEYS[5],id,1)
382 return redis.call('hGet',KEYS[6],id)
383 LUA;
384 return $conn->luaEval( $script,
385 array(
386 $this->getQueueKey( 'l-unclaimed' ), # KEYS[1]
387 $this->getQueueKey( 'h-sha1ById' ), # KEYS[2]
388 $this->getQueueKey( 'h-idBySha1' ), # KEYS[3]
389 $this->getQueueKey( 'z-claimed' ), # KEYS[4]
390 $this->getQueueKey( 'h-attempts' ), # KEYS[5]
391 $this->getQueueKey( 'h-data' ), # KEYS[6]
392 time(), # ARGV[1] (injected to be replication-safe)
394 6 # number of first argument(s) that are keys
399 * @see JobQueue::doAck()
400 * @param Job $job
401 * @return Job|bool
402 * @throws MWException
404 protected function doAck( Job $job ) {
405 if ( !isset( $job->metadata['uuid'] ) ) {
406 throw new MWException( "Job of type '{$job->getType()}' has no UUID." );
408 if ( $this->claimTTL > 0 ) {
409 $conn = $this->getConnection();
410 try {
411 static $script =
412 <<<LUA
413 -- Unmark the job as claimed
414 redis.call('zRem',KEYS[1],ARGV[1])
415 redis.call('hDel',KEYS[2],ARGV[1])
416 -- Delete the job data itself
417 return redis.call('hDel',KEYS[3],ARGV[1])
418 LUA;
419 $res = $conn->luaEval( $script,
420 array(
421 $this->getQueueKey( 'z-claimed' ), # KEYS[1]
422 $this->getQueueKey( 'h-attempts' ), # KEYS[2]
423 $this->getQueueKey( 'h-data' ), # KEYS[3]
424 $job->metadata['uuid'] # ARGV[1]
426 3 # number of first argument(s) that are keys
429 if ( !$res ) {
430 wfDebugLog( 'JobQueueRedis', "Could not acknowledge {$this->type} job." );
431 return false;
433 } catch ( RedisException $e ) {
434 $this->throwRedisException( $this->server, $conn, $e );
437 return true;
441 * @see JobQueue::doDeduplicateRootJob()
442 * @param Job $job
443 * @return bool
444 * @throws MWException
446 protected function doDeduplicateRootJob( Job $job ) {
447 if ( !$job->hasRootJobParams() ) {
448 throw new MWException( "Cannot register root job; missing parameters." );
450 $params = $job->getRootJobParams();
452 $key = $this->getRootJobCacheKey( $params['rootJobSignature'] );
454 $conn = $this->getConnection();
455 try {
456 $timestamp = $conn->get( $key ); // current last timestamp of this job
457 if ( $timestamp && $timestamp >= $params['rootJobTimestamp'] ) {
458 return true; // a newer version of this root job was enqueued
460 // Update the timestamp of the last root job started at the location...
461 return $conn->set( $key, $params['rootJobTimestamp'], self::ROOTJOB_TTL ); // 2 weeks
462 } catch ( RedisException $e ) {
463 $this->throwRedisException( $this->server, $conn, $e );
468 * @see JobQueue::doIsRootJobOldDuplicate()
469 * @param Job $job
470 * @return bool
472 protected function doIsRootJobOldDuplicate( Job $job ) {
473 if ( !$job->hasRootJobParams() ) {
474 return false; // job has no de-deplication info
476 $params = $job->getRootJobParams();
478 $conn = $this->getConnection();
479 try {
480 // Get the last time this root job was enqueued
481 $timestamp = $conn->get( $this->getRootJobCacheKey( $params['rootJobSignature'] ) );
482 } catch ( RedisException $e ) {
483 $this->throwRedisException( $this->server, $conn, $e );
486 // Check if a new root job was started at the location after this one's...
487 return ( $timestamp && $timestamp > $params['rootJobTimestamp'] );
491 * @see JobQueue::doDelete()
492 * @return bool
494 protected function doDelete() {
495 static $props = array( 'l-unclaimed', 'z-claimed', 'z-abandoned',
496 'z-delayed', 'h-idBySha1', 'h-sha1ById', 'h-attempts', 'h-data' );
498 $conn = $this->getConnection();
499 try {
500 $keys = array();
501 foreach ( $props as $prop ) {
502 $keys[] = $this->getQueueKey( $prop );
504 $res = ( $conn->delete( $keys ) !== false );
505 } catch ( RedisException $e ) {
506 $this->throwRedisException( $this->server, $conn, $e );
511 * @see JobQueue::getAllQueuedJobs()
512 * @return Iterator
514 public function getAllQueuedJobs() {
515 $conn = $this->getConnection();
516 try {
517 $that = $this;
518 return new MappedIterator(
519 $conn->lRange( $this->getQueueKey( 'l-unclaimed' ), 0, -1 ),
520 function( $uid ) use ( $that, $conn ) {
521 return $that->getJobFromUidInternal( $uid, $conn );
523 array( 'accept' => function ( $job ) { return is_object( $job ); } )
525 } catch ( RedisException $e ) {
526 $this->throwRedisException( $this->server, $conn, $e );
531 * @see JobQueue::getAllQueuedJobs()
532 * @return Iterator
534 public function getAllDelayedJobs() {
535 $conn = $this->getConnection();
536 try {
537 $that = $this;
538 return new MappedIterator( // delayed jobs
539 $conn->zRange( $this->getQueueKey( 'z-delayed' ), 0, -1 ),
540 function( $uid ) use ( $that, $conn ) {
541 return $that->getJobFromUidInternal( $uid, $conn );
543 array( 'accept' => function ( $job ) { return is_object( $job ); } )
545 } catch ( RedisException $e ) {
546 $this->throwRedisException( $this->server, $conn, $e );
551 * This function should not be called outside JobQueueRedis
553 * @param $uid string
554 * @param $conn RedisConnRef
555 * @return Job|bool Returns false if the job does not exist
556 * @throws MWException
558 public function getJobFromUidInternal( $uid, RedisConnRef $conn ) {
559 try {
560 $data = $conn->hGet( $this->getQueueKey( 'h-data' ), $uid );
561 if ( $data === false ) {
562 return false; // not found
564 $item = $this->unserialize( $conn->hGet( $this->getQueueKey( 'h-data' ), $uid ) );
565 if ( !is_array( $item ) ) { // this shouldn't happen
566 throw new MWException( "Could not find job with ID '$uid'." );
568 $title = Title::makeTitle( $item['namespace'], $item['title'] );
569 $job = Job::factory( $item['type'], $title, $item['params'] );
570 $job->metadata['uuid'] = $item['uuid'];
571 return $job;
572 } catch ( RedisException $e ) {
573 $this->throwRedisException( $this->server, $conn, $e );
578 * Release any ready delayed jobs into the queue
580 * @return integer Number of jobs released
581 * @throws MWException
583 public function releaseReadyDelayedJobs() {
584 $count = 0;
586 $conn = $this->getConnection();
587 try {
588 static $script =
589 <<<LUA
590 -- Get the list of ready delayed jobs, sorted by readiness
591 local ids = redis.call('zRangeByScore',KEYS[1],0,ARGV[1])
592 -- Migrate the jobs from the "delayed" set to the "unclaimed" list
593 for k,id in ipairs(ids) do
594 redis.call('lPush',KEYS[2],id)
595 redis.call('zRem',KEYS[1],id)
597 return #ids
598 LUA;
599 $count += (int)$conn->luaEval( $script,
600 array(
601 $this->getQueueKey( 'z-delayed' ), // KEYS[1]
602 $this->getQueueKey( 'l-unclaimed' ), // KEYS[2]
603 time() // ARGV[1]; max "delay until" UNIX timestamp
605 2 # first two arguments are keys
607 } catch ( RedisException $e ) {
608 $this->throwRedisException( $this->server, $conn, $e );
611 return $count;
615 * Recycle or destroy any jobs that have been claimed for too long
617 * @return integer Number of jobs recycled/deleted
618 * @throws MWException
620 public function recycleAndDeleteStaleJobs() {
621 if ( $this->claimTTL <= 0 ) { // sanity
622 throw new MWException( "Cannot recycle jobs since acknowledgements are disabled." );
624 $count = 0;
625 // For each job item that can be retried, we need to add it back to the
626 // main queue and remove it from the list of currenty claimed job items.
627 // For those that cannot, they are marked as dead and kept around for
628 // investigation and manual job restoration but are eventually deleted.
629 $conn = $this->getConnection();
630 try {
631 $now = time();
632 static $script =
633 <<<LUA
634 local released,abandoned,pruned = 0,0,0
635 -- Get all non-dead jobs that have an expired claim on them.
636 -- The score for each item is the last claim timestamp (UNIX).
637 local staleClaims = redis.call('zRangeByScore',KEYS[1],0,ARGV[1])
638 for k,id in ipairs(staleClaims) do
639 local timestamp = redis.call('zScore',KEYS[1],id)
640 local attempts = redis.call('hGet',KEYS[2],id)
641 if attempts < ARGV[3] then
642 -- Claim expired and retries left: re-enqueue the job
643 redis.call('lPush',KEYS[3],id)
644 redis.call('hIncrBy',KEYS[2],id,1)
645 released = released + 1
646 else
647 -- Claim expired and no retries left: mark the job as dead
648 redis.call('zAdd',KEYS[5],timestamp,id)
649 abandoned = abandoned + 1
651 redis.call('zRem',KEYS[1],id)
653 -- Get all of the dead jobs that have been marked as dead for too long.
654 -- The score for each item is the last claim timestamp (UNIX).
655 local deadClaims = redis.call('zRangeByScore',KEYS[5],0,ARGV[2])
656 for k,id in ipairs(deadClaims) do
657 -- Stale and out of retries: remove any traces of the job
658 redis.call('zRem',KEYS[5],id)
659 redis.call('hDel',KEYS[2],id)
660 redis.call('hDel',KEYS[4],id)
661 pruned = pruned + 1
663 return {released,abandoned,pruned}
664 LUA;
665 $res = $conn->luaEval( $script,
666 array(
667 $this->getQueueKey( 'z-claimed' ), # KEYS[1]
668 $this->getQueueKey( 'h-attempts' ), # KEYS[2]
669 $this->getQueueKey( 'l-unclaimed' ), # KEYS[3]
670 $this->getQueueKey( 'h-data' ), # KEYS[4]
671 $this->getQueueKey( 'z-abandoned' ), # KEYS[5]
672 $now - $this->claimTTL, # ARGV[1]
673 $now - self::MAX_AGE_PRUNE, # ARGV[2]
674 $this->maxTries # ARGV[3]
676 5 # number of first argument(s) that are keys
678 if ( $res ) {
679 list( $released, $abandoned, $pruned ) = $res;
680 $count += $released + $pruned;
681 JobQueue::incrStats( 'job-recycle', $this->type, $released );
682 JobQueue::incrStats( 'job-abandon', $this->type, $abandoned );
684 } catch ( RedisException $e ) {
685 $this->throwRedisException( $this->server, $conn, $e );
688 return $count;
692 * @return Array
694 protected function doGetPeriodicTasks() {
695 $tasks = array();
696 if ( $this->claimTTL > 0 ) {
697 $tasks['recycleAndDeleteStaleJobs'] = array(
698 'callback' => array( $this, 'recycleAndDeleteStaleJobs' ),
699 'period' => ceil( $this->claimTTL / 2 )
702 if ( $this->checkDelay ) {
703 $tasks['releaseReadyDelayedJobs'] = array(
704 'callback' => array( $this, 'releaseReadyDelayedJobs' ),
705 'period' => 300 // 5 minutes
708 return $tasks;
712 * @param $job Job
713 * @return array
715 protected function getNewJobFields( Job $job ) {
716 return array(
717 // Fields that describe the nature of the job
718 'type' => $job->getType(),
719 'namespace' => $job->getTitle()->getNamespace(),
720 'title' => $job->getTitle()->getDBkey(),
721 'params' => $job->getParams(),
722 // Some jobs cannot run until a "release timestamp"
723 'rtimestamp' => $job->getReleaseTimestamp() ?: 0,
724 // Additional job metadata
725 'uuid' => UIDGenerator::newRawUUIDv4( UIDGenerator::QUICK_RAND ),
726 'sha1' => $job->ignoreDuplicates()
727 ? wfBaseConvert( sha1( serialize( $job->getDeduplicationInfo() ) ), 16, 36, 31 )
728 : '',
729 'timestamp' => time() // UNIX timestamp
734 * @param $fields array
735 * @return Job|bool
737 protected function getJobFromFields( array $fields ) {
738 $title = Title::makeTitleSafe( $fields['namespace'], $fields['title'] );
739 if ( $title ) {
740 $job = Job::factory( $fields['type'], $title, $fields['params'] );
741 $job->metadata['uuid'] = $fields['uuid'];
742 return $job;
744 return false;
748 * @param array $fields
749 * @return string Serialized and possibly compressed version of $fields
751 protected function serialize( array $fields ) {
752 $blob = serialize( $fields );
753 if ( $this->compression === 'gzip'
754 && strlen( $blob ) >= 1024 && function_exists( 'gzdeflate' ) )
756 $object = (object)array( 'blob' => gzdeflate( $blob ), 'enc' => 'gzip' );
757 $blobz = serialize( $object );
758 return ( strlen( $blobz ) < strlen( $blob ) ) ? $blobz : $blob;
759 } else {
760 return $blob;
765 * @param string $blob
766 * @return array|bool Unserialized version of $blob or false
768 protected function unserialize( $blob ) {
769 $fields = unserialize( $blob );
770 if ( is_object( $fields ) ) {
771 if ( $fields->enc === 'gzip' && function_exists( 'gzinflate' ) ) {
772 $fields = unserialize( gzinflate( $fields->blob ) );
773 } else {
774 $fields = false;
777 return is_array( $fields ) ? $fields : false;
781 * Get a connection to the server that handles all sub-queues for this queue
783 * @return Array (server name, Redis instance)
784 * @throws MWException
786 protected function getConnection() {
787 $conn = $this->redisPool->getConnection( $this->server );
788 if ( !$conn ) {
789 throw new MWException( "Unable to connect to redis server." );
791 return $conn;
795 * @param $server string
796 * @param $conn RedisConnRef
797 * @param $e RedisException
798 * @throws MWException
800 protected function throwRedisException( $server, RedisConnRef $conn, $e ) {
801 $this->redisPool->handleException( $server, $conn, $e );
802 throw new MWException( "Redis server error: {$e->getMessage()}\n" );
806 * @param $prop string
807 * @return string
809 private function getQueueKey( $prop ) {
810 list( $db, $prefix ) = wfSplitWikiID( $this->wiki );
811 if ( strlen( $this->key ) ) { // namespaced queue (for testing)
812 return wfForeignMemcKey( $db, $prefix, 'jobqueue', $this->type, $this->key, $prop );
813 } else {
814 return wfForeignMemcKey( $db, $prefix, 'jobqueue', $this->type, $prop );
819 * @param $key string
820 * @return void
822 public function setTestingPrefix( $key ) {
823 $this->key = $key;