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