Update documentation for job related classes
[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 /** @var string Server address */
64 protected $server;
65
66 /** @var string Compression method to use */
67 protected $compression;
68
69 const MAX_AGE_PRUNE = 604800; // integer; seconds a job can live once claimed (7 days)
70
71 /** @var string Key to prefix the queue keys with (used for testing) */
72 protected $key;
73
74 /**
75 * @params include:
76 * - redisConfig : An array of parameters to RedisConnectionPool::__construct().
77 * Note that the serializer option is ignored as "none" is always used.
78 * - redisServer : A hostname/port combination or the absolute path of a UNIX socket.
79 * If a hostname is specified but no port, the standard port number
80 * 6379 will be used. Required.
81 * - compression : The type of compression to use; one of (none,gzip).
82 * @param array $params
83 */
84 public function __construct( array $params ) {
85 parent::__construct( $params );
86 $params['redisConfig']['serializer'] = 'none'; // make it easy to use Lua
87 $this->server = $params['redisServer'];
88 $this->compression = isset( $params['compression'] ) ? $params['compression'] : 'none';
89 $this->redisPool = RedisConnectionPool::singleton( $params['redisConfig'] );
90 }
91
92 protected function supportedOrders() {
93 return array( 'timestamp', 'fifo' );
94 }
95
96 protected function optimalOrder() {
97 return 'fifo';
98 }
99
100 protected function supportsDelayedJobs() {
101 return true;
102 }
103
104 /**
105 * @see JobQueue::doIsEmpty()
106 * @return bool
107 * @throws MWException
108 */
109 protected function doIsEmpty() {
110 return $this->doGetSize() == 0;
111 }
112
113 /**
114 * @see JobQueue::doGetSize()
115 * @return int
116 * @throws MWException
117 */
118 protected function doGetSize() {
119 $conn = $this->getConnection();
120 try {
121 return $conn->lSize( $this->getQueueKey( 'l-unclaimed' ) );
122 } catch ( RedisException $e ) {
123 $this->throwRedisException( $this->server, $conn, $e );
124 }
125 }
126
127 /**
128 * @see JobQueue::doGetAcquiredCount()
129 * @return int
130 * @throws JobQueueError
131 */
132 protected function doGetAcquiredCount() {
133 if ( $this->claimTTL <= 0 ) {
134 return 0; // no acknowledgements
135 }
136 $conn = $this->getConnection();
137 try {
138 $conn->multi( Redis::PIPELINE );
139 $conn->zSize( $this->getQueueKey( 'z-claimed' ) );
140 $conn->zSize( $this->getQueueKey( 'z-abandoned' ) );
141
142 return array_sum( $conn->exec() );
143 } catch ( RedisException $e ) {
144 $this->throwRedisException( $this->server, $conn, $e );
145 }
146 }
147
148 /**
149 * @see JobQueue::doGetDelayedCount()
150 * @return int
151 * @throws JobQueueError
152 */
153 protected function doGetDelayedCount() {
154 if ( !$this->checkDelay ) {
155 return 0; // no delayed jobs
156 }
157 $conn = $this->getConnection();
158 try {
159 return $conn->zSize( $this->getQueueKey( 'z-delayed' ) );
160 } catch ( RedisException $e ) {
161 $this->throwRedisException( $this->server, $conn, $e );
162 }
163 }
164
165 /**
166 * @see JobQueue::doGetAbandonedCount()
167 * @return int
168 * @throws JobQueueError
169 */
170 protected function doGetAbandonedCount() {
171 if ( $this->claimTTL <= 0 ) {
172 return 0; // no acknowledgements
173 }
174 $conn = $this->getConnection();
175 try {
176 return $conn->zSize( $this->getQueueKey( 'z-abandoned' ) );
177 } catch ( RedisException $e ) {
178 $this->throwRedisException( $this->server, $conn, $e );
179 }
180 }
181
182 /**
183 * @see JobQueue::doBatchPush()
184 * @param array $jobs
185 * @param $flags
186 * @return bool
187 * @throws JobQueueError
188 */
189 protected function doBatchPush( array $jobs, $flags ) {
190 // Convert the jobs into field maps (de-duplicated against each other)
191 $items = array(); // (job ID => job fields map)
192 foreach ( $jobs as $job ) {
193 $item = $this->getNewJobFields( $job );
194 if ( strlen( $item['sha1'] ) ) { // hash identifier => de-duplicate
195 $items[$item['sha1']] = $item;
196 } else {
197 $items[$item['uuid']] = $item;
198 }
199 }
200
201 if ( !count( $items ) ) {
202 return true; // nothing to do
203 }
204
205 $conn = $this->getConnection();
206 try {
207 // Actually push the non-duplicate jobs into the queue...
208 if ( $flags & self::QOS_ATOMIC ) {
209 $batches = array( $items ); // all or nothing
210 } else {
211 $batches = array_chunk( $items, 500 ); // avoid tying up the server
212 }
213 $failed = 0;
214 $pushed = 0;
215 foreach ( $batches as $itemBatch ) {
216 $added = $this->pushBlobs( $conn, $itemBatch );
217 if ( is_int( $added ) ) {
218 $pushed += $added;
219 } else {
220 $failed += count( $itemBatch );
221 }
222 }
223 if ( $failed > 0 ) {
224 wfDebugLog( 'JobQueueRedis', "Could not insert {$failed} {$this->type} job(s)." );
225
226 return false;
227 }
228 JobQueue::incrStats( 'job-insert', $this->type, count( $items ) );
229 JobQueue::incrStats( 'job-insert-duplicate', $this->type,
230 count( $items ) - $failed - $pushed );
231 } catch ( RedisException $e ) {
232 $this->throwRedisException( $this->server, $conn, $e );
233 }
234
235 return true;
236 }
237
238 /**
239 * @param RedisConnRef $conn
240 * @param array $items List of results from JobQueueRedis::getNewJobFields()
241 * @return int Number of jobs inserted (duplicates are ignored)
242 * @throws RedisException
243 */
244 protected function pushBlobs( RedisConnRef $conn, array $items ) {
245 $args = array(); // ([id, sha1, rtime, blob [, id, sha1, rtime, blob ... ] ] )
246 foreach ( $items as $item ) {
247 $args[] = (string)$item['uuid'];
248 $args[] = (string)$item['sha1'];
249 $args[] = (string)$item['rtimestamp'];
250 $args[] = (string)$this->serialize( $item );
251 }
252 static $script =
253 <<<LUA
254 if #ARGV % 4 ~= 0 then return redis.error_reply('Unmatched arguments') end
255 local pushed = 0
256 for i = 1,#ARGV,4 do
257 local id,sha1,rtimestamp,blob = ARGV[i],ARGV[i+1],ARGV[i+2],ARGV[i+3]
258 if sha1 == '' or redis.call('hExists',KEYS[3],sha1) == 0 then
259 if 1*rtimestamp > 0 then
260 -- Insert into delayed queue (release time as score)
261 redis.call('zAdd',KEYS[4],rtimestamp,id)
262 else
263 -- Insert into unclaimed queue
264 redis.call('lPush',KEYS[1],id)
265 end
266 if sha1 ~= '' then
267 redis.call('hSet',KEYS[2],id,sha1)
268 redis.call('hSet',KEYS[3],sha1,id)
269 end
270 redis.call('hSet',KEYS[5],id,blob)
271 pushed = pushed + 1
272 end
273 end
274 return pushed
275 LUA;
276 return $conn->luaEval( $script,
277 array_merge(
278 array(
279 $this->getQueueKey( 'l-unclaimed' ), # KEYS[1]
280 $this->getQueueKey( 'h-sha1ById' ), # KEYS[2]
281 $this->getQueueKey( 'h-idBySha1' ), # KEYS[3]
282 $this->getQueueKey( 'z-delayed' ), # KEYS[4]
283 $this->getQueueKey( 'h-data' ), # KEYS[5]
284 ),
285 $args
286 ),
287 5 # number of first argument(s) that are keys
288 );
289 }
290
291 /**
292 * @see JobQueue::doPop()
293 * @return Job|bool
294 * @throws JobQueueError
295 */
296 protected function doPop() {
297 $job = false;
298
299 // Push ready delayed jobs into the queue every 10 jobs to spread the load.
300 // This is also done as a periodic task, but we don't want too much done at once.
301 if ( $this->checkDelay && mt_rand( 0, 9 ) == 0 ) {
302 $this->releaseReadyDelayedJobs();
303 }
304
305 $conn = $this->getConnection();
306 try {
307 do {
308 if ( $this->claimTTL > 0 ) {
309 // Keep the claimed job list down for high-traffic queues
310 if ( mt_rand( 0, 99 ) == 0 ) {
311 $this->recycleAndDeleteStaleJobs();
312 }
313 $blob = $this->popAndAcquireBlob( $conn );
314 } else {
315 $blob = $this->popAndDeleteBlob( $conn );
316 }
317 if ( $blob === false ) {
318 break; // no jobs; nothing to do
319 }
320
321 JobQueue::incrStats( 'job-pop', $this->type );
322 $item = $this->unserialize( $blob );
323 if ( $item === false ) {
324 wfDebugLog( 'JobQueueRedis', "Could not unserialize {$this->type} job." );
325 continue;
326 }
327
328 // If $item is invalid, recycleAndDeleteStaleJobs() will cleanup as needed
329 $job = $this->getJobFromFields( $item ); // may be false
330 } while ( !$job ); // job may be false if invalid
331 } catch ( RedisException $e ) {
332 $this->throwRedisException( $this->server, $conn, $e );
333 }
334
335 return $job;
336 }
337
338 /**
339 * @param RedisConnRef $conn
340 * @return array serialized string or false
341 * @throws RedisException
342 */
343 protected function popAndDeleteBlob( RedisConnRef $conn ) {
344 static $script =
345 <<<LUA
346 -- Pop an item off the queue
347 local id = redis.call('rpop',KEYS[1])
348 if not id then return false end
349 -- Get the job data and remove it
350 local item = redis.call('hGet',KEYS[4],id)
351 redis.call('hDel',KEYS[4],id)
352 -- Allow new duplicates of this job
353 local sha1 = redis.call('hGet',KEYS[2],id)
354 if sha1 then redis.call('hDel',KEYS[3],sha1) end
355 redis.call('hDel',KEYS[2],id)
356 -- Return the job data
357 return item
358 LUA;
359 return $conn->luaEval( $script,
360 array(
361 $this->getQueueKey( 'l-unclaimed' ), # KEYS[1]
362 $this->getQueueKey( 'h-sha1ById' ), # KEYS[2]
363 $this->getQueueKey( 'h-idBySha1' ), # KEYS[3]
364 $this->getQueueKey( 'h-data' ), # KEYS[4]
365 ),
366 4 # number of first argument(s) that are keys
367 );
368 }
369
370 /**
371 * @param RedisConnRef $conn
372 * @return array serialized string or false
373 * @throws RedisException
374 */
375 protected function popAndAcquireBlob( RedisConnRef $conn ) {
376 static $script =
377 <<<LUA
378 -- Pop an item off the queue
379 local id = redis.call('rPop',KEYS[1])
380 if not id then return false end
381 -- Allow new duplicates of this job
382 local sha1 = redis.call('hGet',KEYS[2],id)
383 if sha1 then redis.call('hDel',KEYS[3],sha1) end
384 redis.call('hDel',KEYS[2],id)
385 -- Mark the jobs as claimed and return it
386 redis.call('zAdd',KEYS[4],ARGV[1],id)
387 redis.call('hIncrBy',KEYS[5],id,1)
388 return redis.call('hGet',KEYS[6],id)
389 LUA;
390 return $conn->luaEval( $script,
391 array(
392 $this->getQueueKey( 'l-unclaimed' ), # KEYS[1]
393 $this->getQueueKey( 'h-sha1ById' ), # KEYS[2]
394 $this->getQueueKey( 'h-idBySha1' ), # KEYS[3]
395 $this->getQueueKey( 'z-claimed' ), # KEYS[4]
396 $this->getQueueKey( 'h-attempts' ), # KEYS[5]
397 $this->getQueueKey( 'h-data' ), # KEYS[6]
398 time(), # ARGV[1] (injected to be replication-safe)
399 ),
400 6 # number of first argument(s) that are keys
401 );
402 }
403
404 /**
405 * @see JobQueue::doAck()
406 * @param Job $job
407 * @return Job|bool
408 * @throws MWException|JobQueueError
409 */
410 protected function doAck( Job $job ) {
411 if ( !isset( $job->metadata['uuid'] ) ) {
412 throw new MWException( "Job of type '{$job->getType()}' has no UUID." );
413 }
414 if ( $this->claimTTL > 0 ) {
415 $conn = $this->getConnection();
416 try {
417 static $script =
418 <<<LUA
419 -- Unmark the job as claimed
420 redis.call('zRem',KEYS[1],ARGV[1])
421 redis.call('hDel',KEYS[2],ARGV[1])
422 -- Delete the job data itself
423 return redis.call('hDel',KEYS[3],ARGV[1])
424 LUA;
425 $res = $conn->luaEval( $script,
426 array(
427 $this->getQueueKey( 'z-claimed' ), # KEYS[1]
428 $this->getQueueKey( 'h-attempts' ), # KEYS[2]
429 $this->getQueueKey( 'h-data' ), # KEYS[3]
430 $job->metadata['uuid'] # ARGV[1]
431 ),
432 3 # number of first argument(s) that are keys
433 );
434
435 if ( !$res ) {
436 wfDebugLog( 'JobQueueRedis', "Could not acknowledge {$this->type} job." );
437
438 return false;
439 }
440 } catch ( RedisException $e ) {
441 $this->throwRedisException( $this->server, $conn, $e );
442 }
443 }
444
445 return true;
446 }
447
448 /**
449 * @see JobQueue::doDeduplicateRootJob()
450 * @param Job $job
451 * @return bool
452 * @throws MWException|JobQueueError
453 */
454 protected function doDeduplicateRootJob( Job $job ) {
455 if ( !$job->hasRootJobParams() ) {
456 throw new MWException( "Cannot register root job; missing parameters." );
457 }
458 $params = $job->getRootJobParams();
459
460 $key = $this->getRootJobCacheKey( $params['rootJobSignature'] );
461
462 $conn = $this->getConnection();
463 try {
464 $timestamp = $conn->get( $key ); // current last timestamp of this job
465 if ( $timestamp && $timestamp >= $params['rootJobTimestamp'] ) {
466 return true; // a newer version of this root job was enqueued
467 }
468
469 // Update the timestamp of the last root job started at the location...
470 return $conn->set( $key, $params['rootJobTimestamp'], self::ROOTJOB_TTL ); // 2 weeks
471 } catch ( RedisException $e ) {
472 $this->throwRedisException( $this->server, $conn, $e );
473 }
474 }
475
476 /**
477 * @see JobQueue::doIsRootJobOldDuplicate()
478 * @param Job $job
479 * @return bool
480 * @throws JobQueueError
481 */
482 protected function doIsRootJobOldDuplicate( Job $job ) {
483 if ( !$job->hasRootJobParams() ) {
484 return false; // job has no de-deplication info
485 }
486 $params = $job->getRootJobParams();
487
488 $conn = $this->getConnection();
489 try {
490 // Get the last time this root job was enqueued
491 $timestamp = $conn->get( $this->getRootJobCacheKey( $params['rootJobSignature'] ) );
492 } catch ( RedisException $e ) {
493 $this->throwRedisException( $this->server, $conn, $e );
494 }
495
496 // Check if a new root job was started at the location after this one's...
497 return ( $timestamp && $timestamp > $params['rootJobTimestamp'] );
498 }
499
500 /**
501 * @see JobQueue::doDelete()
502 * @return bool
503 * @throws JobQueueError
504 */
505 protected function doDelete() {
506 static $props = array( 'l-unclaimed', 'z-claimed', 'z-abandoned',
507 'z-delayed', 'h-idBySha1', 'h-sha1ById', 'h-attempts', 'h-data' );
508
509 $conn = $this->getConnection();
510 try {
511 $keys = array();
512 foreach ( $props as $prop ) {
513 $keys[] = $this->getQueueKey( $prop );
514 }
515
516 return ( $conn->delete( $keys ) !== false );
517 } catch ( RedisException $e ) {
518 $this->throwRedisException( $this->server, $conn, $e );
519 }
520 }
521
522 /**
523 * @see JobQueue::getAllQueuedJobs()
524 * @return Iterator
525 */
526 public function getAllQueuedJobs() {
527 $conn = $this->getConnection();
528 try {
529 $that = $this;
530
531 return new MappedIterator(
532 $conn->lRange( $this->getQueueKey( 'l-unclaimed' ), 0, -1 ),
533 function ( $uid ) use ( $that, $conn ) {
534 return $that->getJobFromUidInternal( $uid, $conn );
535 },
536 array( 'accept' => function ( $job ) {
537 return is_object( $job );
538 } )
539 );
540 } catch ( RedisException $e ) {
541 $this->throwRedisException( $this->server, $conn, $e );
542 }
543 }
544
545 /**
546 * @see JobQueue::getAllQueuedJobs()
547 * @return Iterator
548 */
549 public function getAllDelayedJobs() {
550 $conn = $this->getConnection();
551 try {
552 $that = $this;
553
554 return new MappedIterator( // delayed jobs
555 $conn->zRange( $this->getQueueKey( 'z-delayed' ), 0, -1 ),
556 function ( $uid ) use ( $that, $conn ) {
557 return $that->getJobFromUidInternal( $uid, $conn );
558 },
559 array( 'accept' => function ( $job ) {
560 return is_object( $job );
561 } )
562 );
563 } catch ( RedisException $e ) {
564 $this->throwRedisException( $this->server, $conn, $e );
565 }
566 }
567
568 public function getCoalesceLocationInternal() {
569 return "RedisServer:" . $this->server;
570 }
571
572 protected function doGetSiblingQueuesWithJobs( array $types ) {
573 return array_keys( array_filter( $this->doGetSiblingQueueSizes( $types ) ) );
574 }
575
576 protected function doGetSiblingQueueSizes( array $types ) {
577 $sizes = array(); // (type => size)
578 $types = array_values( $types ); // reindex
579 try {
580 $conn = $this->getConnection();
581 $conn->multi( Redis::PIPELINE );
582 foreach ( $types as $type ) {
583 $conn->lSize( $this->getQueueKey( 'l-unclaimed', $type ) );
584 }
585 $res = $conn->exec();
586 if ( is_array( $res ) ) {
587 foreach ( $res as $i => $size ) {
588 $sizes[$types[$i]] = $size;
589 }
590 }
591 } catch ( RedisException $e ) {
592 $this->throwRedisException( $this->server, $conn, $e );
593 }
594
595 return $sizes;
596 }
597
598 /**
599 * This function should not be called outside JobQueueRedis
600 *
601 * @param $uid string
602 * @param $conn RedisConnRef
603 * @return Job|bool Returns false if the job does not exist
604 * @throws MWException|JobQueueError
605 */
606 public function getJobFromUidInternal( $uid, RedisConnRef $conn ) {
607 try {
608 $data = $conn->hGet( $this->getQueueKey( 'h-data' ), $uid );
609 if ( $data === false ) {
610 return false; // not found
611 }
612 $item = $this->unserialize( $conn->hGet( $this->getQueueKey( 'h-data' ), $uid ) );
613 if ( !is_array( $item ) ) { // this shouldn't happen
614 throw new MWException( "Could not find job with ID '$uid'." );
615 }
616 $title = Title::makeTitle( $item['namespace'], $item['title'] );
617 $job = Job::factory( $item['type'], $title, $item['params'] );
618 $job->metadata['uuid'] = $item['uuid'];
619
620 return $job;
621 } catch ( RedisException $e ) {
622 $this->throwRedisException( $this->server, $conn, $e );
623 }
624 }
625
626 /**
627 * Release any ready delayed jobs into the queue
628 *
629 * @return int Number of jobs released
630 * @throws JobQueueError
631 */
632 public function releaseReadyDelayedJobs() {
633 $count = 0;
634
635 $conn = $this->getConnection();
636 try {
637 static $script =
638 <<<LUA
639 -- Get the list of ready delayed jobs, sorted by readiness
640 local ids = redis.call('zRangeByScore',KEYS[1],0,ARGV[1])
641 -- Migrate the jobs from the "delayed" set to the "unclaimed" list
642 for k,id in ipairs(ids) do
643 redis.call('lPush',KEYS[2],id)
644 redis.call('zRem',KEYS[1],id)
645 end
646 return #ids
647 LUA;
648 $count += (int)$conn->luaEval( $script,
649 array(
650 $this->getQueueKey( 'z-delayed' ), // KEYS[1]
651 $this->getQueueKey( 'l-unclaimed' ), // KEYS[2]
652 time() // ARGV[1]; max "delay until" UNIX timestamp
653 ),
654 2 # first two arguments are keys
655 );
656 } catch ( RedisException $e ) {
657 $this->throwRedisException( $this->server, $conn, $e );
658 }
659
660 return $count;
661 }
662
663 /**
664 * Recycle or destroy any jobs that have been claimed for too long
665 *
666 * @return int Number of jobs recycled/deleted
667 * @throws MWException|JobQueueError
668 */
669 public function recycleAndDeleteStaleJobs() {
670 if ( $this->claimTTL <= 0 ) { // sanity
671 throw new MWException( "Cannot recycle jobs since acknowledgements are disabled." );
672 }
673 $count = 0;
674 // For each job item that can be retried, we need to add it back to the
675 // main queue and remove it from the list of currenty claimed job items.
676 // For those that cannot, they are marked as dead and kept around for
677 // investigation and manual job restoration but are eventually deleted.
678 $conn = $this->getConnection();
679 try {
680 $now = time();
681 static $script =
682 <<<LUA
683 local released,abandoned,pruned = 0,0,0
684 -- Get all non-dead jobs that have an expired claim on them.
685 -- The score for each item is the last claim timestamp (UNIX).
686 local staleClaims = redis.call('zRangeByScore',KEYS[1],0,ARGV[1])
687 for k,id in ipairs(staleClaims) do
688 local timestamp = redis.call('zScore',KEYS[1],id)
689 local attempts = redis.call('hGet',KEYS[2],id)
690 if attempts < ARGV[3] then
691 -- Claim expired and retries left: re-enqueue the job
692 redis.call('lPush',KEYS[3],id)
693 redis.call('hIncrBy',KEYS[2],id,1)
694 released = released + 1
695 else
696 -- Claim expired and no retries left: mark the job as dead
697 redis.call('zAdd',KEYS[5],timestamp,id)
698 abandoned = abandoned + 1
699 end
700 redis.call('zRem',KEYS[1],id)
701 end
702 -- Get all of the dead jobs that have been marked as dead for too long.
703 -- The score for each item is the last claim timestamp (UNIX).
704 local deadClaims = redis.call('zRangeByScore',KEYS[5],0,ARGV[2])
705 for k,id in ipairs(deadClaims) do
706 -- Stale and out of retries: remove any traces of the job
707 redis.call('zRem',KEYS[5],id)
708 redis.call('hDel',KEYS[2],id)
709 redis.call('hDel',KEYS[4],id)
710 pruned = pruned + 1
711 end
712 return {released,abandoned,pruned}
713 LUA;
714 $res = $conn->luaEval( $script,
715 array(
716 $this->getQueueKey( 'z-claimed' ), # KEYS[1]
717 $this->getQueueKey( 'h-attempts' ), # KEYS[2]
718 $this->getQueueKey( 'l-unclaimed' ), # KEYS[3]
719 $this->getQueueKey( 'h-data' ), # KEYS[4]
720 $this->getQueueKey( 'z-abandoned' ), # KEYS[5]
721 $now - $this->claimTTL, # ARGV[1]
722 $now - self::MAX_AGE_PRUNE, # ARGV[2]
723 $this->maxTries # ARGV[3]
724 ),
725 5 # number of first argument(s) that are keys
726 );
727 if ( $res ) {
728 list( $released, $abandoned, $pruned ) = $res;
729 $count += $released + $pruned;
730 JobQueue::incrStats( 'job-recycle', $this->type, $released );
731 JobQueue::incrStats( 'job-abandon', $this->type, $abandoned );
732 }
733 } catch ( RedisException $e ) {
734 $this->throwRedisException( $this->server, $conn, $e );
735 }
736
737 return $count;
738 }
739
740 /**
741 * @return array
742 */
743 protected function doGetPeriodicTasks() {
744 $tasks = array();
745 if ( $this->claimTTL > 0 ) {
746 $tasks['recycleAndDeleteStaleJobs'] = array(
747 'callback' => array( $this, 'recycleAndDeleteStaleJobs' ),
748 'period' => ceil( $this->claimTTL / 2 )
749 );
750 }
751 if ( $this->checkDelay ) {
752 $tasks['releaseReadyDelayedJobs'] = array(
753 'callback' => array( $this, 'releaseReadyDelayedJobs' ),
754 'period' => 300 // 5 minutes
755 );
756 }
757
758 return $tasks;
759 }
760
761 /**
762 * @param Job $job
763 * @return array
764 */
765 protected function getNewJobFields( Job $job ) {
766 return array(
767 // Fields that describe the nature of the job
768 'type' => $job->getType(),
769 'namespace' => $job->getTitle()->getNamespace(),
770 'title' => $job->getTitle()->getDBkey(),
771 'params' => $job->getParams(),
772 // Some jobs cannot run until a "release timestamp"
773 'rtimestamp' => $job->getReleaseTimestamp() ? : 0,
774 // Additional job metadata
775 'uuid' => UIDGenerator::newRawUUIDv4( UIDGenerator::QUICK_RAND ),
776 'sha1' => $job->ignoreDuplicates()
777 ? wfBaseConvert( sha1( serialize( $job->getDeduplicationInfo() ) ), 16, 36, 31 )
778 : '',
779 'timestamp' => time() // UNIX timestamp
780 );
781 }
782
783 /**
784 * @param $fields array
785 * @return Job|bool
786 */
787 protected function getJobFromFields( array $fields ) {
788 $title = Title::makeTitleSafe( $fields['namespace'], $fields['title'] );
789 if ( $title ) {
790 $job = Job::factory( $fields['type'], $title, $fields['params'] );
791 $job->metadata['uuid'] = $fields['uuid'];
792
793 return $job;
794 }
795
796 return false;
797 }
798
799 /**
800 * @param array $fields
801 * @return string Serialized and possibly compressed version of $fields
802 */
803 protected function serialize( array $fields ) {
804 $blob = serialize( $fields );
805 if ( $this->compression === 'gzip'
806 && strlen( $blob ) >= 1024
807 && function_exists( 'gzdeflate' )
808 ) {
809 $object = (object)array( 'blob' => gzdeflate( $blob ), 'enc' => 'gzip' );
810 $blobz = serialize( $object );
811
812 return ( strlen( $blobz ) < strlen( $blob ) ) ? $blobz : $blob;
813 } else {
814 return $blob;
815 }
816 }
817
818 /**
819 * @param string $blob
820 * @return array|bool Unserialized version of $blob or false
821 */
822 protected function unserialize( $blob ) {
823 $fields = unserialize( $blob );
824 if ( is_object( $fields ) ) {
825 if ( $fields->enc === 'gzip' && function_exists( 'gzinflate' ) ) {
826 $fields = unserialize( gzinflate( $fields->blob ) );
827 } else {
828 $fields = false;
829 }
830 }
831
832 return is_array( $fields ) ? $fields : false;
833 }
834
835 /**
836 * Get a connection to the server that handles all sub-queues for this queue
837 *
838 * @return RedisConnRef
839 * @throws JobQueueConnectionError
840 */
841 protected function getConnection() {
842 $conn = $this->redisPool->getConnection( $this->server );
843 if ( !$conn ) {
844 throw new JobQueueConnectionError( "Unable to connect to redis server." );
845 }
846
847 return $conn;
848 }
849
850 /**
851 * @param $server string
852 * @param $conn RedisConnRef
853 * @param $e RedisException
854 * @throws JobQueueError
855 */
856 protected function throwRedisException( $server, RedisConnRef $conn, $e ) {
857 $this->redisPool->handleException( $server, $conn, $e );
858 throw new JobQueueError( "Redis server error: {$e->getMessage()}\n" );
859 }
860
861 /**
862 * @param $prop string
863 * @param $type string|null
864 * @return string
865 */
866 private function getQueueKey( $prop, $type = null ) {
867 $type = is_string( $type ) ? $type : $this->type;
868 list( $db, $prefix ) = wfSplitWikiID( $this->wiki );
869 if ( strlen( $this->key ) ) { // namespaced queue (for testing)
870 return wfForeignMemcKey( $db, $prefix, 'jobqueue', $type, $this->key, $prop );
871 } else {
872 return wfForeignMemcKey( $db, $prefix, 'jobqueue', $type, $prop );
873 }
874 }
875
876 /**
877 * @param $key string
878 * @return void
879 */
880 public function setTestingPrefix( $key ) {
881 $this->key = $key;
882 }
883 }