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 protected $wiki; // string; wiki ID
33 protected $type; // string; job type
34 protected $order; // string; job priority for pop()
35 protected $claimTTL; // integer; seconds
36 protected $maxTries; // integer; maximum number of times to try a job
37 protected $checkDelay; // boolean; allow delayed jobs
42 const QOS_ATOMIC
= 1; // integer; "all-or-nothing" job insertions
43 const QoS_Atomic
= 1; // integer; "all-or-nothing" job insertions (b/c)
45 const ROOTJOB_TTL
= 2419200; // integer; seconds to remember root jobs (28 days)
48 * @param $params array
50 protected function __construct( array $params ) {
51 $this->wiki
= $params['wiki'];
52 $this->type
= $params['type'];
53 $this->claimTTL
= isset( $params['claimTTL'] ) ?
$params['claimTTL'] : 0;
54 $this->maxTries
= isset( $params['maxTries'] ) ?
$params['maxTries'] : 3;
55 if ( isset( $params['order'] ) && $params['order'] !== 'any' ) {
56 $this->order
= $params['order'];
58 $this->order
= $this->optimalOrder();
60 if ( !in_array( $this->order
, $this->supportedOrders() ) ) {
61 throw new MWException( __CLASS__
. " does not support '{$this->order}' order." );
63 $this->checkDelay
= !empty( $params['checkDelay'] );
64 if ( $this->checkDelay
&& !$this->supportsDelayedJobs() ) {
65 throw new MWException( __CLASS__
. " does not support delayed jobs." );
67 $this->dupCache
= wfGetCache( CACHE_ANYTHING
);
71 * Get a job queue object of the specified type.
73 * - class : What job class to use (determines job type)
74 * - wiki : wiki ID of the wiki the jobs are for (defaults to current wiki)
75 * - type : The name of the job types this queue handles
76 * - order : Order that pop() selects jobs, one of "fifo", "timestamp" or "random".
77 * If "fifo" is used, the queue will effectively be FIFO. Note that job
78 * completion will not appear to be exactly FIFO if there are multiple
79 * job runners since jobs can take different times to finish once popped.
80 * If "timestamp" is used, the queue will at least be loosely ordered
81 * by timestamp, allowing for some jobs to be popped off out of order.
82 * If "random" is used, pop() will pick jobs in random order.
83 * Note that it may only be weakly random (e.g. a lottery of the oldest X).
84 * If "any" is choosen, the queue will use whatever order is the fastest.
85 * This might be useful for improving concurrency for job acquisition.
86 * - claimTTL : If supported, the queue will recycle jobs that have been popped
87 * but not acknowledged as completed after this many seconds. Recycling
88 * of jobs simple means re-inserting them into the queue. Jobs can be
89 * attempted up to three times before being discarded.
90 * - checkDelay : If supported, respect Job::getReleaseTimestamp() in the push functions.
91 * This lets delayed jobs wait in a staging area until a given timestamp is
92 * reached, at which point they will enter the queue. If this is not enabled
93 * or not supported, an exception will be thrown on delayed job insertion.
95 * Queue classes should throw an exception if they do not support the options given.
97 * @param $params array
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." );
114 * @return string Wiki ID
116 final public function getWiki() {
121 * @return string Job type that this queue handles
123 final public function getType() {
128 * @return string One of (random, timestamp, fifo, undefined)
130 final public function getOrder() {
135 * @return bool Whether delayed jobs are enabled
138 final public function delayedJobsEnabled() {
139 return $this->checkDelay
;
143 * Get the allowed queue orders for configuration validation
145 * @return Array Subset of (random, timestamp, fifo, undefined)
147 abstract protected function supportedOrders();
150 * Get the default queue order to use if configuration does not specify one
152 * @return string One of (random, timestamp, fifo, undefined)
154 abstract protected function optimalOrder();
157 * Find out if delayed jobs are supported for configuration validation
159 * @return boolean Whether delayed jobs are supported
161 protected function supportsDelayedJobs() {
162 return false; // not implemented
166 * Quickly check if the queue has no available (unacquired, non-delayed) jobs.
167 * Queue classes should use caching if they are any slower without memcached.
169 * If caching is used, this might return false when there are actually no jobs.
170 * If pop() is called and returns false then it should correct the cache. Also,
171 * calling flushCaches() first prevents this. However, this affect is typically
172 * not distinguishable from the race condition between isEmpty() and pop().
175 * @throws JobQueueError
177 final public function isEmpty() {
178 wfProfileIn( __METHOD__
);
179 $res = $this->doIsEmpty();
180 wfProfileOut( __METHOD__
);
185 * @see JobQueue::isEmpty()
188 abstract protected function doIsEmpty();
191 * Get the number of available (unacquired, non-delayed) jobs in the queue.
192 * Queue classes should use caching if they are any slower without memcached.
194 * If caching is used, this number might be out of date for a minute.
197 * @throws JobQueueError
199 final public function getSize() {
200 wfProfileIn( __METHOD__
);
201 $res = $this->doGetSize();
202 wfProfileOut( __METHOD__
);
207 * @see JobQueue::getSize()
210 abstract protected function doGetSize();
213 * Get the number of acquired jobs (these are temporarily out of the queue).
214 * Queue classes should use caching if they are any slower without memcached.
216 * If caching is used, this number might be out of date for a minute.
219 * @throws JobQueueError
221 final public function getAcquiredCount() {
222 wfProfileIn( __METHOD__
);
223 $res = $this->doGetAcquiredCount();
224 wfProfileOut( __METHOD__
);
229 * @see JobQueue::getAcquiredCount()
232 abstract protected function doGetAcquiredCount();
235 * Get the number of delayed jobs (these are temporarily out of the queue).
236 * Queue classes should use caching if they are any slower without memcached.
238 * If caching is used, this number might be out of date for a minute.
241 * @throws JobQueueError
244 final public function getDelayedCount() {
245 wfProfileIn( __METHOD__
);
246 $res = $this->doGetDelayedCount();
247 wfProfileOut( __METHOD__
);
252 * @see JobQueue::getDelayedCount()
255 protected function doGetDelayedCount() {
256 return 0; // not implemented
260 * Get the number of acquired jobs that can no longer be attempted.
261 * Queue classes should use caching if they are any slower without memcached.
263 * If caching is used, this number might be out of date for a minute.
266 * @throws JobQueueError
268 final public function getAbandonedCount() {
269 wfProfileIn( __METHOD__
);
270 $res = $this->doGetAbandonedCount();
271 wfProfileOut( __METHOD__
);
276 * @see JobQueue::getAbandonedCount()
279 protected function doGetAbandonedCount() {
280 return 0; // not implemented
284 * Push a single jobs into the queue.
285 * This does not require $wgJobClasses to be set for the given job type.
286 * Outside callers should use JobQueueGroup::push() instead of this function.
288 * @param $jobs Job|Array
289 * @param $flags integer Bitfield (supports JobQueue::QOS_ATOMIC)
290 * @return bool Returns false on failure
291 * @throws JobQueueError
293 final public function push( $jobs, $flags = 0 ) {
294 return $this->batchPush( is_array( $jobs ) ?
$jobs : array( $jobs ), $flags );
298 * Push a batch of jobs into the queue.
299 * This does not require $wgJobClasses to be set for the given job type.
300 * Outside callers should use JobQueueGroup::push() instead of this function.
302 * @param array $jobs List of Jobs
303 * @param $flags integer Bitfield (supports JobQueue::QOS_ATOMIC)
304 * @return bool Returns false on failure
305 * @throws JobQueueError
307 final public function batchPush( array $jobs, $flags = 0 ) {
308 if ( !count( $jobs ) ) {
309 return true; // nothing to do
312 foreach ( $jobs as $job ) {
313 if ( $job->getType() !== $this->type
) {
314 throw new MWException(
315 "Got '{$job->getType()}' job; expected a '{$this->type}' job." );
316 } elseif ( $job->getReleaseTimestamp() && !$this->checkDelay
) {
317 throw new MWException(
318 "Got delayed '{$job->getType()}' job; delays are not supported." );
322 wfProfileIn( __METHOD__
);
323 $ok = $this->doBatchPush( $jobs, $flags );
324 wfProfileOut( __METHOD__
);
329 * @see JobQueue::batchPush()
332 abstract protected function doBatchPush( array $jobs, $flags );
335 * Pop a job off of the queue.
336 * This requires $wgJobClasses to be set for the given job type.
337 * Outside callers should use JobQueueGroup::pop() instead of this function.
339 * @return Job|bool Returns false if there are no jobs
340 * @throws JobQueueError
342 final public function pop() {
343 global $wgJobClasses;
345 if ( $this->wiki
!== wfWikiID() ) {
346 throw new MWException( "Cannot pop '{$this->type}' job off foreign wiki queue." );
347 } elseif ( !isset( $wgJobClasses[$this->type
] ) ) {
348 // Do not pop jobs if there is no class for the queue type
349 throw new MWException( "Unrecognized job type '{$this->type}'." );
352 wfProfileIn( __METHOD__
);
353 $job = $this->doPop();
354 wfProfileOut( __METHOD__
);
356 // Flag this job as an old duplicate based on its "root" job...
358 if ( $job && $this->isRootJobOldDuplicate( $job ) ) {
359 JobQueue
::incrStats( 'job-pop-duplicate', $this->type
);
360 $job = DuplicateJob
::newFromJob( $job ); // convert to a no-op
362 } catch ( MWException
$e ) {} // don't lose jobs over this
368 * @see JobQueue::pop()
371 abstract protected function doPop();
374 * Acknowledge that a job was completed.
376 * This does nothing for certain queue classes or if "claimTTL" is not set.
377 * Outside callers should use JobQueueGroup::ack() instead of this function.
381 * @throws JobQueueError
383 final public function ack( Job
$job ) {
384 if ( $job->getType() !== $this->type
) {
385 throw new MWException( "Got '{$job->getType()}' job; expected '{$this->type}'." );
387 wfProfileIn( __METHOD__
);
388 $ok = $this->doAck( $job );
389 wfProfileOut( __METHOD__
);
394 * @see JobQueue::ack()
397 abstract protected function doAck( Job
$job );
400 * Register the "root job" of a given job into the queue for de-duplication.
401 * This should only be called right *after* all the new jobs have been inserted.
402 * This is used to turn older, duplicate, job entries into no-ops. The root job
403 * information will remain in the registry until it simply falls out of cache.
405 * This requires that $job has two special fields in the "params" array:
406 * - rootJobSignature : hash (e.g. SHA1) that identifies the task
407 * - rootJobTimestamp : TS_MW timestamp of this instance of the task
409 * A "root job" is a conceptual job that consist of potentially many smaller jobs
410 * that are actually inserted into the queue. For example, "refreshLinks" jobs are
411 * spawned when a template is edited. One can think of the task as "update links
412 * of pages that use template X" and an instance of that task as a "root job".
413 * However, what actually goes into the queue are potentially many refreshLinks2 jobs.
414 * Since these jobs include things like page ID ranges and DB master positions, and morph
415 * into smaller refreshLinks2 jobs recursively, simple duplicate detection (like job_sha1)
416 * for individual jobs being identical is not useful.
418 * In the case of "refreshLinks", if these jobs are still in the queue when the template
419 * is edited again, we want all of these old refreshLinks jobs for that template to become
420 * no-ops. This can greatly reduce server load, since refreshLinks jobs involves parsing.
421 * Essentially, the new batch of jobs belong to a new "root job" and the older ones to a
422 * previous "root job" for the same task of "update links of pages that use template X".
424 * This does nothing for certain queue classes.
428 * @throws JobQueueError
430 final public function deduplicateRootJob( Job
$job ) {
431 if ( $job->getType() !== $this->type
) {
432 throw new MWException( "Got '{$job->getType()}' job; expected '{$this->type}'." );
434 wfProfileIn( __METHOD__
);
435 $ok = $this->doDeduplicateRootJob( $job );
436 wfProfileOut( __METHOD__
);
441 * @see JobQueue::deduplicateRootJob()
445 protected function doDeduplicateRootJob( Job
$job ) {
446 if ( !$job->hasRootJobParams() ) {
447 throw new MWException( "Cannot register root job; missing parameters." );
449 $params = $job->getRootJobParams();
451 $key = $this->getRootJobCacheKey( $params['rootJobSignature'] );
452 // Callers should call batchInsert() and then this function so that if the insert
453 // fails, the de-duplication registration will be aborted. Since the insert is
454 // deferred till "transaction idle", do the same here, so that the ordering is
455 // maintained. Having only the de-duplication registration succeed would cause
456 // jobs to become no-ops without any actual jobs that made them redundant.
457 $timestamp = $this->dupCache
->get( $key ); // current last timestamp of this job
458 if ( $timestamp && $timestamp >= $params['rootJobTimestamp'] ) {
459 return true; // a newer version of this root job was enqueued
462 // Update the timestamp of the last root job started at the location...
463 return $this->dupCache
->set( $key, $params['rootJobTimestamp'], JobQueueDB
::ROOTJOB_TTL
);
467 * Check if the "root" job of a given job has been superseded by a newer one
471 * @throws JobQueueError
473 final protected function isRootJobOldDuplicate( Job
$job ) {
474 if ( $job->getType() !== $this->type
) {
475 throw new MWException( "Got '{$job->getType()}' job; expected '{$this->type}'." );
477 wfProfileIn( __METHOD__
);
478 $isDuplicate = $this->doIsRootJobOldDuplicate( $job );
479 wfProfileOut( __METHOD__
);
484 * @see JobQueue::isRootJobOldDuplicate()
488 protected function doIsRootJobOldDuplicate( Job
$job ) {
489 if ( !$job->hasRootJobParams() ) {
490 return false; // job has no de-deplication info
492 $params = $job->getRootJobParams();
494 $key = $this->getRootJobCacheKey( $params['rootJobSignature'] );
495 // Get the last time this root job was enqueued
496 $timestamp = $this->dupCache
->get( $key );
498 // Check if a new root job was started at the location after this one's...
499 return ( $timestamp && $timestamp > $params['rootJobTimestamp'] );
503 * @param string $signature Hash identifier of the root job
506 protected function getRootJobCacheKey( $signature ) {
507 list( $db, $prefix ) = wfSplitWikiID( $this->wiki
);
508 return wfForeignMemcKey( $db, $prefix, 'jobqueue', $this->type
, 'rootjob', $signature );
512 * Deleted all unclaimed and delayed jobs from the queue
514 * @return bool Success
515 * @throws JobQueueError
518 final public function delete() {
519 wfProfileIn( __METHOD__
);
520 $res = $this->doDelete();
521 wfProfileOut( __METHOD__
);
526 * @see JobQueue::delete()
527 * @return bool Success
529 protected function doDelete() {
530 throw new MWException( "This method is not implemented." );
534 * Wait for any slaves or backup servers to catch up.
536 * This does nothing for certain queue classes.
539 * @throws JobQueueError
541 final public function waitForBackups() {
542 wfProfileIn( __METHOD__
);
543 $this->doWaitForBackups();
544 wfProfileOut( __METHOD__
);
548 * @see JobQueue::waitForBackups()
551 protected function doWaitForBackups() {}
554 * Return a map of task names to task definition maps.
555 * A "task" is a fast periodic queue maintenance action.
556 * Mutually exclusive tasks must implement their own locking in the callback.
558 * Each task value is an associative array with:
559 * - name : the name of the task
560 * - callback : a PHP callable that performs the task
561 * - period : the period in seconds corresponding to the task frequency
565 final public function getPeriodicTasks() {
566 $tasks = $this->doGetPeriodicTasks();
567 foreach ( $tasks as $name => &$def ) {
568 $def['name'] = $name;
574 * @see JobQueue::getPeriodicTasks()
577 protected function doGetPeriodicTasks() {
582 * Clear any process and persistent caches
586 final public function flushCaches() {
587 wfProfileIn( __METHOD__
);
588 $this->doFlushCaches();
589 wfProfileOut( __METHOD__
);
593 * @see JobQueue::flushCaches()
596 protected function doFlushCaches() {}
599 * Get an iterator to traverse over all available jobs in this queue.
600 * This does not include jobs that are currently acquired or delayed.
601 * Note: results may be stale if the queue is concurrently modified.
604 * @throws JobQueueError
606 abstract public function getAllQueuedJobs();
609 * Get an iterator to traverse over all delayed jobs in this queue.
610 * Note: results may be stale if the queue is concurrently modified.
613 * @throws JobQueueError
616 public function getAllDelayedJobs() {
617 return new ArrayIterator( array() ); // not implemented
621 * Do not use this function outside of JobQueue/JobQueueGroup
626 public function getCoalesceLocationInternal() {
631 * Check whether each of the given queues are empty.
632 * This is used for batching checks for queues stored at the same place.
634 * @param array $types List of queues types
635 * @return array|null (list of non-empty queue types) or null if unsupported
636 * @throws MWException
639 final public function getSiblingQueuesWithJobs( array $types ) {
640 $section = new ProfileSection( __METHOD__
);
641 return $this->doGetSiblingQueuesWithJobs( $types );
645 * @see JobQueue::getSiblingQueuesWithJobs()
646 * @param array $types List of queues types
647 * @return array|null (list of queue types) or null if unsupported
649 protected function doGetSiblingQueuesWithJobs( array $types ) {
650 return null; // not supported
654 * Check the size of each of the given queues.
655 * For queues not served by the same store as this one, 0 is returned.
656 * This is used for batching checks for queues stored at the same place.
658 * @param array $types List of queues types
659 * @return array|null (job type => whether queue is empty) or null if unsupported
660 * @throws MWException
663 final public function getSiblingQueueSizes( array $types ) {
664 $section = new ProfileSection( __METHOD__
);
665 return $this->doGetSiblingQueueSizes( $types );
669 * @see JobQueue::getSiblingQueuesSize()
670 * @param array $types List of queues types
671 * @return array|null (list of queue types) or null if unsupported
673 protected function doGetSiblingQueueSizes( array $types ) {
674 return null; // not supported
678 * Call wfIncrStats() for the queue overall and for the queue type
680 * @param string $key Event type
681 * @param string $type Job type
682 * @param integer $delta
685 public static function incrStats( $key, $type, $delta = 1 ) {
686 wfIncrStats( $key, $delta );
687 wfIncrStats( "{$key}-{$type}", $delta );
691 * Namespace the queue with a key to isolate it for testing
695 * @throws MWException
697 public function setTestingPrefix( $key ) {
698 throw new MWException( "Queue namespacing not supported for this queue type." );
706 class JobQueueError
extends MWException
{}
707 class JobQueueConnectionError
extends JobQueueError
{}