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