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