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