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