Merge "CSSMin: version URLs based on content, not mtime"
[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 a faster and less resource-intensive job queue than 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 persistence. 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
68 const MAX_AGE_PRUNE = 604800; // integer; seconds a job can live once claimed (7 days)
69
70 /** @var string Key to prefix the queue keys with (used for testing) */
71 protected $key;
72
73 /**
74 * @param array $params Possible keys:
75 * - redisConfig : An array of parameters to RedisConnectionPool::__construct().
76 * Note that the serializer option is ignored as "none" is always used.
77 * - redisServer : A hostname/port combination or the absolute path of a UNIX socket.
78 * If a hostname is specified but no port, the standard port number
79 * 6379 will be used. Required.
80 * - compression : The type of compression to use; one of (none,gzip).
81 * - daemonized : Set to true if the redisJobRunnerService runs in the background.
82 * This will disable job recycling/undelaying from the MediaWiki side
83 * to avoid redundance and out-of-sync configuration.
84 * @throws InvalidArgumentException
85 */
86 public function __construct( array $params ) {
87 parent::__construct( $params );
88 $params['redisConfig']['serializer'] = 'none'; // make it easy to use Lua
89 $this->server = $params['redisServer'];
90 $this->compression = isset( $params['compression'] ) ? $params['compression'] : 'none';
91 $this->redisPool = RedisConnectionPool::singleton( $params['redisConfig'] );
92 if ( empty( $params['daemonized'] ) ) {
93 throw new InvalidArgumentException(
94 "Non-daemonized mode is no longer supported. Please install the " .
95 "mediawiki/services/jobrunner service and update \$wgJobTypeConf as needed." );
96 }
97 }
98
99 protected function supportedOrders() {
100 return array( 'timestamp', 'fifo' );
101 }
102
103 protected function optimalOrder() {
104 return 'fifo';
105 }
106
107 protected function supportsDelayedJobs() {
108 return true;
109 }
110
111 /**
112 * @see JobQueue::doIsEmpty()
113 * @return bool
114 * @throws JobQueueError
115 */
116 protected function doIsEmpty() {
117 return $this->doGetSize() == 0;
118 }
119
120 /**
121 * @see JobQueue::doGetSize()
122 * @return int
123 * @throws JobQueueError
124 */
125 protected function doGetSize() {
126 $conn = $this->getConnection();
127 try {
128 return $conn->lSize( $this->getQueueKey( 'l-unclaimed' ) );
129 } catch ( RedisException $e ) {
130 $this->throwRedisException( $conn, $e );
131 }
132 }
133
134 /**
135 * @see JobQueue::doGetAcquiredCount()
136 * @return int
137 * @throws JobQueueError
138 */
139 protected function doGetAcquiredCount() {
140 $conn = $this->getConnection();
141 try {
142 $conn->multi( Redis::PIPELINE );
143 $conn->zSize( $this->getQueueKey( 'z-claimed' ) );
144 $conn->zSize( $this->getQueueKey( 'z-abandoned' ) );
145
146 return array_sum( $conn->exec() );
147 } catch ( RedisException $e ) {
148 $this->throwRedisException( $conn, $e );
149 }
150 }
151
152 /**
153 * @see JobQueue::doGetDelayedCount()
154 * @return int
155 * @throws JobQueueError
156 */
157 protected function doGetDelayedCount() {
158 $conn = $this->getConnection();
159 try {
160 return $conn->zSize( $this->getQueueKey( 'z-delayed' ) );
161 } catch ( RedisException $e ) {
162 $this->throwRedisException( $conn, $e );
163 }
164 }
165
166 /**
167 * @see JobQueue::doGetAbandonedCount()
168 * @return int
169 * @throws JobQueueError
170 */
171 protected function doGetAbandonedCount() {
172 $conn = $this->getConnection();
173 try {
174 return $conn->zSize( $this->getQueueKey( 'z-abandoned' ) );
175 } catch ( RedisException $e ) {
176 $this->throwRedisException( $conn, $e );
177 }
178 }
179
180 /**
181 * @see JobQueue::doBatchPush()
182 * @param array $jobs
183 * @param int $flags
184 * @return void
185 * @throws JobQueueError
186 */
187 protected function doBatchPush( array $jobs, $flags ) {
188 // Convert the jobs into field maps (de-duplicated against each other)
189 $items = array(); // (job ID => job fields map)
190 foreach ( $jobs as $job ) {
191 $item = $this->getNewJobFields( $job );
192 if ( strlen( $item['sha1'] ) ) { // hash identifier => de-duplicate
193 $items[$item['sha1']] = $item;
194 } else {
195 $items[$item['uuid']] = $item;
196 }
197 }
198
199 if ( !count( $items ) ) {
200 return; // nothing to do
201 }
202
203 $conn = $this->getConnection();
204 try {
205 // Actually push the non-duplicate jobs into the queue...
206 if ( $flags & self::QOS_ATOMIC ) {
207 $batches = array( $items ); // all or nothing
208 } else {
209 $batches = array_chunk( $items, 100 ); // avoid tying up the server
210 }
211 $failed = 0;
212 $pushed = 0;
213 foreach ( $batches as $itemBatch ) {
214 $added = $this->pushBlobs( $conn, $itemBatch );
215 if ( is_int( $added ) ) {
216 $pushed += $added;
217 } else {
218 $failed += count( $itemBatch );
219 }
220 }
221 if ( $failed > 0 ) {
222 wfDebugLog( 'JobQueueRedis', "Could not insert {$failed} {$this->type} job(s)." );
223
224 throw new RedisException( "Could not insert {$failed} {$this->type} job(s)." );
225 }
226 JobQueue::incrStats( 'inserts', $this->type, count( $items ) );
227 JobQueue::incrStats( 'dupe_inserts', $this->type,
228 count( $items ) - $failed - $pushed );
229 } catch ( RedisException $e ) {
230 $this->throwRedisException( $conn, $e );
231 }
232 }
233
234 /**
235 * @param RedisConnRef $conn
236 * @param array $items List of results from JobQueueRedis::getNewJobFields()
237 * @return int Number of jobs inserted (duplicates are ignored)
238 * @throws RedisException
239 */
240 protected function pushBlobs( RedisConnRef $conn, array $items ) {
241 $args = array(); // ([id, sha1, rtime, blob [, id, sha1, rtime, blob ... ] ] )
242 foreach ( $items as $item ) {
243 $args[] = (string)$item['uuid'];
244 $args[] = (string)$item['sha1'];
245 $args[] = (string)$item['rtimestamp'];
246 $args[] = (string)$this->serialize( $item );
247 }
248 static $script =
249 <<<LUA
250 local kUnclaimed, kSha1ById, kIdBySha1, kDelayed, kData = unpack(KEYS)
251 if #ARGV % 4 ~= 0 then return redis.error_reply('Unmatched arguments') end
252 local pushed = 0
253 for i = 1,#ARGV,4 do
254 local id,sha1,rtimestamp,blob = ARGV[i],ARGV[i+1],ARGV[i+2],ARGV[i+3]
255 if sha1 == '' or redis.call('hExists',kIdBySha1,sha1) == 0 then
256 if 1*rtimestamp > 0 then
257 -- Insert into delayed queue (release time as score)
258 redis.call('zAdd',kDelayed,rtimestamp,id)
259 else
260 -- Insert into unclaimed queue
261 redis.call('lPush',kUnclaimed,id)
262 end
263 if sha1 ~= '' then
264 redis.call('hSet',kSha1ById,id,sha1)
265 redis.call('hSet',kIdBySha1,sha1,id)
266 end
267 redis.call('hSet',kData,id,blob)
268 pushed = pushed + 1
269 end
270 end
271 return pushed
272 LUA;
273 return $conn->luaEval( $script,
274 array_merge(
275 array(
276 $this->getQueueKey( 'l-unclaimed' ), # KEYS[1]
277 $this->getQueueKey( 'h-sha1ById' ), # KEYS[2]
278 $this->getQueueKey( 'h-idBySha1' ), # KEYS[3]
279 $this->getQueueKey( 'z-delayed' ), # KEYS[4]
280 $this->getQueueKey( 'h-data' ), # KEYS[5]
281 ),
282 $args
283 ),
284 5 # number of first argument(s) that are keys
285 );
286 }
287
288 /**
289 * @see JobQueue::doPop()
290 * @return Job|bool
291 * @throws JobQueueError
292 */
293 protected function doPop() {
294 $job = false;
295
296 $conn = $this->getConnection();
297 try {
298 do {
299 $blob = $this->popAndAcquireBlob( $conn );
300 if ( !is_string( $blob ) ) {
301 break; // no jobs; nothing to do
302 }
303
304 JobQueue::incrStats( 'job-pop', $this->type );
305 $item = $this->unserialize( $blob );
306 if ( $item === false ) {
307 wfDebugLog( 'JobQueueRedis', "Could not unserialize {$this->type} job." );
308 continue;
309 }
310
311 // If $item is invalid, the runner loop recyling will cleanup as needed
312 $job = $this->getJobFromFields( $item ); // may be false
313 } while ( !$job ); // job may be false if invalid
314 } catch ( RedisException $e ) {
315 $this->throwRedisException( $conn, $e );
316 }
317
318 return $job;
319 }
320
321 /**
322 * @param RedisConnRef $conn
323 * @return array Serialized string or false
324 * @throws RedisException
325 */
326 protected function popAndAcquireBlob( RedisConnRef $conn ) {
327 static $script =
328 <<<LUA
329 local kUnclaimed, kSha1ById, kIdBySha1, kClaimed, kAttempts, kData = unpack(KEYS)
330 -- Pop an item off the queue
331 local id = redis.call('rPop',kUnclaimed)
332 if not id then return false end
333 -- Allow new duplicates of this job
334 local sha1 = redis.call('hGet',kSha1ById,id)
335 if sha1 then redis.call('hDel',kIdBySha1,sha1) end
336 redis.call('hDel',kSha1ById,id)
337 -- Mark the jobs as claimed and return it
338 redis.call('zAdd',kClaimed,ARGV[1],id)
339 redis.call('hIncrBy',kAttempts,id,1)
340 return redis.call('hGet',kData,id)
341 LUA;
342 return $conn->luaEval( $script,
343 array(
344 $this->getQueueKey( 'l-unclaimed' ), # KEYS[1]
345 $this->getQueueKey( 'h-sha1ById' ), # KEYS[2]
346 $this->getQueueKey( 'h-idBySha1' ), # KEYS[3]
347 $this->getQueueKey( 'z-claimed' ), # KEYS[4]
348 $this->getQueueKey( 'h-attempts' ), # KEYS[5]
349 $this->getQueueKey( 'h-data' ), # KEYS[6]
350 time(), # ARGV[1] (injected to be replication-safe)
351 ),
352 6 # number of first argument(s) that are keys
353 );
354 }
355
356 /**
357 * @see JobQueue::doAck()
358 * @param Job $job
359 * @return Job|bool
360 * @throws UnexpectedValueException
361 * @throws JobQueueError
362 */
363 protected function doAck( Job $job ) {
364 if ( !isset( $job->metadata['uuid'] ) ) {
365 throw new UnexpectedValueException( "Job of type '{$job->getType()}' has no UUID." );
366 }
367
368 $uuid = $job->metadata['uuid'];
369 $conn = $this->getConnection();
370 try {
371 static $script =
372 <<<LUA
373 local kClaimed, kAttempts, kData = unpack(KEYS)
374 -- Unmark the job as claimed
375 redis.call('zRem',kClaimed,ARGV[1])
376 redis.call('hDel',kAttempts,ARGV[1])
377 -- Delete the job data itself
378 return redis.call('hDel',kData,ARGV[1])
379 LUA;
380 $res = $conn->luaEval( $script,
381 array(
382 $this->getQueueKey( 'z-claimed' ), # KEYS[1]
383 $this->getQueueKey( 'h-attempts' ), # KEYS[2]
384 $this->getQueueKey( 'h-data' ), # KEYS[3]
385 $uuid # ARGV[1]
386 ),
387 3 # number of first argument(s) that are keys
388 );
389
390 if ( !$res ) {
391 wfDebugLog( 'JobQueueRedis', "Could not acknowledge {$this->type} job $uuid." );
392
393 return false;
394 }
395
396 JobQueue::incrStats( 'job-ack', $this->type );
397 } catch ( RedisException $e ) {
398 $this->throwRedisException( $conn, $e );
399 }
400
401 return true;
402 }
403
404 /**
405 * @see JobQueue::doDeduplicateRootJob()
406 * @param IJobSpecification $job
407 * @return bool
408 * @throws JobQueueError
409 * @throws LogicException
410 */
411 protected function doDeduplicateRootJob( IJobSpecification $job ) {
412 if ( !$job->hasRootJobParams() ) {
413 throw new LogicException( "Cannot register root job; missing parameters." );
414 }
415 $params = $job->getRootJobParams();
416
417 $key = $this->getRootJobCacheKey( $params['rootJobSignature'] );
418
419 $conn = $this->getConnection();
420 try {
421 $timestamp = $conn->get( $key ); // current last timestamp of this job
422 if ( $timestamp && $timestamp >= $params['rootJobTimestamp'] ) {
423 return true; // a newer version of this root job was enqueued
424 }
425
426 // Update the timestamp of the last root job started at the location...
427 return $conn->set( $key, $params['rootJobTimestamp'], self::ROOTJOB_TTL ); // 2 weeks
428 } catch ( RedisException $e ) {
429 $this->throwRedisException( $conn, $e );
430 }
431 }
432
433 /**
434 * @see JobQueue::doIsRootJobOldDuplicate()
435 * @param Job $job
436 * @return bool
437 * @throws JobQueueError
438 */
439 protected function doIsRootJobOldDuplicate( Job $job ) {
440 if ( !$job->hasRootJobParams() ) {
441 return false; // job has no de-deplication info
442 }
443 $params = $job->getRootJobParams();
444
445 $conn = $this->getConnection();
446 try {
447 // Get the last time this root job was enqueued
448 $timestamp = $conn->get( $this->getRootJobCacheKey( $params['rootJobSignature'] ) );
449 } catch ( RedisException $e ) {
450 $timestamp = false;
451 $this->throwRedisException( $conn, $e );
452 }
453
454 // Check if a new root job was started at the location after this one's...
455 return ( $timestamp && $timestamp > $params['rootJobTimestamp'] );
456 }
457
458 /**
459 * @see JobQueue::doDelete()
460 * @return bool
461 * @throws JobQueueError
462 */
463 protected function doDelete() {
464 static $props = array( 'l-unclaimed', 'z-claimed', 'z-abandoned',
465 'z-delayed', 'h-idBySha1', 'h-sha1ById', 'h-attempts', 'h-data' );
466
467 $conn = $this->getConnection();
468 try {
469 $keys = array();
470 foreach ( $props as $prop ) {
471 $keys[] = $this->getQueueKey( $prop );
472 }
473
474 return ( $conn->delete( $keys ) !== false );
475 } catch ( RedisException $e ) {
476 $this->throwRedisException( $conn, $e );
477 }
478 }
479
480 /**
481 * @see JobQueue::getAllQueuedJobs()
482 * @return Iterator
483 * @throws JobQueueError
484 */
485 public function getAllQueuedJobs() {
486 $conn = $this->getConnection();
487 try {
488 $uids = $conn->lRange( $this->getQueueKey( 'l-unclaimed' ), 0, -1 );
489 } catch ( RedisException $e ) {
490 $this->throwRedisException( $conn, $e );
491 }
492
493 return $this->getJobIterator( $conn, $uids );
494 }
495
496 /**
497 * @see JobQueue::getAllDelayedJobs()
498 * @return Iterator
499 * @throws JobQueueError
500 */
501 public function getAllDelayedJobs() {
502 $conn = $this->getConnection();
503 try {
504 $uids = $conn->zRange( $this->getQueueKey( 'z-delayed' ), 0, -1 );
505 } catch ( RedisException $e ) {
506 $this->throwRedisException( $conn, $e );
507 }
508
509 return $this->getJobIterator( $conn, $uids );
510 }
511
512 /**
513 * @see JobQueue::getAllAcquiredJobs()
514 * @return Iterator
515 * @throws JobQueueError
516 */
517 public function getAllAcquiredJobs() {
518 $conn = $this->getConnection();
519 try {
520 $uids = $conn->zRange( $this->getQueueKey( 'z-claimed' ), 0, -1 );
521 } catch ( RedisException $e ) {
522 $this->throwRedisException( $conn, $e );
523 }
524
525 return $this->getJobIterator( $conn, $uids );
526 }
527
528 /**
529 * @see JobQueue::getAllAbandonedJobs()
530 * @return Iterator
531 * @throws JobQueueError
532 */
533 public function getAllAbandonedJobs() {
534 $conn = $this->getConnection();
535 try {
536 $uids = $conn->zRange( $this->getQueueKey( 'z-abandoned' ), 0, -1 );
537 } catch ( RedisException $e ) {
538 $this->throwRedisException( $conn, $e );
539 }
540
541 return $this->getJobIterator( $conn, $uids );
542 }
543
544 /**
545 * @param RedisConnRef $conn
546 * @param array $uids List of job UUIDs
547 * @return MappedIterator
548 */
549 protected function getJobIterator( RedisConnRef $conn, array $uids ) {
550 $that = $this;
551
552 return new MappedIterator(
553 $uids,
554 function ( $uid ) use ( $that, $conn ) {
555 return $that->getJobFromUidInternal( $uid, $conn );
556 },
557 array( 'accept' => function ( $job ) {
558 return is_object( $job );
559 } )
560 );
561 }
562
563 public function getCoalesceLocationInternal() {
564 return "RedisServer:" . $this->server;
565 }
566
567 protected function doGetSiblingQueuesWithJobs( array $types ) {
568 return array_keys( array_filter( $this->doGetSiblingQueueSizes( $types ) ) );
569 }
570
571 protected function doGetSiblingQueueSizes( array $types ) {
572 $sizes = array(); // (type => size)
573 $types = array_values( $types ); // reindex
574 $conn = $this->getConnection();
575 try {
576 $conn->multi( Redis::PIPELINE );
577 foreach ( $types as $type ) {
578 $conn->lSize( $this->getQueueKey( 'l-unclaimed', $type ) );
579 }
580 $res = $conn->exec();
581 if ( is_array( $res ) ) {
582 foreach ( $res as $i => $size ) {
583 $sizes[$types[$i]] = $size;
584 }
585 }
586 } catch ( RedisException $e ) {
587 $this->throwRedisException( $conn, $e );
588 }
589
590 return $sizes;
591 }
592
593 /**
594 * This function should not be called outside JobQueueRedis
595 *
596 * @param string $uid
597 * @param RedisConnRef $conn
598 * @return Job|bool Returns false if the job does not exist
599 * @throws JobQueueError
600 * @throws UnexpectedValueException
601 */
602 public function getJobFromUidInternal( $uid, RedisConnRef $conn ) {
603 try {
604 $data = $conn->hGet( $this->getQueueKey( 'h-data' ), $uid );
605 if ( $data === false ) {
606 return false; // not found
607 }
608 $item = $this->unserialize( $data );
609 if ( !is_array( $item ) ) { // this shouldn't happen
610 throw new UnexpectedValueException( "Could not find job with ID '$uid'." );
611 }
612 $title = Title::makeTitle( $item['namespace'], $item['title'] );
613 $job = Job::factory( $item['type'], $title, $item['params'] );
614 $job->metadata['uuid'] = $item['uuid'];
615 $job->metadata['timestamp'] = $item['timestamp'];
616
617 return $job;
618 } catch ( RedisException $e ) {
619 $this->throwRedisException( $conn, $e );
620 }
621 }
622
623 /**
624 * @param IJobSpecification $job
625 * @return array
626 */
627 protected function getNewJobFields( IJobSpecification $job ) {
628 return array(
629 // Fields that describe the nature of the job
630 'type' => $job->getType(),
631 'namespace' => $job->getTitle()->getNamespace(),
632 'title' => $job->getTitle()->getDBkey(),
633 'params' => $job->getParams(),
634 // Some jobs cannot run until a "release timestamp"
635 'rtimestamp' => $job->getReleaseTimestamp() ?: 0,
636 // Additional job metadata
637 'uuid' => UIDGenerator::newRawUUIDv4( UIDGenerator::QUICK_RAND ),
638 'sha1' => $job->ignoreDuplicates()
639 ? wfBaseConvert( sha1( serialize( $job->getDeduplicationInfo() ) ), 16, 36, 31 )
640 : '',
641 'timestamp' => time() // UNIX timestamp
642 );
643 }
644
645 /**
646 * @param array $fields
647 * @return Job|bool
648 */
649 protected function getJobFromFields( array $fields ) {
650 $title = Title::makeTitle( $fields['namespace'], $fields['title'] );
651 $job = Job::factory( $fields['type'], $title, $fields['params'] );
652 $job->metadata['uuid'] = $fields['uuid'];
653 $job->metadata['timestamp'] = $fields['timestamp'];
654
655 return $job;
656 }
657
658 /**
659 * @param array $fields
660 * @return string Serialized and possibly compressed version of $fields
661 */
662 protected function serialize( array $fields ) {
663 $blob = serialize( $fields );
664 if ( $this->compression === 'gzip'
665 && strlen( $blob ) >= 1024
666 && function_exists( 'gzdeflate' )
667 ) {
668 $object = (object)array( 'blob' => gzdeflate( $blob ), 'enc' => 'gzip' );
669 $blobz = serialize( $object );
670
671 return ( strlen( $blobz ) < strlen( $blob ) ) ? $blobz : $blob;
672 } else {
673 return $blob;
674 }
675 }
676
677 /**
678 * @param string $blob
679 * @return array|bool Unserialized version of $blob or false
680 */
681 protected function unserialize( $blob ) {
682 $fields = unserialize( $blob );
683 if ( is_object( $fields ) ) {
684 if ( $fields->enc === 'gzip' && function_exists( 'gzinflate' ) ) {
685 $fields = unserialize( gzinflate( $fields->blob ) );
686 } else {
687 $fields = false;
688 }
689 }
690
691 return is_array( $fields ) ? $fields : false;
692 }
693
694 /**
695 * Get a connection to the server that handles all sub-queues for this queue
696 *
697 * @return RedisConnRef
698 * @throws JobQueueConnectionError
699 */
700 protected function getConnection() {
701 $conn = $this->redisPool->getConnection( $this->server );
702 if ( !$conn ) {
703 throw new JobQueueConnectionError( "Unable to connect to redis server." );
704 }
705
706 return $conn;
707 }
708
709 /**
710 * @param RedisConnRef $conn
711 * @param RedisException $e
712 * @throws JobQueueError
713 */
714 protected function throwRedisException( RedisConnRef $conn, $e ) {
715 $this->redisPool->handleError( $conn, $e );
716 throw new JobQueueError( "Redis server error: {$e->getMessage()}\n" );
717 }
718
719 /**
720 * @param string $prop
721 * @param string|null $type
722 * @return string
723 */
724 private function getQueueKey( $prop, $type = null ) {
725 $type = is_string( $type ) ? $type : $this->type;
726 list( $db, $prefix ) = wfSplitWikiID( $this->wiki );
727 if ( strlen( $this->key ) ) { // namespaced queue (for testing)
728 return wfForeignMemcKey( $db, $prefix, 'jobqueue', $type, $this->key, $prop );
729 } else {
730 return wfForeignMemcKey( $db, $prefix, 'jobqueue', $type, $prop );
731 }
732 }
733
734 /**
735 * @param string $key
736 * @return void
737 */
738 public function setTestingPrefix( $key ) {
739 $this->key = $key;
740 }
741 }