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
22 * @author Aaron Schulz
26 * Class to handle enqueueing and running of background jobs
31 abstract class JobQueue
{
32 /** @var string Wiki ID */
35 /** @var string Job type */
38 /** @var string Job priority for pop() */
41 /** @var int Time to live in seconds */
44 /** @var int Maximum number of times to try a job */
49 /** @var JobQueueAggregator */
52 const QOS_ATOMIC
= 1; // integer; "all-or-nothing" job insertions
54 const ROOTJOB_TTL
= 2419200; // integer; seconds to remember root jobs (28 days)
57 * @param array $params
60 protected function __construct( array $params ) {
61 $this->wiki
= $params['wiki'];
62 $this->type
= $params['type'];
63 $this->claimTTL
= isset( $params['claimTTL'] ) ?
$params['claimTTL'] : 0;
64 $this->maxTries
= isset( $params['maxTries'] ) ?
$params['maxTries'] : 3;
65 if ( isset( $params['order'] ) && $params['order'] !== 'any' ) {
66 $this->order
= $params['order'];
68 $this->order
= $this->optimalOrder();
70 if ( !in_array( $this->order
, $this->supportedOrders() ) ) {
71 throw new MWException( __CLASS__
. " does not support '{$this->order}' order." );
73 $this->dupCache
= wfGetCache( CACHE_ANYTHING
);
74 $this->aggr
= isset( $params['aggregator'] )
75 ?
$params['aggregator']
76 : new JobQueueAggregatorNull( array() );
80 * Get a job queue object of the specified type.
82 * - class : What job class to use (determines job type)
83 * - wiki : wiki ID of the wiki the jobs are for (defaults to current wiki)
84 * - type : The name of the job types this queue handles
85 * - order : Order that pop() selects jobs, one of "fifo", "timestamp" or "random".
86 * If "fifo" is used, the queue will effectively be FIFO. Note that job
87 * completion will not appear to be exactly FIFO if there are multiple
88 * job runners since jobs can take different times to finish once popped.
89 * If "timestamp" is used, the queue will at least be loosely ordered
90 * by timestamp, allowing for some jobs to be popped off out of order.
91 * If "random" is used, pop() will pick jobs in random order.
92 * Note that it may only be weakly random (e.g. a lottery of the oldest X).
93 * If "any" is choosen, the queue will use whatever order is the fastest.
94 * This might be useful for improving concurrency for job acquisition.
95 * - claimTTL : If supported, the queue will recycle jobs that have been popped
96 * but not acknowledged as completed after this many seconds. Recycling
97 * of jobs simple means re-inserting them into the queue. Jobs can be
98 * attempted up to three times before being discarded.
100 * Queue classes should throw an exception if they do not support the options given.
102 * @param array $params
104 * @throws MWException
106 final public static function factory( array $params ) {
107 $class = $params['class'];
108 if ( !class_exists( $class ) ) {
109 throw new MWException( "Invalid job queue class '$class'." );
111 $obj = new $class( $params );
112 if ( !( $obj instanceof self
) ) {
113 throw new MWException( "Class '$class' is not a " . __CLASS__
. " class." );
120 * @return string Wiki ID
122 final public function getWiki() {
127 * @return string Job type that this queue handles
129 final public function getType() {
134 * @return string One of (random, timestamp, fifo, undefined)
136 final public function getOrder() {
141 * Get the allowed queue orders for configuration validation
143 * @return array Subset of (random, timestamp, fifo, undefined)
145 abstract protected function supportedOrders();
148 * Get the default queue order to use if configuration does not specify one
150 * @return string One of (random, timestamp, fifo, undefined)
152 abstract protected function optimalOrder();
155 * Find out if delayed jobs are supported for configuration validation
157 * @return bool Whether delayed jobs are supported
159 protected function supportsDelayedJobs() {
160 return false; // not implemented
164 * Quickly check if the queue has no available (unacquired, non-delayed) jobs.
165 * Queue classes should use caching if they are any slower without memcached.
167 * If caching is used, this might return false when there are actually no jobs.
168 * If pop() is called and returns false then it should correct the cache. Also,
169 * calling flushCaches() first prevents this. However, this affect is typically
170 * not distinguishable from the race condition between isEmpty() and pop().
173 * @throws JobQueueError
175 final public function isEmpty() {
176 $res = $this->doIsEmpty();
182 * @see JobQueue::isEmpty()
185 abstract protected function doIsEmpty();
188 * Get the number of available (unacquired, non-delayed) jobs in the queue.
189 * Queue classes should use caching if they are any slower without memcached.
191 * If caching is used, this number might be out of date for a minute.
194 * @throws JobQueueError
196 final public function getSize() {
197 $res = $this->doGetSize();
203 * @see JobQueue::getSize()
206 abstract protected function doGetSize();
209 * Get the number of acquired jobs (these are temporarily out of the queue).
210 * Queue classes should use caching if they are any slower without memcached.
212 * If caching is used, this number might be out of date for a minute.
215 * @throws JobQueueError
217 final public function getAcquiredCount() {
218 $res = $this->doGetAcquiredCount();
224 * @see JobQueue::getAcquiredCount()
227 abstract protected function doGetAcquiredCount();
230 * Get the number of delayed jobs (these are temporarily out of the queue).
231 * Queue classes should use caching if they are any slower without memcached.
233 * If caching is used, this number might be out of date for a minute.
236 * @throws JobQueueError
239 final public function getDelayedCount() {
240 $res = $this->doGetDelayedCount();
246 * @see JobQueue::getDelayedCount()
249 protected function doGetDelayedCount() {
250 return 0; // not implemented
254 * Get the number of acquired jobs that can no longer be attempted.
255 * Queue classes should use caching if they are any slower without memcached.
257 * If caching is used, this number might be out of date for a minute.
260 * @throws JobQueueError
262 final public function getAbandonedCount() {
263 $res = $this->doGetAbandonedCount();
269 * @see JobQueue::getAbandonedCount()
272 protected function doGetAbandonedCount() {
273 return 0; // not implemented
277 * Push one or more jobs into the queue.
278 * This does not require $wgJobClasses to be set for the given job type.
279 * Outside callers should use JobQueueGroup::push() instead of this function.
281 * @param Job|array $jobs A single job or an array of Jobs
282 * @param int $flags Bitfield (supports JobQueue::QOS_ATOMIC)
284 * @throws JobQueueError
286 final public function push( $jobs, $flags = 0 ) {
287 $jobs = is_array( $jobs ) ?
$jobs : array( $jobs );
288 $this->batchPush( $jobs, $flags );
292 * Push a batch of jobs into the queue.
293 * This does not require $wgJobClasses to be set for the given job type.
294 * Outside callers should use JobQueueGroup::push() instead of this function.
296 * @param array $jobs List of Jobs
297 * @param int $flags Bitfield (supports JobQueue::QOS_ATOMIC)
299 * @throws MWException
301 final public function batchPush( array $jobs, $flags = 0 ) {
302 if ( !count( $jobs ) ) {
303 return; // nothing to do
306 foreach ( $jobs as $job ) {
307 if ( $job->getType() !== $this->type
) {
308 throw new MWException(
309 "Got '{$job->getType()}' job; expected a '{$this->type}' job." );
310 } elseif ( $job->getReleaseTimestamp() && !$this->supportsDelayedJobs() ) {
311 throw new MWException(
312 "Got delayed '{$job->getType()}' job; delays are not supported." );
316 $this->doBatchPush( $jobs, $flags );
317 $this->aggr
->notifyQueueNonEmpty( $this->wiki
, $this->type
);
321 * @see JobQueue::batchPush()
325 abstract protected function doBatchPush( array $jobs, $flags );
328 * Pop a job off of the queue.
329 * This requires $wgJobClasses to be set for the given job type.
330 * Outside callers should use JobQueueGroup::pop() instead of this function.
332 * @throws MWException
333 * @return Job|bool Returns false if there are no jobs
335 final public function pop() {
336 global $wgJobClasses;
338 if ( $this->wiki
!== wfWikiID() ) {
339 throw new MWException( "Cannot pop '{$this->type}' job off foreign wiki queue." );
340 } elseif ( !isset( $wgJobClasses[$this->type
] ) ) {
341 // Do not pop jobs if there is no class for the queue type
342 throw new MWException( "Unrecognized job type '{$this->type}'." );
345 $job = $this->doPop();
348 $this->aggr
->notifyQueueEmpty( $this->wiki
, $this->type
);
351 // Flag this job as an old duplicate based on its "root" job...
353 if ( $job && $this->isRootJobOldDuplicate( $job ) ) {
354 JobQueue
::incrStats( 'job-pop-duplicate', $this->type
, 1, $this->wiki
);
355 $job = DuplicateJob
::newFromJob( $job ); // convert to a no-op
357 } catch ( Exception
$e ) {
358 // don't lose jobs over this
365 * @see JobQueue::pop()
368 abstract protected function doPop();
371 * Acknowledge that a job was completed.
373 * This does nothing for certain queue classes or if "claimTTL" is not set.
374 * Outside callers should use JobQueueGroup::ack() instead of this function.
378 * @throws MWException
380 final public function ack( Job
$job ) {
381 if ( $job->getType() !== $this->type
) {
382 throw new MWException( "Got '{$job->getType()}' job; expected '{$this->type}'." );
384 $this->doAck( $job );
388 * @see JobQueue::ack()
391 abstract protected function doAck( Job
$job );
394 * Register the "root job" of a given job into the queue for de-duplication.
395 * This should only be called right *after* all the new jobs have been inserted.
396 * This is used to turn older, duplicate, job entries into no-ops. The root job
397 * information will remain in the registry until it simply falls out of cache.
399 * This requires that $job has two special fields in the "params" array:
400 * - rootJobSignature : hash (e.g. SHA1) that identifies the task
401 * - rootJobTimestamp : TS_MW timestamp of this instance of the task
403 * A "root job" is a conceptual job that consist of potentially many smaller jobs
404 * that are actually inserted into the queue. For example, "refreshLinks" jobs are
405 * spawned when a template is edited. One can think of the task as "update links
406 * of pages that use template X" and an instance of that task as a "root job".
407 * However, what actually goes into the queue are range and leaf job subtypes.
408 * Since these jobs include things like page ID ranges and DB master positions,
409 * and can morph into smaller jobs recursively, simple duplicate detection
410 * for individual jobs being identical (like that of job_sha1) is not useful.
412 * In the case of "refreshLinks", if these jobs are still in the queue when the template
413 * is edited again, we want all of these old refreshLinks jobs for that template to become
414 * no-ops. This can greatly reduce server load, since refreshLinks jobs involves parsing.
415 * Essentially, the new batch of jobs belong to a new "root job" and the older ones to a
416 * previous "root job" for the same task of "update links of pages that use template X".
418 * This does nothing for certain queue classes.
421 * @throws MWException
424 final public function deduplicateRootJob( Job
$job ) {
425 if ( $job->getType() !== $this->type
) {
426 throw new MWException( "Got '{$job->getType()}' job; expected '{$this->type}'." );
428 $ok = $this->doDeduplicateRootJob( $job );
434 * @see JobQueue::deduplicateRootJob()
436 * @throws MWException
439 protected function doDeduplicateRootJob( Job
$job ) {
440 if ( !$job->hasRootJobParams() ) {
441 throw new MWException( "Cannot register root job; missing parameters." );
443 $params = $job->getRootJobParams();
445 $key = $this->getRootJobCacheKey( $params['rootJobSignature'] );
446 // Callers should call batchInsert() and then this function so that if the insert
447 // fails, the de-duplication registration will be aborted. Since the insert is
448 // deferred till "transaction idle", do the same here, so that the ordering is
449 // maintained. Having only the de-duplication registration succeed would cause
450 // jobs to become no-ops without any actual jobs that made them redundant.
451 $timestamp = $this->dupCache
->get( $key ); // current last timestamp of this job
452 if ( $timestamp && $timestamp >= $params['rootJobTimestamp'] ) {
453 return true; // a newer version of this root job was enqueued
456 // Update the timestamp of the last root job started at the location...
457 return $this->dupCache
->set( $key, $params['rootJobTimestamp'], JobQueueDB
::ROOTJOB_TTL
);
461 * Check if the "root" job of a given job has been superseded by a newer one
464 * @throws MWException
467 final protected function isRootJobOldDuplicate( Job
$job ) {
468 if ( $job->getType() !== $this->type
) {
469 throw new MWException( "Got '{$job->getType()}' job; expected '{$this->type}'." );
471 $isDuplicate = $this->doIsRootJobOldDuplicate( $job );
477 * @see JobQueue::isRootJobOldDuplicate()
481 protected function doIsRootJobOldDuplicate( Job
$job ) {
482 if ( !$job->hasRootJobParams() ) {
483 return false; // job has no de-deplication info
485 $params = $job->getRootJobParams();
487 $key = $this->getRootJobCacheKey( $params['rootJobSignature'] );
488 // Get the last time this root job was enqueued
489 $timestamp = $this->dupCache
->get( $key );
491 // Check if a new root job was started at the location after this one's...
492 return ( $timestamp && $timestamp > $params['rootJobTimestamp'] );
496 * @param string $signature Hash identifier of the root job
499 protected function getRootJobCacheKey( $signature ) {
500 list( $db, $prefix ) = wfSplitWikiID( $this->wiki
);
502 return wfForeignMemcKey( $db, $prefix, 'jobqueue', $this->type
, 'rootjob', $signature );
506 * Deleted all unclaimed and delayed jobs from the queue
508 * @throws JobQueueError
512 final public function delete() {
517 * @see JobQueue::delete()
518 * @throws MWException
520 protected function doDelete() {
521 throw new MWException( "This method is not implemented." );
525 * Wait for any slaves or backup servers to catch up.
527 * This does nothing for certain queue classes.
530 * @throws JobQueueError
532 final public function waitForBackups() {
533 $this->doWaitForBackups();
537 * @see JobQueue::waitForBackups()
540 protected function doWaitForBackups() {
544 * Return a map of task names to task definition maps.
545 * A "task" is a fast periodic queue maintenance action.
546 * Mutually exclusive tasks must implement their own locking in the callback.
548 * Each task value is an associative array with:
549 * - name : the name of the task
550 * - callback : a PHP callable that performs the task
551 * - period : the period in seconds corresponding to the task frequency
555 final public function getPeriodicTasks() {
556 $tasks = $this->doGetPeriodicTasks();
557 foreach ( $tasks as $name => &$def ) {
558 $def['name'] = $name;
565 * @see JobQueue::getPeriodicTasks()
568 protected function doGetPeriodicTasks() {
573 * Clear any process and persistent caches
577 final public function flushCaches() {
578 $this->doFlushCaches();
582 * @see JobQueue::flushCaches()
585 protected function doFlushCaches() {
589 * Get an iterator to traverse over all available jobs in this queue.
590 * This does not include jobs that are currently acquired or delayed.
591 * Note: results may be stale if the queue is concurrently modified.
594 * @throws JobQueueError
596 abstract public function getAllQueuedJobs();
599 * Get an iterator to traverse over all delayed jobs in this queue.
600 * Note: results may be stale if the queue is concurrently modified.
603 * @throws JobQueueError
606 public function getAllDelayedJobs() {
607 return new ArrayIterator( array() ); // not implemented
611 * Do not use this function outside of JobQueue/JobQueueGroup
616 public function getCoalesceLocationInternal() {
621 * Check whether each of the given queues are empty.
622 * This is used for batching checks for queues stored at the same place.
624 * @param array $types List of queues types
625 * @return array|null (list of non-empty queue types) or null if unsupported
626 * @throws MWException
629 final public function getSiblingQueuesWithJobs( array $types ) {
631 return $this->doGetSiblingQueuesWithJobs( $types );
635 * @see JobQueue::getSiblingQueuesWithJobs()
636 * @param array $types List of queues types
637 * @return array|null (list of queue types) or null if unsupported
639 protected function doGetSiblingQueuesWithJobs( array $types ) {
640 return null; // not supported
644 * Check the size of each of the given queues.
645 * For queues not served by the same store as this one, 0 is returned.
646 * This is used for batching checks for queues stored at the same place.
648 * @param array $types List of queues types
649 * @return array|null (job type => whether queue is empty) or null if unsupported
650 * @throws MWException
653 final public function getSiblingQueueSizes( array $types ) {
655 return $this->doGetSiblingQueueSizes( $types );
659 * @see JobQueue::getSiblingQueuesSize()
660 * @param array $types List of queues types
661 * @return array|null (list of queue types) or null if unsupported
663 protected function doGetSiblingQueueSizes( array $types ) {
664 return null; // not supported
668 * Call wfIncrStats() for the queue overall and for the queue type
670 * @param string $key Event type
671 * @param string $type Job type
673 * @param string $wiki Wiki ID (added in 1.23)
676 public static function incrStats( $key, $type, $delta = 1, $wiki = null ) {
677 wfIncrStats( $key, $delta );
678 wfIncrStats( "{$key}-{$type}", $delta );
679 if ( $wiki !== null ) {
680 wfIncrStats( "{$key}-{$type}-{$wiki}", $delta );
685 * Namespace the queue with a key to isolate it for testing
689 * @throws MWException
691 public function setTestingPrefix( $key ) {
692 throw new MWException( "Queue namespacing not supported for this queue type." );
700 class JobQueueError
extends MWException
{
703 class JobQueueConnectionError
extends JobQueueError
{