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
39 const QOS_ATOMIC
= 1; // integer; "all-or-nothing" job insertions
40 const QoS_Atomic
= 1; // integer; "all-or-nothing" job insertions (b/c)
42 const ROOTJOB_TTL
= 2419200; // integer; seconds to remember root jobs (28 days)
45 * @param $params array
47 protected function __construct( array $params ) {
48 $this->wiki
= $params['wiki'];
49 $this->type
= $params['type'];
50 $this->claimTTL
= isset( $params['claimTTL'] ) ?
$params['claimTTL'] : 0;
51 $this->maxTries
= isset( $params['maxTries'] ) ?
$params['maxTries'] : 3;
52 if ( isset( $params['order'] ) && $params['order'] !== 'any' ) {
53 $this->order
= $params['order'];
55 $this->order
= $this->optimalOrder();
57 if ( !in_array( $this->order
, $this->supportedOrders() ) ) {
58 throw new MWException( __CLASS__
. " does not support '{$this->order}' order." );
60 $this->checkDelay
= !empty( $params['checkDelay'] );
61 if ( $this->checkDelay
&& !$this->supportsDelayedJobs() ) {
62 throw new MWException( __CLASS__
. " does not support delayed jobs." );
67 * Get a job queue object of the specified type.
69 * - class : What job class to use (determines job type)
70 * - wiki : wiki ID of the wiki the jobs are for (defaults to current wiki)
71 * - type : The name of the job types this queue handles
72 * - order : Order that pop() selects jobs, one of "fifo", "timestamp" or "random".
73 * If "fifo" is used, the queue will effectively be FIFO. Note that job
74 * completion will not appear to be exactly FIFO if there are multiple
75 * job runners since jobs can take different times to finish once popped.
76 * If "timestamp" is used, the queue will at least be loosely ordered
77 * by timestamp, allowing for some jobs to be popped off out of order.
78 * If "random" is used, pop() will pick jobs in random order.
79 * Note that it may only be weakly random (e.g. a lottery of the oldest X).
80 * If "any" is choosen, the queue will use whatever order is the fastest.
81 * This might be useful for improving concurrency for job acquisition.
82 * - claimTTL : If supported, the queue will recycle jobs that have been popped
83 * but not acknowledged as completed after this many seconds. Recycling
84 * of jobs simple means re-inserting them into the queue. Jobs can be
85 * attempted up to three times before being discarded.
86 * - checkDelay : If supported, respect Job::getReleaseTimestamp() in the push functions.
87 * This lets delayed jobs wait in a staging area until a given timestamp is
88 * reached, at which point they will enter the queue. If this is not enabled
89 * or not supported, an exception will be thrown on delayed job insertion.
91 * Queue classes should throw an exception if they do not support the options given.
93 * @param $params array
97 final public static function factory( array $params ) {
98 $class = $params['class'];
99 if ( !MWInit
::classExists( $class ) ) {
100 throw new MWException( "Invalid job queue class '$class'." );
102 $obj = new $class( $params );
103 if ( !( $obj instanceof self
) ) {
104 throw new MWException( "Class '$class' is not a " . __CLASS__
. " class." );
110 * @return string Wiki ID
112 final public function getWiki() {
117 * @return string Job type that this queue handles
119 final public function getType() {
124 * @return string One of (random, timestamp, fifo)
126 final public function getOrder() {
131 * @return Array Subset of (random, timestamp, fifo)
133 abstract protected function supportedOrders();
136 * @return string One of (random, timestamp, fifo)
138 abstract protected function optimalOrder();
141 * @return boolean Whether delayed jobs are supported
143 protected function supportsDelayedJobs() {
144 return false; // not implemented
148 * Quickly check if the queue has no available (unacquired, non-delayed) jobs.
149 * Queue classes should use caching if they are any slower without memcached.
151 * If caching is used, this might return false when there are actually no jobs.
152 * If pop() is called and returns false then it should correct the cache. Also,
153 * calling flushCaches() first prevents this. However, this affect is typically
154 * not distinguishable from the race condition between isEmpty() and pop().
157 * @throws MWException
159 final public function isEmpty() {
160 wfProfileIn( __METHOD__
);
161 $res = $this->doIsEmpty();
162 wfProfileOut( __METHOD__
);
167 * @see JobQueue::isEmpty()
170 abstract protected function doIsEmpty();
173 * Get the number of available (unacquired, non-delayed) jobs in the queue.
174 * Queue classes should use caching if they are any slower without memcached.
176 * If caching is used, this number might be out of date for a minute.
179 * @throws MWException
181 final public function getSize() {
182 wfProfileIn( __METHOD__
);
183 $res = $this->doGetSize();
184 wfProfileOut( __METHOD__
);
189 * @see JobQueue::getSize()
192 abstract protected function doGetSize();
195 * Get the number of acquired jobs (these are temporarily out of the queue).
196 * Queue classes should use caching if they are any slower without memcached.
198 * If caching is used, this number might be out of date for a minute.
201 * @throws MWException
203 final public function getAcquiredCount() {
204 wfProfileIn( __METHOD__
);
205 $res = $this->doGetAcquiredCount();
206 wfProfileOut( __METHOD__
);
211 * @see JobQueue::getAcquiredCount()
214 abstract protected function doGetAcquiredCount();
217 * Get the number of delayed jobs (these are temporarily out of the queue).
218 * Queue classes should use caching if they are any slower without memcached.
220 * If caching is used, this number might be out of date for a minute.
223 * @throws MWException
226 final public function getDelayedCount() {
227 wfProfileIn( __METHOD__
);
228 $res = $this->doGetDelayedCount();
229 wfProfileOut( __METHOD__
);
234 * @see JobQueue::getDelayedCount()
237 protected function doGetDelayedCount() {
238 return 0; // not implemented
242 * Push a single jobs into the queue.
243 * This does not require $wgJobClasses to be set for the given job type.
244 * Outside callers should use JobQueueGroup::push() instead of this function.
246 * @param $jobs Job|Array
247 * @param $flags integer Bitfield (supports JobQueue::QOS_ATOMIC)
248 * @return bool Returns false on failure
249 * @throws MWException
251 final public function push( $jobs, $flags = 0 ) {
252 return $this->batchPush( is_array( $jobs ) ?
$jobs : array( $jobs ), $flags );
256 * Push a batch of jobs into the queue.
257 * This does not require $wgJobClasses to be set for the given job type.
258 * Outside callers should use JobQueueGroup::push() instead of this function.
260 * @param array $jobs List of Jobs
261 * @param $flags integer Bitfield (supports JobQueue::QOS_ATOMIC)
262 * @return bool Returns false on failure
263 * @throws MWException
265 final public function batchPush( array $jobs, $flags = 0 ) {
266 if ( !count( $jobs ) ) {
267 return true; // nothing to do
270 foreach ( $jobs as $job ) {
271 if ( $job->getType() !== $this->type
) {
272 throw new MWException(
273 "Got '{$job->getType()}' job; expected a '{$this->type}' job." );
274 } elseif ( $job->getReleaseTimestamp() && !$this->checkDelay
) {
275 throw new MWException(
276 "Got delayed '{$job->getType()}' job; delays are not supported." );
280 wfProfileIn( __METHOD__
);
281 $ok = $this->doBatchPush( $jobs, $flags );
282 wfProfileOut( __METHOD__
);
287 * @see JobQueue::batchPush()
290 abstract protected function doBatchPush( array $jobs, $flags );
293 * Pop a job off of the queue.
294 * This requires $wgJobClasses to be set for the given job type.
295 * Outside callers should use JobQueueGroup::pop() instead of this function.
297 * @return Job|bool Returns false if there are no jobs
298 * @throws MWException
300 final public function pop() {
301 global $wgJobClasses;
303 if ( $this->wiki
!== wfWikiID() ) {
304 throw new MWException( "Cannot pop '{$this->type}' job off foreign wiki queue." );
305 } elseif ( !isset( $wgJobClasses[$this->type
] ) ) {
306 // Do not pop jobs if there is no class for the queue type
307 throw new MWException( "Unrecognized job type '{$this->type}'." );
310 wfProfileIn( __METHOD__
);
311 $job = $this->doPop();
312 wfProfileOut( __METHOD__
);
314 // Flag this job as an old duplicate based on its "root" job...
316 if ( $job && $this->isRootJobOldDuplicate( $job ) ) {
317 wfIncrStats( 'job-pop-duplicate' );
318 $job = DuplicateJob
::newFromJob( $job ); // convert to a no-op
320 } catch ( MWException
$e ) {} // don't lose jobs over this
326 * @see JobQueue::pop()
329 abstract protected function doPop();
332 * Acknowledge that a job was completed.
334 * This does nothing for certain queue classes or if "claimTTL" is not set.
335 * Outside callers should use JobQueueGroup::ack() instead of this function.
339 * @throws MWException
341 final public function ack( Job
$job ) {
342 if ( $job->getType() !== $this->type
) {
343 throw new MWException( "Got '{$job->getType()}' job; expected '{$this->type}'." );
345 wfProfileIn( __METHOD__
);
346 $ok = $this->doAck( $job );
347 wfProfileOut( __METHOD__
);
352 * @see JobQueue::ack()
355 abstract protected function doAck( Job
$job );
358 * Register the "root job" of a given job into the queue for de-duplication.
359 * This should only be called right *after* all the new jobs have been inserted.
360 * This is used to turn older, duplicate, job entries into no-ops. The root job
361 * information will remain in the registry until it simply falls out of cache.
363 * This requires that $job has two special fields in the "params" array:
364 * - rootJobSignature : hash (e.g. SHA1) that identifies the task
365 * - rootJobTimestamp : TS_MW timestamp of this instance of the task
367 * A "root job" is a conceptual job that consist of potentially many smaller jobs
368 * that are actually inserted into the queue. For example, "refreshLinks" jobs are
369 * spawned when a template is edited. One can think of the task as "update links
370 * of pages that use template X" and an instance of that task as a "root job".
371 * However, what actually goes into the queue are potentially many refreshLinks2 jobs.
372 * Since these jobs include things like page ID ranges and DB master positions, and morph
373 * into smaller refreshLinks2 jobs recursively, simple duplicate detection (like job_sha1)
374 * for individual jobs being identical is not useful.
376 * In the case of "refreshLinks", if these jobs are still in the queue when the template
377 * is edited again, we want all of these old refreshLinks jobs for that template to become
378 * no-ops. This can greatly reduce server load, since refreshLinks jobs involves parsing.
379 * Essentially, the new batch of jobs belong to a new "root job" and the older ones to a
380 * previous "root job" for the same task of "update links of pages that use template X".
382 * This does nothing for certain queue classes.
386 * @throws MWException
388 final public function deduplicateRootJob( Job
$job ) {
389 if ( $job->getType() !== $this->type
) {
390 throw new MWException( "Got '{$job->getType()}' job; expected '{$this->type}'." );
392 wfProfileIn( __METHOD__
);
393 $ok = $this->doDeduplicateRootJob( $job );
394 wfProfileOut( __METHOD__
);
399 * @see JobQueue::deduplicateRootJob()
403 protected function doDeduplicateRootJob( Job
$job ) {
406 $params = $job->getParams();
407 if ( !isset( $params['rootJobSignature'] ) ) {
408 throw new MWException( "Cannot register root job; missing 'rootJobSignature'." );
409 } elseif ( !isset( $params['rootJobTimestamp'] ) ) {
410 throw new MWException( "Cannot register root job; missing 'rootJobTimestamp'." );
412 $key = $this->getRootJobCacheKey( $params['rootJobSignature'] );
413 // Callers should call batchInsert() and then this function so that if the insert
414 // fails, the de-duplication registration will be aborted. Since the insert is
415 // deferred till "transaction idle", do the same here, so that the ordering is
416 // maintained. Having only the de-duplication registration succeed would cause
417 // jobs to become no-ops without any actual jobs that made them redundant.
418 $timestamp = $wgMemc->get( $key ); // current last timestamp of this job
419 if ( $timestamp && $timestamp >= $params['rootJobTimestamp'] ) {
420 return true; // a newer version of this root job was enqueued
423 // Update the timestamp of the last root job started at the location...
424 return $wgMemc->set( $key, $params['rootJobTimestamp'], JobQueueDB
::ROOTJOB_TTL
);
428 * Check if the "root" job of a given job has been superseded by a newer one
432 * @throws MWException
434 final protected function isRootJobOldDuplicate( Job
$job ) {
435 if ( $job->getType() !== $this->type
) {
436 throw new MWException( "Got '{$job->getType()}' job; expected '{$this->type}'." );
438 wfProfileIn( __METHOD__
);
439 $isDuplicate = $this->doIsRootJobOldDuplicate( $job );
440 wfProfileOut( __METHOD__
);
445 * @see JobQueue::isRootJobOldDuplicate()
449 protected function doIsRootJobOldDuplicate( Job
$job ) {
452 $params = $job->getParams();
453 if ( !isset( $params['rootJobSignature'] ) ) {
454 return false; // job has no de-deplication info
455 } elseif ( !isset( $params['rootJobTimestamp'] ) ) {
456 trigger_error( "Cannot check root job; missing 'rootJobTimestamp'." );
460 // Get the last time this root job was enqueued
461 $timestamp = $wgMemc->get( $this->getRootJobCacheKey( $params['rootJobSignature'] ) );
463 // Check if a new root job was started at the location after this one's...
464 return ( $timestamp && $timestamp > $params['rootJobTimestamp'] );
468 * @param string $signature Hash identifier of the root job
471 protected function getRootJobCacheKey( $signature ) {
472 list( $db, $prefix ) = wfSplitWikiID( $this->wiki
);
473 return wfForeignMemcKey( $db, $prefix, 'jobqueue', $this->type
, 'rootjob', $signature );
477 * Wait for any slaves or backup servers to catch up.
479 * This does nothing for certain queue classes.
482 * @throws MWException
484 final public function waitForBackups() {
485 wfProfileIn( __METHOD__
);
486 $this->doWaitForBackups();
487 wfProfileOut( __METHOD__
);
491 * @see JobQueue::waitForBackups()
494 protected function doWaitForBackups() {}
497 * Return a map of task names to task definition maps.
498 * A "task" is a fast periodic queue maintenance action.
499 * Mutually exclusive tasks must implement their own locking in the callback.
501 * Each task value is an associative array with:
502 * - name : the name of the task
503 * - callback : a PHP callable that performs the task
504 * - period : the period in seconds corresponding to the task frequency
508 final public function getPeriodicTasks() {
509 $tasks = $this->doGetPeriodicTasks();
510 foreach ( $tasks as $name => &$def ) {
511 $def['name'] = $name;
517 * @see JobQueue::getPeriodicTasks()
520 protected function doGetPeriodicTasks() {
525 * Clear any process and persistent caches
529 final public function flushCaches() {
530 wfProfileIn( __METHOD__
);
531 $this->doFlushCaches();
532 wfProfileOut( __METHOD__
);
536 * @see JobQueue::flushCaches()
539 protected function doFlushCaches() {}
542 * Get an iterator to traverse over all available jobs in this queue.
543 * This does not include jobs that are currently acquired or delayed.
544 * This should only be called on a queue that is no longer being popped.
546 * @return Iterator|Traversable|Array
547 * @throws MWException
549 abstract public function getAllQueuedJobs();
552 * Get an iterator to traverse over all delayed jobs in this queue.
553 * This should only be called on a queue that is no longer being popped.
555 * @return Iterator|Traversable|Array
556 * @throws MWException
559 public function getAllDelayedJobs() {
560 return array(); // not implemented
564 * Namespace the queue with a key to isolate it for testing
568 * @throws MWException
570 public function setTestingPrefix( $key ) {
571 throw new MWException( "Queue namespacing not supported for this queue type." );