Merge "Add method parameter type documentation"
[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 return ( $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 array( 'accept' => function ( $job ) { return is_object( $job ); } )
524 );
525 } catch ( RedisException $e ) {
526 $this->throwRedisException( $this->server, $conn, $e );
527 }
528 }
529
530 /**
531 * @see JobQueue::getAllQueuedJobs()
532 * @return Iterator
533 */
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 );
542 },
543 array( 'accept' => function ( $job ) { return is_object( $job ); } )
544 );
545 } catch ( RedisException $e ) {
546 $this->throwRedisException( $this->server, $conn, $e );
547 }
548 }
549
550 public function getCoalesceLocationInternal() {
551 return "RedisServer:" . $this->server;
552 }
553
554 protected function doGetSiblingQueuesWithJobs( array $types ) {
555 return array_keys( array_filter( $this->doGetSiblingQueueSizes( $types ) ) );
556 }
557
558 protected function doGetSiblingQueueSizes( array $types ) {
559 $sizes = array(); // (type => size)
560 $types = array_values( $types ); // reindex
561 try {
562 $conn = $this->getConnection();
563 $conn->multi( Redis::PIPELINE );
564 foreach ( $types as $type ) {
565 $conn->lSize( $this->getQueueKey( 'l-unclaimed', $type ) );
566 }
567 $res = $conn->exec();
568 if ( is_array( $res ) ) {
569 foreach ( $res as $i => $size ) {
570 $sizes[$types[$i]] = $size;
571 }
572 }
573 } catch ( RedisException $e ) {
574 $this->throwRedisException( $this->server, $conn, $e );
575 }
576 return $sizes;
577 }
578
579 /**
580 * This function should not be called outside JobQueueRedis
581 *
582 * @param $uid string
583 * @param $conn RedisConnRef
584 * @return Job|bool Returns false if the job does not exist
585 * @throws MWException
586 */
587 public function getJobFromUidInternal( $uid, RedisConnRef $conn ) {
588 try {
589 $data = $conn->hGet( $this->getQueueKey( 'h-data' ), $uid );
590 if ( $data === false ) {
591 return false; // not found
592 }
593 $item = $this->unserialize( $conn->hGet( $this->getQueueKey( 'h-data' ), $uid ) );
594 if ( !is_array( $item ) ) { // this shouldn't happen
595 throw new MWException( "Could not find job with ID '$uid'." );
596 }
597 $title = Title::makeTitle( $item['namespace'], $item['title'] );
598 $job = Job::factory( $item['type'], $title, $item['params'] );
599 $job->metadata['uuid'] = $item['uuid'];
600 return $job;
601 } catch ( RedisException $e ) {
602 $this->throwRedisException( $this->server, $conn, $e );
603 }
604 }
605
606 /**
607 * Release any ready delayed jobs into the queue
608 *
609 * @return integer Number of jobs released
610 * @throws MWException
611 */
612 public function releaseReadyDelayedJobs() {
613 $count = 0;
614
615 $conn = $this->getConnection();
616 try {
617 static $script =
618 <<<LUA
619 -- Get the list of ready delayed jobs, sorted by readiness
620 local ids = redis.call('zRangeByScore',KEYS[1],0,ARGV[1])
621 -- Migrate the jobs from the "delayed" set to the "unclaimed" list
622 for k,id in ipairs(ids) do
623 redis.call('lPush',KEYS[2],id)
624 redis.call('zRem',KEYS[1],id)
625 end
626 return #ids
627 LUA;
628 $count += (int)$conn->luaEval( $script,
629 array(
630 $this->getQueueKey( 'z-delayed' ), // KEYS[1]
631 $this->getQueueKey( 'l-unclaimed' ), // KEYS[2]
632 time() // ARGV[1]; max "delay until" UNIX timestamp
633 ),
634 2 # first two arguments are keys
635 );
636 } catch ( RedisException $e ) {
637 $this->throwRedisException( $this->server, $conn, $e );
638 }
639
640 return $count;
641 }
642
643 /**
644 * Recycle or destroy any jobs that have been claimed for too long
645 *
646 * @return integer Number of jobs recycled/deleted
647 * @throws MWException
648 */
649 public function recycleAndDeleteStaleJobs() {
650 if ( $this->claimTTL <= 0 ) { // sanity
651 throw new MWException( "Cannot recycle jobs since acknowledgements are disabled." );
652 }
653 $count = 0;
654 // For each job item that can be retried, we need to add it back to the
655 // main queue and remove it from the list of currenty claimed job items.
656 // For those that cannot, they are marked as dead and kept around for
657 // investigation and manual job restoration but are eventually deleted.
658 $conn = $this->getConnection();
659 try {
660 $now = time();
661 static $script =
662 <<<LUA
663 local released,abandoned,pruned = 0,0,0
664 -- Get all non-dead jobs that have an expired claim on them.
665 -- The score for each item is the last claim timestamp (UNIX).
666 local staleClaims = redis.call('zRangeByScore',KEYS[1],0,ARGV[1])
667 for k,id in ipairs(staleClaims) do
668 local timestamp = redis.call('zScore',KEYS[1],id)
669 local attempts = redis.call('hGet',KEYS[2],id)
670 if attempts < ARGV[3] then
671 -- Claim expired and retries left: re-enqueue the job
672 redis.call('lPush',KEYS[3],id)
673 redis.call('hIncrBy',KEYS[2],id,1)
674 released = released + 1
675 else
676 -- Claim expired and no retries left: mark the job as dead
677 redis.call('zAdd',KEYS[5],timestamp,id)
678 abandoned = abandoned + 1
679 end
680 redis.call('zRem',KEYS[1],id)
681 end
682 -- Get all of the dead jobs that have been marked as dead for too long.
683 -- The score for each item is the last claim timestamp (UNIX).
684 local deadClaims = redis.call('zRangeByScore',KEYS[5],0,ARGV[2])
685 for k,id in ipairs(deadClaims) do
686 -- Stale and out of retries: remove any traces of the job
687 redis.call('zRem',KEYS[5],id)
688 redis.call('hDel',KEYS[2],id)
689 redis.call('hDel',KEYS[4],id)
690 pruned = pruned + 1
691 end
692 return {released,abandoned,pruned}
693 LUA;
694 $res = $conn->luaEval( $script,
695 array(
696 $this->getQueueKey( 'z-claimed' ), # KEYS[1]
697 $this->getQueueKey( 'h-attempts' ), # KEYS[2]
698 $this->getQueueKey( 'l-unclaimed' ), # KEYS[3]
699 $this->getQueueKey( 'h-data' ), # KEYS[4]
700 $this->getQueueKey( 'z-abandoned' ), # KEYS[5]
701 $now - $this->claimTTL, # ARGV[1]
702 $now - self::MAX_AGE_PRUNE, # ARGV[2]
703 $this->maxTries # ARGV[3]
704 ),
705 5 # number of first argument(s) that are keys
706 );
707 if ( $res ) {
708 list( $released, $abandoned, $pruned ) = $res;
709 $count += $released + $pruned;
710 JobQueue::incrStats( 'job-recycle', $this->type, $released );
711 JobQueue::incrStats( 'job-abandon', $this->type, $abandoned );
712 }
713 } catch ( RedisException $e ) {
714 $this->throwRedisException( $this->server, $conn, $e );
715 }
716
717 return $count;
718 }
719
720 /**
721 * @return Array
722 */
723 protected function doGetPeriodicTasks() {
724 $tasks = array();
725 if ( $this->claimTTL > 0 ) {
726 $tasks['recycleAndDeleteStaleJobs'] = array(
727 'callback' => array( $this, 'recycleAndDeleteStaleJobs' ),
728 'period' => ceil( $this->claimTTL / 2 )
729 );
730 }
731 if ( $this->checkDelay ) {
732 $tasks['releaseReadyDelayedJobs'] = array(
733 'callback' => array( $this, 'releaseReadyDelayedJobs' ),
734 'period' => 300 // 5 minutes
735 );
736 }
737 return $tasks;
738 }
739
740 /**
741 * @param $job Job
742 * @return array
743 */
744 protected function getNewJobFields( Job $job ) {
745 return array(
746 // Fields that describe the nature of the job
747 'type' => $job->getType(),
748 'namespace' => $job->getTitle()->getNamespace(),
749 'title' => $job->getTitle()->getDBkey(),
750 'params' => $job->getParams(),
751 // Some jobs cannot run until a "release timestamp"
752 'rtimestamp' => $job->getReleaseTimestamp() ?: 0,
753 // Additional job metadata
754 'uuid' => UIDGenerator::newRawUUIDv4( UIDGenerator::QUICK_RAND ),
755 'sha1' => $job->ignoreDuplicates()
756 ? wfBaseConvert( sha1( serialize( $job->getDeduplicationInfo() ) ), 16, 36, 31 )
757 : '',
758 'timestamp' => time() // UNIX timestamp
759 );
760 }
761
762 /**
763 * @param $fields array
764 * @return Job|bool
765 */
766 protected function getJobFromFields( array $fields ) {
767 $title = Title::makeTitleSafe( $fields['namespace'], $fields['title'] );
768 if ( $title ) {
769 $job = Job::factory( $fields['type'], $title, $fields['params'] );
770 $job->metadata['uuid'] = $fields['uuid'];
771 return $job;
772 }
773 return false;
774 }
775
776 /**
777 * @param array $fields
778 * @return string Serialized and possibly compressed version of $fields
779 */
780 protected function serialize( array $fields ) {
781 $blob = serialize( $fields );
782 if ( $this->compression === 'gzip'
783 && strlen( $blob ) >= 1024 && function_exists( 'gzdeflate' ) )
784 {
785 $object = (object)array( 'blob' => gzdeflate( $blob ), 'enc' => 'gzip' );
786 $blobz = serialize( $object );
787 return ( strlen( $blobz ) < strlen( $blob ) ) ? $blobz : $blob;
788 } else {
789 return $blob;
790 }
791 }
792
793 /**
794 * @param string $blob
795 * @return array|bool Unserialized version of $blob or false
796 */
797 protected function unserialize( $blob ) {
798 $fields = unserialize( $blob );
799 if ( is_object( $fields ) ) {
800 if ( $fields->enc === 'gzip' && function_exists( 'gzinflate' ) ) {
801 $fields = unserialize( gzinflate( $fields->blob ) );
802 } else {
803 $fields = false;
804 }
805 }
806 return is_array( $fields ) ? $fields : false;
807 }
808
809 /**
810 * Get a connection to the server that handles all sub-queues for this queue
811 *
812 * @return Array (server name, Redis instance)
813 * @throws MWException
814 */
815 protected function getConnection() {
816 $conn = $this->redisPool->getConnection( $this->server );
817 if ( !$conn ) {
818 throw new JobQueueConnectionError( "Unable to connect to redis server." );
819 }
820 return $conn;
821 }
822
823 /**
824 * @param $server string
825 * @param $conn RedisConnRef
826 * @param $e RedisException
827 * @throws MWException
828 */
829 protected function throwRedisException( $server, RedisConnRef $conn, $e ) {
830 $this->redisPool->handleException( $server, $conn, $e );
831 throw new JobQueueError( "Redis server error: {$e->getMessage()}\n" );
832 }
833
834 /**
835 * @param $prop string
836 * @param $type string|null
837 * @return string
838 */
839 private function getQueueKey( $prop, $type = null ) {
840 $type = is_string( $type ) ? $type : $this->type;
841 list( $db, $prefix ) = wfSplitWikiID( $this->wiki );
842 if ( strlen( $this->key ) ) { // namespaced queue (for testing)
843 return wfForeignMemcKey( $db, $prefix, 'jobqueue', $type, $this->key, $prop );
844 } else {
845 return wfForeignMemcKey( $db, $prefix, 'jobqueue', $type, $prop );
846 }
847 }
848
849 /**
850 * @param $key string
851 * @return void
852 */
853 public function setTestingPrefix( $key ) {
854 $this->key = $key;
855 }
856 }