Merge "Allow server selection when running sql.php"
[lhc/web/wiklou.git] / includes / job / JobQueueRedis.php
1 <?php
2 /**
3 * Redis-backed job queue code.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 * @author Aaron Schulz
22 */
23
24 /**
25 * Class to handle job queues stored in Redis
26 *
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.
29 *
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.
45 *
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.
49 *
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.
54 *
55 * @ingroup JobQueue
56 * @ingroup Redis
57 * @since 1.22
58 */
59 class JobQueueRedis extends JobQueue {
60 /** @var RedisConnectionPool */
61 protected $redisPool;
62
63 protected $server; // string; server address
64 protected $compression; // string; compression method to use
65
66 const MAX_AGE_PRUNE = 604800; // integer; seconds a job can live once claimed (7 days)
67
68 protected $key; // string; key to prefix the queue keys with (used for testing)
69
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
79 */
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'] );
86 }
87
88 protected function supportedOrders() {
89 return array( 'timestamp', 'fifo' );
90 }
91
92 protected function optimalOrder() {
93 return 'fifo';
94 }
95
96 protected function supportsDelayedJobs() {
97 return true;
98 }
99
100 /**
101 * @see JobQueue::doIsEmpty()
102 * @return bool
103 * @throws MWException
104 */
105 protected function doIsEmpty() {
106 return $this->doGetSize() == 0;
107 }
108
109 /**
110 * @see JobQueue::doGetSize()
111 * @return integer
112 * @throws MWException
113 */
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 );
120 }
121 }
122
123 /**
124 * @see JobQueue::doGetAcquiredCount()
125 * @return integer
126 * @throws MWException
127 */
128 protected function doGetAcquiredCount() {
129 if ( $this->claimTTL <= 0 ) {
130 return 0; // no acknowledgements
131 }
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 );
140 }
141 }
142
143 /**
144 * @see JobQueue::doGetDelayedCount()
145 * @return integer
146 * @throws MWException
147 */
148 protected function doGetDelayedCount() {
149 if ( !$this->checkDelay ) {
150 return 0; // no delayed jobs
151 }
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 );
157 }
158 }
159
160 /**
161 * @see JobQueue::doGetAbandonedCount()
162 * @return integer
163 * @throws MWException
164 */
165 protected function doGetAbandonedCount() {
166 if ( $this->claimTTL <= 0 ) {
167 return 0; // no acknowledgements
168 }
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 );
174 }
175 }
176
177 /**
178 * @see JobQueue::doBatchPush()
179 * @param array $jobs
180 * @param $flags
181 * @return bool
182 * @throws MWException
183 */
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;
193 }
194 }
195
196 if ( !count( $items ) ) {
197 return true; // nothing to do
198 }
199
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
207 }
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 );
216 }
217 }
218 if ( $failed > 0 ) {
219 wfDebugLog( 'JobQueueRedis', "Could not insert {$failed} {$this->type} job(s)." );
220 return false;
221 }
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 );
227 }
228
229 return true;
230 }
231
232 /**
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
237 */
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 );
245 }
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)
259 end
260 if sha1 ~= '' then
261 redis.call('hSet',KEYS[2],id,sha1)
262 redis.call('hSet',KEYS[3],sha1,id)
263 end
264 redis.call('hSet',KEYS[5],id,blob)
265 pushed = pushed + 1
266 end
267 end
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]
278 ),
279 $args
280 ),
281 5 # number of first argument(s) that are keys
282 );
283 }
284
285 /**
286 * @see JobQueue::doPop()
287 * @return Job|bool
288 * @throws MWException
289 */
290 protected function doPop() {
291 $job = false;
292
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();
297 }
298
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();
306 }
307 $blob = $this->popAndAcquireBlob( $conn );
308 } else {
309 $blob = $this->popAndDeleteBlob( $conn );
310 }
311 if ( $blob === false ) {
312 break; // no jobs; nothing to do
313 }
314
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;
320 }
321
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 );
327 }
328
329 return $job;
330 }
331
332 /**
333 * @param RedisConnRef $conn
334 * @return array serialized string or false
335 * @throws RedisException
336 */
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]
359 ),
360 4 # number of first argument(s) that are keys
361 );
362 }
363
364 /**
365 * @param RedisConnRef $conn
366 * @return array serialized string or false
367 * @throws RedisException
368 */
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)
393 ),
394 6 # number of first argument(s) that are keys
395 );
396 }
397
398 /**
399 * @see JobQueue::doAck()
400 * @param Job $job
401 * @return Job|bool
402 * @throws MWException
403 */
404 protected function doAck( Job $job ) {
405 if ( !isset( $job->metadata['uuid'] ) ) {
406 throw new MWException( "Job of type '{$job->getType()}' has no UUID." );
407 }
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]
425 ),
426 3 # number of first argument(s) that are keys
427 );
428
429 if ( !$res ) {
430 wfDebugLog( 'JobQueueRedis', "Could not acknowledge {$this->type} job." );
431 return false;
432 }
433 } catch ( RedisException $e ) {
434 $this->throwRedisException( $this->server, $conn, $e );
435 }
436 }
437 return true;
438 }
439
440 /**
441 * @see JobQueue::doDeduplicateRootJob()
442 * @param Job $job
443 * @return bool
444 * @throws MWException
445 */
446 protected function doDeduplicateRootJob( Job $job ) {
447 if ( !$job->hasRootJobParams() ) {
448 throw new MWException( "Cannot register root job; missing parameters." );
449 }
450 $params = $job->getRootJobParams();
451
452 $key = $this->getRootJobCacheKey( $params['rootJobSignature'] );
453
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
459 }
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 );
464 }
465 }
466
467 /**
468 * @see JobQueue::doIsRootJobOldDuplicate()
469 * @param Job $job
470 * @return bool
471 */
472 protected function doIsRootJobOldDuplicate( Job $job ) {
473 if ( !$job->hasRootJobParams() ) {
474 return false; // job has no de-deplication info
475 }
476 $params = $job->getRootJobParams();
477
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 );
484 }
485
486 // Check if a new root job was started at the location after this one's...
487 return ( $timestamp && $timestamp > $params['rootJobTimestamp'] );
488 }
489
490 /**
491 * @see JobQueue::doDelete()
492 * @return bool
493 */
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' );
497
498 $conn = $this->getConnection();
499 try {
500 $keys = array();
501 foreach ( $props as $prop ) {
502 $keys[] = $this->getQueueKey( $prop );
503 }
504 $res = ( $conn->delete( $keys ) !== false );
505 } catch ( RedisException $e ) {
506 $this->throwRedisException( $this->server, $conn, $e );
507 }
508 }
509
510 /**
511 * @see JobQueue::getAllQueuedJobs()
512 * @return Iterator
513 */
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 );
522 }
523 );
524 } catch ( RedisException $e ) {
525 $this->throwRedisException( $this->server, $conn, $e );
526 }
527 }
528
529 /**
530 * @see JobQueue::getAllQueuedJobs()
531 * @return Iterator
532 */
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 );
541 }
542 );
543 } catch ( RedisException $e ) {
544 $this->throwRedisException( $this->server, $conn, $e );
545 }
546 }
547
548 /**
549 * This function should not be called outside JobQueueRedis
550 *
551 * @param $uid string
552 * @param $conn RedisConnRef
553 * @return Job
554 * @throws MWException
555 */
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'." );
561 }
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 );
568 }
569 }
570
571 /**
572 * Release any ready delayed jobs into the queue
573 *
574 * @return integer Number of jobs released
575 * @throws MWException
576 */
577 public function releaseReadyDelayedJobs() {
578 $count = 0;
579
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)
590 end
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
598 ),
599 2 # first two arguments are keys
600 );
601 } catch ( RedisException $e ) {
602 $this->throwRedisException( $this->server, $conn, $e );
603 }
604
605 return $count;
606 }
607
608 /**
609 * Recycle or destroy any jobs that have been claimed for too long
610 *
611 * @return integer Number of jobs recycled/deleted
612 * @throws MWException
613 */
614 public function recycleAndDeleteStaleJobs() {
615 if ( $this->claimTTL <= 0 ) { // sanity
616 throw new MWException( "Cannot recycle jobs since acknowledgements are disabled." );
617 }
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
644 end
645 redis.call('zRem',KEYS[1],id)
646 end
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
656 end
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]
669 ),
670 5 # number of first argument(s) that are keys
671 );
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 );
677 }
678 } catch ( RedisException $e ) {
679 $this->throwRedisException( $this->server, $conn, $e );
680 }
681
682 return $count;
683 }
684
685 /**
686 * @return Array
687 */
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 )
694 );
695 }
696 if ( $this->checkDelay ) {
697 $tasks['releaseReadyDelayedJobs'] = array(
698 'callback' => array( $this, 'releaseReadyDelayedJobs' ),
699 'period' => 300 // 5 minutes
700 );
701 }
702 return $tasks;
703 }
704
705 /**
706 * @param $job Job
707 * @return array
708 */
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
724 );
725 }
726
727 /**
728 * @param $fields array
729 * @return Job|bool
730 */
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;
737 }
738 return false;
739 }
740
741 /**
742 * @param array $fields
743 * @return string Serialized and possibly compressed version of $fields
744 */
745 protected function serialize( array $fields ) {
746 $blob = serialize( $fields );
747 if ( $this->compression === 'gzip'
748 && strlen( $blob ) >= 1024 && function_exists( 'gzdeflate' ) )
749 {
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;
755 }
756 }
757
758 /**
759 * @param string $blob
760 * @return array|bool Unserialized version of $blob or false
761 */
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;
769 }
770 }
771 return is_array( $fields ) ? $fields : false;
772 }
773
774 /**
775 * Get a connection to the server that handles all sub-queues for this queue
776 *
777 * @return Array (server name, Redis instance)
778 * @throws MWException
779 */
780 protected function getConnection() {
781 $conn = $this->redisPool->getConnection( $this->server );
782 if ( !$conn ) {
783 throw new MWException( "Unable to connect to redis server." );
784 }
785 return $conn;
786 }
787
788 /**
789 * @param $server string
790 * @param $conn RedisConnRef
791 * @param $e RedisException
792 * @throws MWException
793 */
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" );
797 }
798
799 /**
800 * @param $prop string
801 * @return string
802 */
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 );
809 }
810 }
811
812 /**
813 * @param $key string
814 * @return void
815 */
816 public function setTestingPrefix( $key ) {
817 $this->key = $key;
818 }
819 }