Merge "Fix HTML output of TablePager"
[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 wfIncrStats( 'job-insert', count( $items ) );
220 wfIncrStats( 'job-insert-duplicate', count( $items ) - $failed - $pushed );
221 } catch ( RedisException $e ) {
222 $this->throwRedisException( $this->server, $conn, $e );
223 }
224
225 return true;
226 }
227
228 /**
229 * @param RedisConnRef $conn
230 * @param array $items List of results from JobQueueRedis::getNewJobFields()
231 * @return integer Number of jobs inserted (duplicates are ignored)
232 * @throws RedisException
233 */
234 protected function pushBlobs( RedisConnRef $conn, array $items ) {
235 $args = array(); // ([id, sha1, rtime, blob [, id, sha1, rtime, blob ... ] ] )
236 foreach ( $items as $item ) {
237 $args[] = (string)$item['uuid'];
238 $args[] = (string)$item['sha1'];
239 $args[] = (string)$item['rtimestamp'];
240 $args[] = (string)serialize( $item );
241 }
242 static $script =
243 <<<LUA
244 if #ARGV % 4 ~= 0 then return redis.error_reply('Unmatched arguments') end
245 local pushed = 0
246 for i = 1,#ARGV,4 do
247 local id,sha1,rtimestamp,blob = ARGV[i],ARGV[i+1],ARGV[i+2],ARGV[i+3]
248 if sha1 == '' or redis.call('hExists',KEYS[3],sha1) == 0 then
249 if 1*rtimestamp > 0 then
250 -- Insert into delayed queue (release time as score)
251 redis.call('zAdd',KEYS[4],rtimestamp,id)
252 else
253 -- Insert into unclaimed queue
254 redis.call('lPush',KEYS[1],id)
255 end
256 if sha1 ~= '' then
257 redis.call('hSet',KEYS[2],id,sha1)
258 redis.call('hSet',KEYS[3],sha1,id)
259 end
260 redis.call('hSet',KEYS[5],id,blob)
261 pushed = pushed + 1
262 end
263 end
264 return pushed
265 LUA;
266 return $this->redisEval( $conn, $script,
267 array_merge(
268 array(
269 $this->getQueueKey( 'l-unclaimed' ), # KEYS[1]
270 $this->getQueueKey( 'h-sha1ById' ), # KEYS[2]
271 $this->getQueueKey( 'h-idBySha1' ), # KEYS[3]
272 $this->getQueueKey( 'z-delayed' ), # KEYS[4]
273 $this->getQueueKey( 'h-data' ), # KEYS[5]
274 ),
275 $args
276 ),
277 5 # number of first argument(s) that are keys
278 );
279 }
280
281 /**
282 * @see JobQueue::doPop()
283 * @return Job|bool
284 * @throws MWException
285 */
286 protected function doPop() {
287 $job = false;
288
289 // Push ready delayed jobs into the queue every 10 jobs to spread the load.
290 // This is also done as a periodic task, but we don't want too much done at once.
291 if ( $this->checkDelay && mt_rand( 0, 9 ) == 0 ) {
292 $this->releaseReadyDelayedJobs();
293 }
294
295 $conn = $this->getConnection();
296 try {
297 do {
298 if ( $this->claimTTL > 0 ) {
299 // Keep the claimed job list down for high-traffic queues
300 if ( mt_rand( 0, 99 ) == 0 ) {
301 $this->recycleAndDeleteStaleJobs();
302 }
303 $blob = $this->popAndAcquireBlob( $conn );
304 } else {
305 $blob = $this->popAndDeleteBlob( $conn );
306 }
307 if ( $blob === false ) {
308 break; // no jobs; nothing to do
309 }
310
311 wfIncrStats( 'job-pop' );
312 $item = unserialize( $blob );
313 if ( $item === false ) {
314 wfDebugLog( 'JobQueueRedis', "Could not unserialize {$this->type} job." );
315 continue;
316 }
317
318 // If $item is invalid, recycleAndDeleteStaleJobs() will cleanup as needed
319 $job = $this->getJobFromFields( $item ); // may be false
320 } while ( !$job ); // job may be false if invalid
321 } catch ( RedisException $e ) {
322 $this->throwRedisException( $this->server, $conn, $e );
323 }
324
325 return $job;
326 }
327
328 /**
329 * @param RedisConnRef $conn
330 * @return array serialized string or false
331 * @throws RedisException
332 */
333 protected function popAndDeleteBlob( RedisConnRef $conn ) {
334 static $script =
335 <<<LUA
336 -- Pop an item off the queue
337 local id = redis.call('rpop',KEYS[1])
338 if not id then return false end
339 -- Get the job data and remove it
340 local item = redis.call('hGet',KEYS[4],id)
341 redis.call('hDel',KEYS[4],id)
342 -- Allow new duplicates of this job
343 local sha1 = redis.call('hGet',KEYS[2],id)
344 if sha1 then redis.call('hDel',KEYS[3],sha1) end
345 redis.call('hDel',KEYS[2],id)
346 -- Return the job data
347 return item
348 LUA;
349 return $this->redisEval( $conn, $script,
350 array(
351 $this->getQueueKey( 'l-unclaimed' ), # KEYS[1]
352 $this->getQueueKey( 'h-sha1ById' ), # KEYS[2]
353 $this->getQueueKey( 'h-idBySha1' ), # KEYS[3]
354 $this->getQueueKey( 'h-data' ), # KEYS[4]
355 ),
356 4 # number of first argument(s) that are keys
357 );
358 }
359
360 /**
361 * @param RedisConnRef $conn
362 * @return array serialized string or false
363 * @throws RedisException
364 */
365 protected function popAndAcquireBlob( RedisConnRef $conn ) {
366 static $script =
367 <<<LUA
368 -- Pop an item off the queue
369 local id = redis.call('rPop',KEYS[1])
370 if not id then return false end
371 -- Allow new duplicates of this job
372 local sha1 = redis.call('hGet',KEYS[2],id)
373 if sha1 then redis.call('hDel',KEYS[3],sha1) end
374 redis.call('hDel',KEYS[2],id)
375 -- Mark the jobs as claimed and return it
376 redis.call('zAdd',KEYS[4],ARGV[1],id)
377 redis.call('hIncrBy',KEYS[5],id,1)
378 return redis.call('hGet',KEYS[6],id)
379 LUA;
380 return $this->redisEval( $conn, $script,
381 array(
382 $this->getQueueKey( 'l-unclaimed' ), # KEYS[1]
383 $this->getQueueKey( 'h-sha1ById' ), # KEYS[2]
384 $this->getQueueKey( 'h-idBySha1' ), # KEYS[3]
385 $this->getQueueKey( 'z-claimed' ), # KEYS[4]
386 $this->getQueueKey( 'h-attempts' ), # KEYS[5]
387 $this->getQueueKey( 'h-data' ), # KEYS[6]
388 time(), # ARGV[1] (injected to be replication-safe)
389 ),
390 6 # number of first argument(s) that are keys
391 );
392 }
393
394 /**
395 * @see JobQueue::doAck()
396 * @param Job $job
397 * @return Job|bool
398 * @throws MWException
399 */
400 protected function doAck( Job $job ) {
401 if ( $this->claimTTL > 0 ) {
402 $conn = $this->getConnection();
403 try {
404 // Get the exact field map this Job came from, regardless of whether
405 // the job was transformed into a DuplicateJob or anything of the sort.
406 $item = $job->metadata['sourceFields'];
407
408 static $script =
409 <<<LUA
410 -- Unmark the job as claimed
411 redis.call('zRem',KEYS[1],ARGV[1])
412 redis.call('hDel',KEYS[2],ARGV[1])
413 -- Delete the job data itself
414 return redis.call('hDel',KEYS[3],ARGV[1])
415 LUA;
416 $res = $this->redisEval( $conn, $script,
417 array(
418 $this->getQueueKey( 'z-claimed' ), # KEYS[1]
419 $this->getQueueKey( 'h-attempts' ), # KEYS[2]
420 $this->getQueueKey( 'h-data' ), # KEYS[3]
421 $item['uuid'] # ARGV[1]
422 ),
423 3 # number of first argument(s) that are keys
424 );
425
426 if ( !$res ) {
427 wfDebugLog( 'JobQueueRedis', "Could not acknowledge {$this->type} job." );
428 return false;
429 }
430 } catch ( RedisException $e ) {
431 $this->throwRedisException( $this->server, $conn, $e );
432 }
433 }
434 return true;
435 }
436
437 /**
438 * @see JobQueue::doDeduplicateRootJob()
439 * @param Job $job
440 * @return bool
441 * @throws MWException
442 */
443 protected function doDeduplicateRootJob( Job $job ) {
444 if ( !$job->hasRootJobParams() ) {
445 throw new MWException( "Cannot register root job; missing parameters." );
446 }
447 $params = $job->getRootJobParams();
448
449 $key = $this->getRootJobCacheKey( $params['rootJobSignature'] );
450
451 $conn = $this->getConnection();
452 try {
453 $timestamp = $conn->get( $key ); // current last timestamp of this job
454 if ( $timestamp && $timestamp >= $params['rootJobTimestamp'] ) {
455 return true; // a newer version of this root job was enqueued
456 }
457 // Update the timestamp of the last root job started at the location...
458 return $conn->set( $key, $params['rootJobTimestamp'], self::ROOTJOB_TTL ); // 2 weeks
459 } catch ( RedisException $e ) {
460 $this->throwRedisException( $this->server, $conn, $e );
461 }
462 }
463
464 /**
465 * @see JobQueue::doIsRootJobOldDuplicate()
466 * @param Job $job
467 * @return bool
468 */
469 protected function doIsRootJobOldDuplicate( Job $job ) {
470 $params = $job->getParams();
471 if ( !isset( $params['rootJobSignature'] ) ) {
472 return false; // job has no de-deplication info
473 } elseif ( !isset( $params['rootJobTimestamp'] ) ) {
474 wfDebugLog( 'JobQueueRedis', "Cannot check root job; missing 'rootJobTimestamp'." );
475 return false;
476 }
477
478 $conn = $this->getConnection();
479 try {
480 // Get the last time this root job was enqueued
481 $timestamp = $conn->get( $this->getRootJobCacheKey( $params['rootJobSignature'] ) );
482 } catch ( RedisException $e ) {
483 $this->throwRedisException( $this->server, $conn, $e );
484 }
485
486 // Check if a new root job was started at the location after this one's...
487 return ( $timestamp && $timestamp > $params['rootJobTimestamp'] );
488 }
489
490 /**
491 * @see JobQueue::getAllQueuedJobs()
492 * @return Iterator
493 */
494 public function getAllQueuedJobs() {
495 $conn = $this->getConnection();
496 if ( !$conn ) {
497 throw new MWException( "Unable to connect to redis server." );
498 }
499 try {
500 $that = $this;
501 return new MappedIterator(
502 $conn->lRange( $this->getQueueKey( 'l-unclaimed' ), 0, -1 ),
503 function( $uid ) use ( $that, $conn ) {
504 return $that->getJobFromUidInternal( $uid, $conn );
505 }
506 );
507 } catch ( RedisException $e ) {
508 $this->throwRedisException( $this->server, $conn, $e );
509 }
510 }
511
512 /**
513 * @see JobQueue::getAllQueuedJobs()
514 * @return Iterator
515 */
516 public function getAllDelayedJobs() {
517 $conn = $this->getConnection();
518 if ( !$conn ) {
519 throw new MWException( "Unable to connect to redis server." );
520 }
521 try {
522 $that = $this;
523 return new MappedIterator( // delayed jobs
524 $conn->zRange( $this->getQueueKey( 'z-delayed' ), 0, -1 ),
525 function( $uid ) use ( $that, $conn ) {
526 return $that->getJobFromUidInternal( $uid, $conn );
527 }
528 );
529 } catch ( RedisException $e ) {
530 $this->throwRedisException( $this->server, $conn, $e );
531 }
532 }
533
534 /**
535 * This function should not be called outside JobQueueRedis
536 *
537 * @param $uid string
538 * @param $conn RedisConnRef
539 * @return Job
540 * @throws MWException
541 */
542 public function getJobFromUidInternal( $uid, RedisConnRef $conn ) {
543 try {
544 $item = unserialize( $conn->hGet( $this->getQueueKey( 'h-data' ), $uid ) );
545 if ( !is_array( $item ) ) { // this shouldn't happen
546 throw new MWException( "Could not find job with ID '$uid'." );
547 }
548 $title = Title::makeTitle( $item['namespace'], $item['title'] );
549 $job = Job::factory( $item['type'], $title, $item['params'] );
550 $job->metadata['sourceFields'] = $item;
551 return $job;
552 } catch ( RedisException $e ) {
553 $this->throwRedisException( $this->server, $conn, $e );
554 }
555 }
556
557 /**
558 * Release any ready delayed jobs into the queue
559 *
560 * @return integer Number of jobs released
561 * @throws MWException
562 */
563 public function releaseReadyDelayedJobs() {
564 $count = 0;
565
566 $conn = $this->getConnection();
567 try {
568 static $script =
569 <<<LUA
570 -- Get the list of ready delayed jobs, sorted by readiness
571 local ids = redis.call('zRangeByScore',KEYS[1],0,ARGV[1])
572 -- Migrate the jobs from the "delayed" set to the "unclaimed" list
573 for k,id in ipairs(ids) do
574 redis.call('lPush',KEYS[2],id)
575 redis.call('zRem',KEYS[1],id)
576 end
577 return #ids
578 LUA;
579 $count += (int)$this->redisEval( $conn, $script,
580 array(
581 $this->getQueueKey( 'z-delayed' ), // KEYS[1]
582 $this->getQueueKey( 'l-unclaimed' ), // KEYS[2]
583 time() // ARGV[1]; max "delay until" UNIX timestamp
584 ),
585 2 # first two arguments are keys
586 );
587 } catch ( RedisException $e ) {
588 $this->throwRedisException( $this->server, $conn, $e );
589 }
590
591 return $count;
592 }
593
594 /**
595 * Recycle or destroy any jobs that have been claimed for too long
596 *
597 * @return integer Number of jobs recycled/deleted
598 * @throws MWException
599 */
600 public function recycleAndDeleteStaleJobs() {
601 if ( $this->claimTTL <= 0 ) { // sanity
602 throw new MWException( "Cannot recycle jobs since acknowledgements are disabled." );
603 }
604 $count = 0;
605 // For each job item that can be retried, we need to add it back to the
606 // main queue and remove it from the list of currenty claimed job items.
607 // For those that cannot, they are marked as dead and kept around for
608 // investigation and manual job restoration but are eventually deleted.
609 $conn = $this->getConnection();
610 try {
611 $now = time();
612 static $script =
613 <<<LUA
614 local released,abandoned,pruned = 0,0,0
615 -- Get all non-dead jobs that have an expired claim on them.
616 -- The score for each item is the last claim timestamp (UNIX).
617 local staleClaims = redis.call('zRangeByScore',KEYS[1],0,ARGV[1])
618 for k,id in ipairs(staleClaims) do
619 local timestamp = redis.call('zScore',KEYS[1],id)
620 local attempts = redis.call('hGet',KEYS[2],id)
621 if attempts < ARGV[3] then
622 -- Claim expired and retries left: re-enqueue the job
623 redis.call('lPush',KEYS[3],id)
624 redis.call('hIncrBy',KEYS[2],id,1)
625 released = released + 1
626 else
627 -- Claim expired and no retries left: mark the job as dead
628 redis.call('zAdd',KEYS[5],timestamp,id)
629 abandoned = abandoned + 1
630 end
631 redis.call('zRem',KEYS[1],id)
632 end
633 -- Get all of the dead jobs that have been marked as dead for too long.
634 -- The score for each item is the last claim timestamp (UNIX).
635 local deadClaims = redis.call('zRangeByScore',KEYS[5],0,ARGV[2])
636 for k,id in ipairs(deadClaims) do
637 -- Stale and out of retries: remove any traces of the job
638 redis.call('zRem',KEYS[5],id)
639 redis.call('hDel',KEYS[2],id)
640 redis.call('hDel',KEYS[4],id)
641 pruned = pruned + 1
642 end
643 return {released,abandoned,pruned}
644 LUA;
645 $res = $this->redisEval( $conn, $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 $now - $this->claimTTL, # ARGV[1]
653 $now - self::MAX_AGE_PRUNE, # ARGV[2]
654 $this->maxTries # ARGV[3]
655 ),
656 5 # number of first argument(s) that are keys
657 );
658 if ( $res ) {
659 list( $released, $abandoned, $pruned ) = $res;
660 $count += $released + $pruned;
661 wfIncrStats( 'job-recycle', count( $released ) );
662 }
663 } catch ( RedisException $e ) {
664 $this->throwRedisException( $this->server, $conn, $e );
665 }
666
667 return $count;
668 }
669
670 /**
671 * @return Array
672 */
673 protected function doGetPeriodicTasks() {
674 $tasks = array();
675 if ( $this->claimTTL > 0 ) {
676 $tasks['recycleAndDeleteStaleJobs'] = array(
677 'callback' => array( $this, 'recycleAndDeleteStaleJobs' ),
678 'period' => ceil( $this->claimTTL / 2 )
679 );
680 }
681 if ( $this->checkDelay ) {
682 $tasks['releaseReadyDelayedJobs'] = array(
683 'callback' => array( $this, 'releaseReadyDelayedJobs' ),
684 'period' => 300 // 5 minutes
685 );
686 }
687 return $tasks;
688 }
689
690 /**
691 * @param RedisConnRef $conn
692 * @param string $script
693 * @param array $params
694 * @param integer $numKeys
695 * @return mixed
696 */
697 protected function redisEval( RedisConnRef $conn, $script, array $params, $numKeys ) {
698 $sha1 = sha1( $script ); // 40 char hex
699
700 // Try to run the server-side cached copy of the script
701 $conn->clearLastError();
702 $res = $conn->evalSha( $sha1, $params, $numKeys );
703 // If the script is not in cache, use eval() to retry and cache it
704 if ( $conn->getLastError() && $conn->script( 'exists', $sha1 ) === array( 0 ) ) {
705 $conn->clearLastError();
706 $res = $conn->eval( $script, $params, $numKeys );
707 wfDebugLog( 'JobQueueRedis', "Used eval() for Lua script $sha1." );
708 }
709
710 if ( $conn->getLastError() ) { // script bug?
711 wfDebugLog( 'JobQueueRedis', "Lua script error: " . $conn->getLastError() );
712 }
713
714 return $res;
715 }
716
717 /**
718 * @param $job Job
719 * @return array
720 */
721 protected function getNewJobFields( Job $job ) {
722 return array(
723 // Fields that describe the nature of the job
724 'type' => $job->getType(),
725 'namespace' => $job->getTitle()->getNamespace(),
726 'title' => $job->getTitle()->getDBkey(),
727 'params' => $job->getParams(),
728 // Some jobs cannot run until a "release timestamp"
729 'rtimestamp' => $job->getReleaseTimestamp() ?: 0,
730 // Additional job metadata
731 'uuid' => UIDGenerator::newRawUUIDv4( UIDGenerator::QUICK_RAND ),
732 'sha1' => $job->ignoreDuplicates()
733 ? wfBaseConvert( sha1( serialize( $job->getDeduplicationInfo() ) ), 16, 36, 31 )
734 : '',
735 'timestamp' => time() // UNIX timestamp
736 );
737 }
738
739 /**
740 * @param $fields array
741 * @return Job|bool
742 */
743 protected function getJobFromFields( array $fields ) {
744 $title = Title::makeTitleSafe( $fields['namespace'], $fields['title'] );
745 if ( $title ) {
746 $job = Job::factory( $fields['type'], $title, $fields['params'] );
747 $job->metadata['sourceFields'] = $fields;
748 return $job;
749 }
750 return false;
751 }
752
753 /**
754 * Get a connection to the server that handles all sub-queues for this queue
755 *
756 * @return Array (server name, Redis instance)
757 * @throws MWException
758 */
759 protected function getConnection() {
760 $conn = $this->redisPool->getConnection( $this->server );
761 if ( !$conn ) {
762 throw new MWException( "Unable to connect to redis server." );
763 }
764 return $conn;
765 }
766
767 /**
768 * @param $server string
769 * @param $conn RedisConnRef
770 * @param $e RedisException
771 * @throws MWException
772 */
773 protected function throwRedisException( $server, RedisConnRef $conn, $e ) {
774 $this->redisPool->handleException( $server, $conn, $e );
775 throw new MWException( "Redis server error: {$e->getMessage()}\n" );
776 }
777
778 /**
779 * @param $prop string
780 * @return string
781 */
782 private function getQueueKey( $prop ) {
783 list( $db, $prefix ) = wfSplitWikiID( $this->wiki );
784 if ( strlen( $this->key ) ) { // namespaced queue (for testing)
785 return wfForeignMemcKey( $db, $prefix, 'jobqueue', $this->type, $this->key, $prop );
786 } else {
787 return wfForeignMemcKey( $db, $prefix, 'jobqueue', $this->type, $prop );
788 }
789 }
790
791 /**
792 * @param $key string
793 * @return void
794 */
795 public function setTestingPrefix( $key ) {
796 $this->key = $key;
797 }
798 }