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
44 const ROOTJOB_TTL
= 2419200; // integer; seconds to remember root jobs (28 days)
47 * @param $params array
49 protected function __construct( array $params ) {
50 $this->wiki
= $params['wiki'];
51 $this->type
= $params['type'];
52 $this->claimTTL
= isset( $params['claimTTL'] ) ?
$params['claimTTL'] : 0;
53 $this->maxTries
= isset( $params['maxTries'] ) ?
$params['maxTries'] : 3;
54 if ( isset( $params['order'] ) && $params['order'] !== 'any' ) {
55 $this->order
= $params['order'];
57 $this->order
= $this->optimalOrder();
59 if ( !in_array( $this->order
, $this->supportedOrders() ) ) {
60 throw new MWException( __CLASS__
. " does not support '{$this->order}' order." );
62 $this->checkDelay
= !empty( $params['checkDelay'] );
63 if ( $this->checkDelay
&& !$this->supportsDelayedJobs() ) {
64 throw new MWException( __CLASS__
. " does not support delayed jobs." );
66 $this->dupCache
= wfGetCache( CACHE_ANYTHING
);
70 * Get a job queue object of the specified type.
72 * - class : What job class to use (determines job type)
73 * - wiki : wiki ID of the wiki the jobs are for (defaults to current wiki)
74 * - type : The name of the job types this queue handles
75 * - order : Order that pop() selects jobs, one of "fifo", "timestamp" or "random".
76 * If "fifo" is used, the queue will effectively be FIFO. Note that job
77 * completion will not appear to be exactly FIFO if there are multiple
78 * job runners since jobs can take different times to finish once popped.
79 * If "timestamp" is used, the queue will at least be loosely ordered
80 * by timestamp, allowing for some jobs to be popped off out of order.
81 * If "random" is used, pop() will pick jobs in random order.
82 * Note that it may only be weakly random (e.g. a lottery of the oldest X).
83 * If "any" is choosen, the queue will use whatever order is the fastest.
84 * This might be useful for improving concurrency for job acquisition.
85 * - claimTTL : If supported, the queue will recycle jobs that have been popped
86 * but not acknowledged as completed after this many seconds. Recycling
87 * of jobs simple means re-inserting them into the queue. Jobs can be
88 * attempted up to three times before being discarded.
89 * - checkDelay : If supported, respect Job::getReleaseTimestamp() in the push functions.
90 * This lets delayed jobs wait in a staging area until a given timestamp is
91 * reached, at which point they will enter the queue. If this is not enabled
92 * or not supported, an exception will be thrown on delayed job insertion.
94 * Queue classes should throw an exception if they do not support the options given.
96 * @param $params array
100 final public static function factory( array $params ) {
101 $class = $params['class'];
102 if ( !class_exists( $class ) ) {
103 throw new MWException( "Invalid job queue class '$class'." );
105 $obj = new $class( $params );
106 if ( !( $obj instanceof self
) ) {
107 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__
);
186 * @see JobQueue::isEmpty()
189 abstract protected function doIsEmpty();
192 * Get the number of available (unacquired, non-delayed) jobs in the queue.
193 * Queue classes should use caching if they are any slower without memcached.
195 * If caching is used, this number might be out of date for a minute.
198 * @throws JobQueueError
200 final public function getSize() {
201 wfProfileIn( __METHOD__
);
202 $res = $this->doGetSize();
203 wfProfileOut( __METHOD__
);
209 * @see JobQueue::getSize()
212 abstract protected function doGetSize();
215 * Get the number of acquired jobs (these are temporarily out of the queue).
216 * Queue classes should use caching if they are any slower without memcached.
218 * If caching is used, this number might be out of date for a minute.
221 * @throws JobQueueError
223 final public function getAcquiredCount() {
224 wfProfileIn( __METHOD__
);
225 $res = $this->doGetAcquiredCount();
226 wfProfileOut( __METHOD__
);
232 * @see JobQueue::getAcquiredCount()
235 abstract protected function doGetAcquiredCount();
238 * Get the number of delayed jobs (these are temporarily out of the queue).
239 * Queue classes should use caching if they are any slower without memcached.
241 * If caching is used, this number might be out of date for a minute.
244 * @throws JobQueueError
247 final public function getDelayedCount() {
248 wfProfileIn( __METHOD__
);
249 $res = $this->doGetDelayedCount();
250 wfProfileOut( __METHOD__
);
256 * @see JobQueue::getDelayedCount()
259 protected function doGetDelayedCount() {
260 return 0; // not implemented
264 * Get the number of acquired jobs that can no longer be attempted.
265 * Queue classes should use caching if they are any slower without memcached.
267 * If caching is used, this number might be out of date for a minute.
270 * @throws JobQueueError
272 final public function getAbandonedCount() {
273 wfProfileIn( __METHOD__
);
274 $res = $this->doGetAbandonedCount();
275 wfProfileOut( __METHOD__
);
281 * @see JobQueue::getAbandonedCount()
284 protected function doGetAbandonedCount() {
285 return 0; // not implemented
289 * Push a single jobs into the queue.
290 * This does not require $wgJobClasses to be set for the given job type.
291 * Outside callers should use JobQueueGroup::push() instead of this function.
293 * @param $jobs Job|Array
294 * @param $flags integer Bitfield (supports JobQueue::QOS_ATOMIC)
295 * @return bool Returns false on failure
296 * @throws JobQueueError
298 final public function push( $jobs, $flags = 0 ) {
299 return $this->batchPush( is_array( $jobs ) ?
$jobs : array( $jobs ), $flags );
303 * Push a batch of jobs into the queue.
304 * This does not require $wgJobClasses to be set for the given job type.
305 * Outside callers should use JobQueueGroup::push() instead of this function.
307 * @param array $jobs List of Jobs
308 * @param $flags integer Bitfield (supports JobQueue::QOS_ATOMIC)
309 * @return bool Returns false on failure
310 * @throws JobQueueError
312 final public function batchPush( array $jobs, $flags = 0 ) {
313 if ( !count( $jobs ) ) {
314 return true; // nothing to do
317 foreach ( $jobs as $job ) {
318 if ( $job->getType() !== $this->type
) {
319 throw new MWException(
320 "Got '{$job->getType()}' job; expected a '{$this->type}' job." );
321 } elseif ( $job->getReleaseTimestamp() && !$this->checkDelay
) {
322 throw new MWException(
323 "Got delayed '{$job->getType()}' job; delays are not supported." );
327 wfProfileIn( __METHOD__
);
328 $ok = $this->doBatchPush( $jobs, $flags );
329 wfProfileOut( __METHOD__
);
335 * @see JobQueue::batchPush()
338 abstract protected function doBatchPush( array $jobs, $flags );
341 * Pop a job off of the queue.
342 * This requires $wgJobClasses to be set for the given job type.
343 * Outside callers should use JobQueueGroup::pop() instead of this function.
345 * @return Job|bool Returns false if there are no jobs
346 * @throws JobQueueError
348 final public function pop() {
349 global $wgJobClasses;
351 if ( $this->wiki
!== wfWikiID() ) {
352 throw new MWException( "Cannot pop '{$this->type}' job off foreign wiki queue." );
353 } elseif ( !isset( $wgJobClasses[$this->type
] ) ) {
354 // Do not pop jobs if there is no class for the queue type
355 throw new MWException( "Unrecognized job type '{$this->type}'." );
358 wfProfileIn( __METHOD__
);
359 $job = $this->doPop();
360 wfProfileOut( __METHOD__
);
362 // Flag this job as an old duplicate based on its "root" job...
364 if ( $job && $this->isRootJobOldDuplicate( $job ) ) {
365 JobQueue
::incrStats( 'job-pop-duplicate', $this->type
);
366 $job = DuplicateJob
::newFromJob( $job ); // convert to a no-op
368 } catch ( MWException
$e ) {
369 // don't lose jobs over this
376 * @see JobQueue::pop()
379 abstract protected function doPop();
382 * Acknowledge that a job was completed.
384 * This does nothing for certain queue classes or if "claimTTL" is not set.
385 * Outside callers should use JobQueueGroup::ack() instead of this function.
389 * @throws JobQueueError
391 final public function ack( Job
$job ) {
392 if ( $job->getType() !== $this->type
) {
393 throw new MWException( "Got '{$job->getType()}' job; expected '{$this->type}'." );
395 wfProfileIn( __METHOD__
);
396 $ok = $this->doAck( $job );
397 wfProfileOut( __METHOD__
);
403 * @see JobQueue::ack()
406 abstract protected function doAck( Job
$job );
409 * Register the "root job" of a given job into the queue for de-duplication.
410 * This should only be called right *after* all the new jobs have been inserted.
411 * This is used to turn older, duplicate, job entries into no-ops. The root job
412 * information will remain in the registry until it simply falls out of cache.
414 * This requires that $job has two special fields in the "params" array:
415 * - rootJobSignature : hash (e.g. SHA1) that identifies the task
416 * - rootJobTimestamp : TS_MW timestamp of this instance of the task
418 * A "root job" is a conceptual job that consist of potentially many smaller jobs
419 * that are actually inserted into the queue. For example, "refreshLinks" jobs are
420 * spawned when a template is edited. One can think of the task as "update links
421 * of pages that use template X" and an instance of that task as a "root job".
422 * However, what actually goes into the queue are potentially many refreshLinks2 jobs.
423 * Since these jobs include things like page ID ranges and DB master positions, and morph
424 * into smaller refreshLinks2 jobs recursively, simple duplicate detection (like job_sha1)
425 * for individual jobs being identical is not useful.
427 * In the case of "refreshLinks", if these jobs are still in the queue when the template
428 * is edited again, we want all of these old refreshLinks jobs for that template to become
429 * no-ops. This can greatly reduce server load, since refreshLinks jobs involves parsing.
430 * Essentially, the new batch of jobs belong to a new "root job" and the older ones to a
431 * previous "root job" for the same task of "update links of pages that use template X".
433 * This does nothing for certain queue classes.
437 * @throws JobQueueError
439 final public function deduplicateRootJob( Job
$job ) {
440 if ( $job->getType() !== $this->type
) {
441 throw new MWException( "Got '{$job->getType()}' job; expected '{$this->type}'." );
443 wfProfileIn( __METHOD__
);
444 $ok = $this->doDeduplicateRootJob( $job );
445 wfProfileOut( __METHOD__
);
451 * @see JobQueue::deduplicateRootJob()
455 protected function doDeduplicateRootJob( Job
$job ) {
456 if ( !$job->hasRootJobParams() ) {
457 throw new MWException( "Cannot register root job; missing parameters." );
459 $params = $job->getRootJobParams();
461 $key = $this->getRootJobCacheKey( $params['rootJobSignature'] );
462 // Callers should call batchInsert() and then this function so that if the insert
463 // fails, the de-duplication registration will be aborted. Since the insert is
464 // deferred till "transaction idle", do the same here, so that the ordering is
465 // maintained. Having only the de-duplication registration succeed would cause
466 // jobs to become no-ops without any actual jobs that made them redundant.
467 $timestamp = $this->dupCache
->get( $key ); // current last timestamp of this job
468 if ( $timestamp && $timestamp >= $params['rootJobTimestamp'] ) {
469 return true; // a newer version of this root job was enqueued
472 // Update the timestamp of the last root job started at the location...
473 return $this->dupCache
->set( $key, $params['rootJobTimestamp'], JobQueueDB
::ROOTJOB_TTL
);
477 * Check if the "root" job of a given job has been superseded by a newer one
481 * @throws JobQueueError
483 final protected function isRootJobOldDuplicate( Job
$job ) {
484 if ( $job->getType() !== $this->type
) {
485 throw new MWException( "Got '{$job->getType()}' job; expected '{$this->type}'." );
487 wfProfileIn( __METHOD__
);
488 $isDuplicate = $this->doIsRootJobOldDuplicate( $job );
489 wfProfileOut( __METHOD__
);
495 * @see JobQueue::isRootJobOldDuplicate()
499 protected function doIsRootJobOldDuplicate( Job
$job ) {
500 if ( !$job->hasRootJobParams() ) {
501 return false; // job has no de-deplication info
503 $params = $job->getRootJobParams();
505 $key = $this->getRootJobCacheKey( $params['rootJobSignature'] );
506 // Get the last time this root job was enqueued
507 $timestamp = $this->dupCache
->get( $key );
509 // Check if a new root job was started at the location after this one's...
510 return ( $timestamp && $timestamp > $params['rootJobTimestamp'] );
514 * @param string $signature Hash identifier of the root job
517 protected function getRootJobCacheKey( $signature ) {
518 list( $db, $prefix ) = wfSplitWikiID( $this->wiki
);
520 return wfForeignMemcKey( $db, $prefix, 'jobqueue', $this->type
, 'rootjob', $signature );
524 * Deleted all unclaimed and delayed jobs from the queue
526 * @return bool Success
527 * @throws JobQueueError
530 final public function delete() {
531 wfProfileIn( __METHOD__
);
532 $res = $this->doDelete();
533 wfProfileOut( __METHOD__
);
539 * @see JobQueue::delete()
540 * @return bool Success
542 protected function doDelete() {
543 throw new MWException( "This method is not implemented." );
547 * Wait for any slaves or backup servers to catch up.
549 * This does nothing for certain queue classes.
552 * @throws JobQueueError
554 final public function waitForBackups() {
555 wfProfileIn( __METHOD__
);
556 $this->doWaitForBackups();
557 wfProfileOut( __METHOD__
);
561 * @see JobQueue::waitForBackups()
564 protected function doWaitForBackups() {
568 * Return a map of task names to task definition maps.
569 * A "task" is a fast periodic queue maintenance action.
570 * Mutually exclusive tasks must implement their own locking in the callback.
572 * Each task value is an associative array with:
573 * - name : the name of the task
574 * - callback : a PHP callable that performs the task
575 * - period : the period in seconds corresponding to the task frequency
579 final public function getPeriodicTasks() {
580 $tasks = $this->doGetPeriodicTasks();
581 foreach ( $tasks as $name => &$def ) {
582 $def['name'] = $name;
589 * @see JobQueue::getPeriodicTasks()
592 protected function doGetPeriodicTasks() {
597 * Clear any process and persistent caches
601 final public function flushCaches() {
602 wfProfileIn( __METHOD__
);
603 $this->doFlushCaches();
604 wfProfileOut( __METHOD__
);
608 * @see JobQueue::flushCaches()
611 protected function doFlushCaches() {
615 * Get an iterator to traverse over all available jobs in this queue.
616 * This does not include jobs that are currently acquired or delayed.
617 * Note: results may be stale if the queue is concurrently modified.
620 * @throws JobQueueError
622 abstract public function getAllQueuedJobs();
625 * Get an iterator to traverse over all delayed jobs in this queue.
626 * Note: results may be stale if the queue is concurrently modified.
629 * @throws JobQueueError
632 public function getAllDelayedJobs() {
633 return new ArrayIterator( array() ); // not implemented
637 * Do not use this function outside of JobQueue/JobQueueGroup
642 public function getCoalesceLocationInternal() {
647 * Check whether each of the given queues are empty.
648 * This is used for batching checks for queues stored at the same place.
650 * @param array $types List of queues types
651 * @return array|null (list of non-empty queue types) or null if unsupported
652 * @throws MWException
655 final public function getSiblingQueuesWithJobs( array $types ) {
656 $section = new ProfileSection( __METHOD__
);
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 $section = new ProfileSection( __METHOD__
);
683 return $this->doGetSiblingQueueSizes( $types );
687 * @see JobQueue::getSiblingQueuesSize()
688 * @param array $types List of queues types
689 * @return array|null (list of queue types) or null if unsupported
691 protected function doGetSiblingQueueSizes( array $types ) {
692 return null; // not supported
696 * Call wfIncrStats() for the queue overall and for the queue type
698 * @param string $key Event type
699 * @param string $type Job type
700 * @param integer $delta
703 public static function incrStats( $key, $type, $delta = 1 ) {
704 wfIncrStats( $key, $delta );
705 wfIncrStats( "{$key}-{$type}", $delta );
709 * Namespace the queue with a key to isolate it for testing
713 * @throws MWException
715 public function setTestingPrefix( $key ) {
716 throw new MWException( "Queue namespacing not supported for this queue type." );
724 class JobQueueError
extends MWException
{
727 class JobQueueConnectionError
extends JobQueueError
{