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