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