thumb_handler.php doesn't seem to extract path_info correctly
[mediawiki.git] / includes / job / JobQueueRedis.php
blob1f5b7619bba2cb4c14c5f170d9b51bd58b9a6e49
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 );
524 } catch ( RedisException $e ) {
525 $this->throwRedisException( $this->server, $conn, $e );
530 * @see JobQueue::getAllQueuedJobs()
531 * @return Iterator
533 public function getAllDelayedJobs() {
534 $conn = $this->getConnection();
535 try {
536 $that = $this;
537 return new MappedIterator( // delayed jobs
538 $conn->zRange( $this->getQueueKey( 'z-delayed' ), 0, -1 ),
539 function( $uid ) use ( $that, $conn ) {
540 return $that->getJobFromUidInternal( $uid, $conn );
543 } catch ( RedisException $e ) {
544 $this->throwRedisException( $this->server, $conn, $e );
549 * This function should not be called outside JobQueueRedis
551 * @param $uid string
552 * @param $conn RedisConnRef
553 * @return Job
554 * @throws MWException
556 public function getJobFromUidInternal( $uid, RedisConnRef $conn ) {
557 try {
558 $item = $this->unserialize( $conn->hGet( $this->getQueueKey( 'h-data' ), $uid ) );
559 if ( !is_array( $item ) ) { // this shouldn't happen
560 throw new MWException( "Could not find job with ID '$uid'." );
562 $title = Title::makeTitle( $item['namespace'], $item['title'] );
563 $job = Job::factory( $item['type'], $title, $item['params'] );
564 $job->metadata['uuid'] = $item['uuid'];
565 return $job;
566 } catch ( RedisException $e ) {
567 $this->throwRedisException( $this->server, $conn, $e );
572 * Release any ready delayed jobs into the queue
574 * @return integer Number of jobs released
575 * @throws MWException
577 public function releaseReadyDelayedJobs() {
578 $count = 0;
580 $conn = $this->getConnection();
581 try {
582 static $script =
583 <<<LUA
584 -- Get the list of ready delayed jobs, sorted by readiness
585 local ids = redis.call('zRangeByScore',KEYS[1],0,ARGV[1])
586 -- Migrate the jobs from the "delayed" set to the "unclaimed" list
587 for k,id in ipairs(ids) do
588 redis.call('lPush',KEYS[2],id)
589 redis.call('zRem',KEYS[1],id)
591 return #ids
592 LUA;
593 $count += (int)$conn->luaEval( $script,
594 array(
595 $this->getQueueKey( 'z-delayed' ), // KEYS[1]
596 $this->getQueueKey( 'l-unclaimed' ), // KEYS[2]
597 time() // ARGV[1]; max "delay until" UNIX timestamp
599 2 # first two arguments are keys
601 } catch ( RedisException $e ) {
602 $this->throwRedisException( $this->server, $conn, $e );
605 return $count;
609 * Recycle or destroy any jobs that have been claimed for too long
611 * @return integer Number of jobs recycled/deleted
612 * @throws MWException
614 public function recycleAndDeleteStaleJobs() {
615 if ( $this->claimTTL <= 0 ) { // sanity
616 throw new MWException( "Cannot recycle jobs since acknowledgements are disabled." );
618 $count = 0;
619 // For each job item that can be retried, we need to add it back to the
620 // main queue and remove it from the list of currenty claimed job items.
621 // For those that cannot, they are marked as dead and kept around for
622 // investigation and manual job restoration but are eventually deleted.
623 $conn = $this->getConnection();
624 try {
625 $now = time();
626 static $script =
627 <<<LUA
628 local released,abandoned,pruned = 0,0,0
629 -- Get all non-dead jobs that have an expired claim on them.
630 -- The score for each item is the last claim timestamp (UNIX).
631 local staleClaims = redis.call('zRangeByScore',KEYS[1],0,ARGV[1])
632 for k,id in ipairs(staleClaims) do
633 local timestamp = redis.call('zScore',KEYS[1],id)
634 local attempts = redis.call('hGet',KEYS[2],id)
635 if attempts < ARGV[3] then
636 -- Claim expired and retries left: re-enqueue the job
637 redis.call('lPush',KEYS[3],id)
638 redis.call('hIncrBy',KEYS[2],id,1)
639 released = released + 1
640 else
641 -- Claim expired and no retries left: mark the job as dead
642 redis.call('zAdd',KEYS[5],timestamp,id)
643 abandoned = abandoned + 1
645 redis.call('zRem',KEYS[1],id)
647 -- Get all of the dead jobs that have been marked as dead for too long.
648 -- The score for each item is the last claim timestamp (UNIX).
649 local deadClaims = redis.call('zRangeByScore',KEYS[5],0,ARGV[2])
650 for k,id in ipairs(deadClaims) do
651 -- Stale and out of retries: remove any traces of the job
652 redis.call('zRem',KEYS[5],id)
653 redis.call('hDel',KEYS[2],id)
654 redis.call('hDel',KEYS[4],id)
655 pruned = pruned + 1
657 return {released,abandoned,pruned}
658 LUA;
659 $res = $conn->luaEval( $script,
660 array(
661 $this->getQueueKey( 'z-claimed' ), # KEYS[1]
662 $this->getQueueKey( 'h-attempts' ), # KEYS[2]
663 $this->getQueueKey( 'l-unclaimed' ), # KEYS[3]
664 $this->getQueueKey( 'h-data' ), # KEYS[4]
665 $this->getQueueKey( 'z-abandoned' ), # KEYS[5]
666 $now - $this->claimTTL, # ARGV[1]
667 $now - self::MAX_AGE_PRUNE, # ARGV[2]
668 $this->maxTries # ARGV[3]
670 5 # number of first argument(s) that are keys
672 if ( $res ) {
673 list( $released, $abandoned, $pruned ) = $res;
674 $count += $released + $pruned;
675 JobQueue::incrStats( 'job-recycle', $this->type, $released );
676 JobQueue::incrStats( 'job-abandon', $this->type, $abandoned );
678 } catch ( RedisException $e ) {
679 $this->throwRedisException( $this->server, $conn, $e );
682 return $count;
686 * @return Array
688 protected function doGetPeriodicTasks() {
689 $tasks = array();
690 if ( $this->claimTTL > 0 ) {
691 $tasks['recycleAndDeleteStaleJobs'] = array(
692 'callback' => array( $this, 'recycleAndDeleteStaleJobs' ),
693 'period' => ceil( $this->claimTTL / 2 )
696 if ( $this->checkDelay ) {
697 $tasks['releaseReadyDelayedJobs'] = array(
698 'callback' => array( $this, 'releaseReadyDelayedJobs' ),
699 'period' => 300 // 5 minutes
702 return $tasks;
706 * @param $job Job
707 * @return array
709 protected function getNewJobFields( Job $job ) {
710 return array(
711 // Fields that describe the nature of the job
712 'type' => $job->getType(),
713 'namespace' => $job->getTitle()->getNamespace(),
714 'title' => $job->getTitle()->getDBkey(),
715 'params' => $job->getParams(),
716 // Some jobs cannot run until a "release timestamp"
717 'rtimestamp' => $job->getReleaseTimestamp() ?: 0,
718 // Additional job metadata
719 'uuid' => UIDGenerator::newRawUUIDv4( UIDGenerator::QUICK_RAND ),
720 'sha1' => $job->ignoreDuplicates()
721 ? wfBaseConvert( sha1( serialize( $job->getDeduplicationInfo() ) ), 16, 36, 31 )
722 : '',
723 'timestamp' => time() // UNIX timestamp
728 * @param $fields array
729 * @return Job|bool
731 protected function getJobFromFields( array $fields ) {
732 $title = Title::makeTitleSafe( $fields['namespace'], $fields['title'] );
733 if ( $title ) {
734 $job = Job::factory( $fields['type'], $title, $fields['params'] );
735 $job->metadata['uuid'] = $fields['uuid'];
736 return $job;
738 return false;
742 * @param array $fields
743 * @return string Serialized and possibly compressed version of $fields
745 protected function serialize( array $fields ) {
746 $blob = serialize( $fields );
747 if ( $this->compression === 'gzip'
748 && strlen( $blob ) >= 1024 && function_exists( 'gzdeflate' ) )
750 $object = (object)array( 'blob' => gzdeflate( $blob ), 'enc' => 'gzip' );
751 $blobz = serialize( $object );
752 return ( strlen( $blobz ) < strlen( $blob ) ) ? $blobz : $blob;
753 } else {
754 return $blob;
759 * @param string $blob
760 * @return array|bool Unserialized version of $blob or false
762 protected function unserialize( $blob ) {
763 $fields = unserialize( $blob );
764 if ( is_object( $fields ) ) {
765 if ( $fields->enc === 'gzip' && function_exists( 'gzinflate' ) ) {
766 $fields = unserialize( gzinflate( $fields->blob ) );
767 } else {
768 $fields = false;
771 return is_array( $fields ) ? $fields : false;
775 * Get a connection to the server that handles all sub-queues for this queue
777 * @return Array (server name, Redis instance)
778 * @throws MWException
780 protected function getConnection() {
781 $conn = $this->redisPool->getConnection( $this->server );
782 if ( !$conn ) {
783 throw new MWException( "Unable to connect to redis server." );
785 return $conn;
789 * @param $server string
790 * @param $conn RedisConnRef
791 * @param $e RedisException
792 * @throws MWException
794 protected function throwRedisException( $server, RedisConnRef $conn, $e ) {
795 $this->redisPool->handleException( $server, $conn, $e );
796 throw new MWException( "Redis server error: {$e->getMessage()}\n" );
800 * @param $prop string
801 * @return string
803 private function getQueueKey( $prop ) {
804 list( $db, $prefix ) = wfSplitWikiID( $this->wiki );
805 if ( strlen( $this->key ) ) { // namespaced queue (for testing)
806 return wfForeignMemcKey( $db, $prefix, 'jobqueue', $this->type, $this->key, $prop );
807 } else {
808 return wfForeignMemcKey( $db, $prefix, 'jobqueue', $this->type, $prop );
813 * @param $key string
814 * @return void
816 public function setTestingPrefix( $key ) {
817 $this->key = $key;