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