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.
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.
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
21 * @defgroup JobQueue JobQueue
23 use MediaWiki\MediaWikiServices
;
26 * Class to handle enqueueing and running of background jobs
31 abstract class JobQueue
{
32 /** @var string Wiki ID */
34 /** @var string Job type */
36 /** @var string Job priority for pop() */
38 /** @var int Time to live in seconds */
40 /** @var int Maximum number of times to try a job */
42 /** @var string|bool Read only rationale (or false if r/w) */
43 protected $readOnlyReason;
48 const QOS_ATOMIC
= 1; // integer; "all-or-nothing" job insertions
50 const ROOTJOB_TTL
= 2419200; // integer; seconds to remember root jobs (28 days)
53 * @param array $params
56 protected function __construct( array $params ) {
57 $this->domain
= $params['domain'] ??
$params['wiki']; // b/c
58 $this->type
= $params['type'];
59 $this->claimTTL
= $params['claimTTL'] ??
0;
60 $this->maxTries
= $params['maxTries'] ??
3;
61 if ( isset( $params['order'] ) && $params['order'] !== 'any' ) {
62 $this->order
= $params['order'];
64 $this->order
= $this->optimalOrder();
66 if ( !in_array( $this->order
, $this->supportedOrders() ) ) {
67 throw new MWException( __CLASS__
. " does not support '{$this->order}' order." );
69 $this->dupCache
= wfGetCache( CACHE_ANYTHING
);
70 $this->readOnlyReason
= $params['readOnlyReason'] ??
false;
74 * Get a job queue object of the specified type.
76 * - class : What job class to use (determines job type)
77 * - domain : Database domain ID of the wiki the jobs are for (defaults to current wiki)
78 * - type : The name of the job types this queue handles
79 * - order : Order that pop() selects jobs, one of "fifo", "timestamp" or "random".
80 * If "fifo" is used, the queue will effectively be FIFO. Note that job
81 * completion will not appear to be exactly FIFO if there are multiple
82 * job runners since jobs can take different times to finish once popped.
83 * If "timestamp" is used, the queue will at least be loosely ordered
84 * by timestamp, allowing for some jobs to be popped off out of order.
85 * If "random" is used, pop() will pick jobs in random order.
86 * Note that it may only be weakly random (e.g. a lottery of the oldest X).
87 * If "any" is choosen, the queue will use whatever order is the fastest.
88 * This might be useful for improving concurrency for job acquisition.
89 * - claimTTL : If supported, the queue will recycle jobs that have been popped
90 * but not acknowledged as completed after this many seconds. Recycling
91 * of jobs simply means re-inserting them into the queue. Jobs can be
92 * attempted up to three times before being discarded.
93 * - readOnlyReason : Set this to a string to make the queue read-only.
95 * Queue classes should throw an exception if they do not support the options given.
97 * @param array $params
101 final public static function factory( array $params ) {
102 $class = $params['class'];
103 if ( !class_exists( $class ) ) {
104 throw new MWException( "Invalid job queue class '$class'." );
106 $obj = new $class( $params );
107 if ( !( $obj instanceof self
) ) {
108 throw new MWException( "Class '$class' is not a " . __CLASS__
. " class." );
115 * @return string Wiki ID
117 final public function getDomain() {
118 return $this->domain
;
122 * @return string Wiki ID
125 final public function getWiki() {
126 return WikiMap
::getWikiIdFromDbDomain( $this->domain
);
130 * @return string Job type that this queue handles
132 final public function getType() {
137 * @return string One of (random, timestamp, fifo, undefined)
139 final public function getOrder() {
144 * Get the allowed queue orders for configuration validation
146 * @return array Subset of (random, timestamp, fifo, undefined)
148 abstract protected function supportedOrders();
151 * Get the default queue order to use if configuration does not specify one
153 * @return string One of (random, timestamp, fifo, undefined)
155 abstract protected function optimalOrder();
158 * Find out if delayed jobs are supported for configuration validation
160 * @return bool Whether delayed jobs are supported
162 protected function supportsDelayedJobs() {
163 return false; // not implemented
167 * @return bool Whether delayed jobs are enabled
170 final public function delayedJobsEnabled() {
171 return $this->supportsDelayedJobs();
175 * @return string|bool Read-only rational or false if r/w
178 public function getReadOnlyReason() {
179 return $this->readOnlyReason
;
183 * Quickly check if the queue has no available (unacquired, non-delayed) jobs.
184 * Queue classes should use caching if they are any slower without memcached.
186 * If caching is used, this might return false when there are actually no jobs.
187 * If pop() is called and returns false then it should correct the cache. Also,
188 * calling flushCaches() first prevents this. However, this affect is typically
189 * not distinguishable from the race condition between isEmpty() and pop().
192 * @throws JobQueueError
194 final public function isEmpty() {
195 $res = $this->doIsEmpty();
201 * @see JobQueue::isEmpty()
204 abstract protected function doIsEmpty();
207 * Get the number of available (unacquired, non-delayed) jobs in the queue.
208 * Queue classes should use caching if they are any slower without memcached.
210 * If caching is used, this number might be out of date for a minute.
213 * @throws JobQueueError
215 final public function getSize() {
216 $res = $this->doGetSize();
222 * @see JobQueue::getSize()
225 abstract protected function doGetSize();
228 * Get the number of acquired jobs (these are temporarily out of the queue).
229 * Queue classes should use caching if they are any slower without memcached.
231 * If caching is used, this number might be out of date for a minute.
234 * @throws JobQueueError
236 final public function getAcquiredCount() {
237 $res = $this->doGetAcquiredCount();
243 * @see JobQueue::getAcquiredCount()
246 abstract protected function doGetAcquiredCount();
249 * Get the number of delayed jobs (these are temporarily out of the queue).
250 * Queue classes should use caching if they are any slower without memcached.
252 * If caching is used, this number might be out of date for a minute.
255 * @throws JobQueueError
258 final public function getDelayedCount() {
259 $res = $this->doGetDelayedCount();
265 * @see JobQueue::getDelayedCount()
268 protected function doGetDelayedCount() {
269 return 0; // not implemented
273 * Get the number of acquired jobs that can no longer be attempted.
274 * Queue classes should use caching if they are any slower without memcached.
276 * If caching is used, this number might be out of date for a minute.
279 * @throws JobQueueError
281 final public function getAbandonedCount() {
282 $res = $this->doGetAbandonedCount();
288 * @see JobQueue::getAbandonedCount()
291 protected function doGetAbandonedCount() {
292 return 0; // not implemented
296 * Push one or more jobs into the queue.
297 * This does not require $wgJobClasses to be set for the given job type.
298 * Outside callers should use JobQueueGroup::push() instead of this function.
300 * @param IJobSpecification|IJobSpecification[] $jobs
301 * @param int $flags Bitfield (supports JobQueue::QOS_ATOMIC)
303 * @throws JobQueueError
305 final public function push( $jobs, $flags = 0 ) {
306 $jobs = is_array( $jobs ) ?
$jobs : [ $jobs ];
307 $this->batchPush( $jobs, $flags );
311 * Push a batch of jobs into the queue.
312 * This does not require $wgJobClasses to be set for the given job type.
313 * Outside callers should use JobQueueGroup::push() instead of this function.
315 * @param IJobSpecification[] $jobs
316 * @param int $flags Bitfield (supports JobQueue::QOS_ATOMIC)
318 * @throws MWException
320 final public function batchPush( array $jobs, $flags = 0 ) {
321 $this->assertNotReadOnly();
323 if ( $jobs === [] ) {
324 return; // nothing to do
327 foreach ( $jobs as $job ) {
328 if ( $job->getType() !== $this->type
) {
329 throw new MWException(
330 "Got '{$job->getType()}' job; expected a '{$this->type}' job." );
331 } elseif ( $job->getReleaseTimestamp() && !$this->supportsDelayedJobs() ) {
332 throw new MWException(
333 "Got delayed '{$job->getType()}' job; delays are not supported." );
337 $this->doBatchPush( $jobs, $flags );
339 foreach ( $jobs as $job ) {
340 if ( $job->isRootJob() ) {
341 $this->deduplicateRootJob( $job );
347 * @see JobQueue::batchPush()
348 * @param IJobSpecification[] $jobs
351 abstract protected function doBatchPush( array $jobs, $flags );
354 * Pop a job off of the queue.
355 * This requires $wgJobClasses to be set for the given job type.
356 * Outside callers should use JobQueueGroup::pop() instead of this function.
358 * @throws MWException
359 * @return Job|bool Returns false if there are no jobs
361 final public function pop() {
362 global $wgJobClasses;
364 $this->assertNotReadOnly();
365 if ( !WikiMap
::isCurrentWikiDbDomain( $this->domain
) ) {
366 throw new MWException(
367 "Cannot pop '{$this->type}' job off foreign '{$this->domain}' wiki queue." );
368 } elseif ( !isset( $wgJobClasses[$this->type
] ) ) {
369 // Do not pop jobs if there is no class for the queue type
370 throw new MWException( "Unrecognized job type '{$this->type}'." );
373 $job = $this->doPop();
375 // Flag this job as an old duplicate based on its "root" job...
377 if ( $job && $this->isRootJobOldDuplicate( $job ) ) {
378 self
::incrStats( 'dupe_pops', $this->type
);
379 $job = DuplicateJob
::newFromJob( $job ); // convert to a no-op
381 } catch ( Exception
$e ) {
382 // don't lose jobs over this
389 * @see JobQueue::pop()
392 abstract protected function doPop();
395 * Acknowledge that a job was completed.
397 * This does nothing for certain queue classes or if "claimTTL" is not set.
398 * Outside callers should use JobQueueGroup::ack() instead of this function.
402 * @throws MWException
404 final public function ack( Job
$job ) {
405 $this->assertNotReadOnly();
406 if ( $job->getType() !== $this->type
) {
407 throw new MWException( "Got '{$job->getType()}' job; expected '{$this->type}'." );
410 $this->doAck( $job );
414 * @see JobQueue::ack()
417 abstract protected function doAck( Job
$job );
420 * Register the "root job" of a given job into the queue for de-duplication.
421 * This should only be called right *after* all the new jobs have been inserted.
422 * This is used to turn older, duplicate, job entries into no-ops. The root job
423 * information will remain in the registry until it simply falls out of cache.
425 * This requires that $job has two special fields in the "params" array:
426 * - rootJobSignature : hash (e.g. SHA1) that identifies the task
427 * - rootJobTimestamp : TS_MW timestamp of this instance of the task
429 * A "root job" is a conceptual job that consist of potentially many smaller jobs
430 * that are actually inserted into the queue. For example, "refreshLinks" jobs are
431 * spawned when a template is edited. One can think of the task as "update links
432 * of pages that use template X" and an instance of that task as a "root job".
433 * However, what actually goes into the queue are range and leaf job subtypes.
434 * Since these jobs include things like page ID ranges and DB master positions,
435 * and can morph into smaller jobs recursively, simple duplicate detection
436 * for individual jobs being identical (like that of job_sha1) is not useful.
438 * In the case of "refreshLinks", if these jobs are still in the queue when the template
439 * is edited again, we want all of these old refreshLinks jobs for that template to become
440 * no-ops. This can greatly reduce server load, since refreshLinks jobs involves parsing.
441 * Essentially, the new batch of jobs belong to a new "root job" and the older ones to a
442 * previous "root job" for the same task of "update links of pages that use template X".
444 * This does nothing for certain queue classes.
446 * @param IJobSpecification $job
447 * @throws MWException
450 final public function deduplicateRootJob( IJobSpecification
$job ) {
451 $this->assertNotReadOnly();
452 if ( $job->getType() !== $this->type
) {
453 throw new MWException( "Got '{$job->getType()}' job; expected '{$this->type}'." );
456 return $this->doDeduplicateRootJob( $job );
460 * @see JobQueue::deduplicateRootJob()
461 * @param IJobSpecification $job
462 * @throws MWException
465 protected function doDeduplicateRootJob( IJobSpecification
$job ) {
466 if ( !$job->hasRootJobParams() ) {
467 throw new MWException( "Cannot register root job; missing parameters." );
469 $params = $job->getRootJobParams();
471 $key = $this->getRootJobCacheKey( $params['rootJobSignature'] );
472 // Callers should call JobQueueGroup::push() before this method so that if the insert
473 // fails, the de-duplication registration will be aborted. Since the insert is
474 // deferred till "transaction idle", do the same here, so that the ordering is
475 // maintained. Having only the de-duplication registration succeed would cause
476 // jobs to become no-ops without any actual jobs that made them redundant.
477 $timestamp = $this->dupCache
->get( $key ); // current last timestamp of this job
478 if ( $timestamp && $timestamp >= $params['rootJobTimestamp'] ) {
479 return true; // a newer version of this root job was enqueued
482 // Update the timestamp of the last root job started at the location...
483 return $this->dupCache
->set( $key, $params['rootJobTimestamp'], JobQueueDB
::ROOTJOB_TTL
);
487 * Check if the "root" job of a given job has been superseded by a newer one
490 * @throws MWException
493 final protected function isRootJobOldDuplicate( Job
$job ) {
494 if ( $job->getType() !== $this->type
) {
495 throw new MWException( "Got '{$job->getType()}' job; expected '{$this->type}'." );
497 $isDuplicate = $this->doIsRootJobOldDuplicate( $job );
503 * @see JobQueue::isRootJobOldDuplicate()
507 protected function doIsRootJobOldDuplicate( Job
$job ) {
508 if ( !$job->hasRootJobParams() ) {
509 return false; // job has no de-deplication info
511 $params = $job->getRootJobParams();
513 $key = $this->getRootJobCacheKey( $params['rootJobSignature'] );
514 // Get the last time this root job was enqueued
515 $timestamp = $this->dupCache
->get( $key );
517 // Check if a new root job was started at the location after this one's...
518 return ( $timestamp && $timestamp > $params['rootJobTimestamp'] );
522 * @param string $signature Hash identifier of the root job
525 protected function getRootJobCacheKey( $signature ) {
526 return $this->dupCache
->makeGlobalKey(
536 * Deleted all unclaimed and delayed jobs from the queue
538 * @throws JobQueueError
542 final public function delete() {
543 $this->assertNotReadOnly();
549 * @see JobQueue::delete()
550 * @throws MWException
552 protected function doDelete() {
553 throw new MWException( "This method is not implemented." );
557 * Wait for any replica DBs or backup servers to catch up.
559 * This does nothing for certain queue classes.
562 * @throws JobQueueError
564 final public function waitForBackups() {
565 $this->doWaitForBackups();
569 * @see JobQueue::waitForBackups()
572 protected function doWaitForBackups() {
576 * Clear any process and persistent caches
580 final public function flushCaches() {
581 $this->doFlushCaches();
585 * @see JobQueue::flushCaches()
588 protected function doFlushCaches() {
592 * Get an iterator to traverse over all available jobs in this queue.
593 * This does not include jobs that are currently acquired or delayed.
594 * Note: results may be stale if the queue is concurrently modified.
597 * @throws JobQueueError
599 abstract public function getAllQueuedJobs();
602 * Get an iterator to traverse over all delayed jobs in this queue.
603 * Note: results may be stale if the queue is concurrently modified.
606 * @throws JobQueueError
609 public function getAllDelayedJobs() {
610 return new ArrayIterator( [] ); // not implemented
614 * Get an iterator to traverse over all claimed jobs in this queue
616 * Callers should be quick to iterator over it or few results
617 * will be returned due to jobs being acknowledged and deleted
620 * @throws JobQueueError
623 public function getAllAcquiredJobs() {
624 return new ArrayIterator( [] ); // not implemented
628 * Get an iterator to traverse over all abandoned jobs in this queue
631 * @throws JobQueueError
634 public function getAllAbandonedJobs() {
635 return new ArrayIterator( [] ); // not implemented
639 * Do not use this function outside of JobQueue/JobQueueGroup
644 public function getCoalesceLocationInternal() {
649 * Check whether each of the given queues are empty.
650 * This is used for batching checks for queues stored at the same place.
652 * @param array $types List of queues types
653 * @return array|null (list of non-empty queue types) or null if unsupported
654 * @throws MWException
657 final public function getSiblingQueuesWithJobs( array $types ) {
658 return $this->doGetSiblingQueuesWithJobs( $types );
662 * @see JobQueue::getSiblingQueuesWithJobs()
663 * @param array $types List of queues types
664 * @return array|null (list of queue types) or null if unsupported
666 protected function doGetSiblingQueuesWithJobs( array $types ) {
667 return null; // not supported
671 * Check the size of each of the given queues.
672 * For queues not served by the same store as this one, 0 is returned.
673 * This is used for batching checks for queues stored at the same place.
675 * @param array $types List of queues types
676 * @return array|null (job type => whether queue is empty) or null if unsupported
677 * @throws MWException
680 final public function getSiblingQueueSizes( array $types ) {
681 return $this->doGetSiblingQueueSizes( $types );
685 * @see JobQueue::getSiblingQueuesSize()
686 * @param array $types List of queues types
687 * @return array|null (list of queue types) or null if unsupported
689 protected function doGetSiblingQueueSizes( array $types ) {
690 return null; // not supported
694 * @throws JobQueueReadOnlyError
696 protected function assertNotReadOnly() {
697 if ( $this->readOnlyReason
!== false ) {
698 throw new JobQueueReadOnlyError( "Job queue is read-only: {$this->readOnlyReason}" );
703 * Call wfIncrStats() for the queue overall and for the queue type
705 * @param string $key Event type
706 * @param string $type Job type
710 public static function incrStats( $key, $type, $delta = 1 ) {
713 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
715 $stats->updateCount( "jobqueue.{$key}.all", $delta );
716 $stats->updateCount( "jobqueue.{$key}.{$type}", $delta );