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