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