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