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
38 const QoS_Atomic
= 1; // integer; "all-or-nothing" job insertions
40 const ROOTJOB_TTL
= 2419200; // integer; seconds to remember root jobs (28 days)
43 * @param $params array
45 protected function __construct( array $params ) {
46 $this->wiki
= $params['wiki'];
47 $this->type
= $params['type'];
48 $this->claimTTL
= isset( $params['claimTTL'] ) ?
$params['claimTTL'] : 0;
49 $this->maxTries
= isset( $params['maxTries'] ) ?
$params['maxTries'] : 3;
50 if ( isset( $params['order'] ) && $params['order'] !== 'any' ) {
51 $this->order
= $params['order'];
53 $this->order
= $this->optimalOrder();
55 if ( !in_array( $this->order
, $this->supportedOrders() ) ) {
56 throw new MWException( __CLASS__
. " does not support '{$this->order}' order." );
61 * Get a job queue object of the specified type.
63 * - class : What job class to use (determines job type)
64 * - wiki : wiki ID of the wiki the jobs are for (defaults to current wiki)
65 * - type : The name of the job types this queue handles
66 * - order : Order that pop() selects jobs, one of "fifo", "timestamp" or "random".
67 * If "fifo" is used, the queue will effectively be FIFO. Note that
68 * job completion will not appear to be exactly FIFO if there are multiple
69 * job runners since jobs can take different times to finish once popped.
70 * If "timestamp" is used, the queue will at least be loosely ordered
71 * by timestamp, allowing for some jobs to be popped off out of order.
72 * If "random" is used, pop() will pick jobs in random order.
73 * Note that it may only be weakly random (e.g. a lottery of the oldest X).
74 * If "any" is choosen, the queue will use whatever order is the fastest.
75 * This might be useful for improving concurrency for job acquisition.
76 * - claimTTL : If supported, the queue will recycle jobs that have been popped
77 * but not acknowledged as completed after this many seconds. Recycling
78 * of jobs simple means re-inserting them into the queue. Jobs can be
79 * attempted up to three times before being discarded.
81 * Queue classes should throw an exception if they do not support the options given.
83 * @param $params array
87 final public static function factory( array $params ) {
88 $class = $params['class'];
89 if ( !MWInit
::classExists( $class ) ) {
90 throw new MWException( "Invalid job queue class '$class'." );
92 $obj = new $class( $params );
93 if ( !( $obj instanceof self
) ) {
94 throw new MWException( "Class '$class' is not a " . __CLASS__
. " class." );
100 * @return string Wiki ID
102 final public function getWiki() {
107 * @return string Job type that this queue handles
109 final public function getType() {
114 * @return string One of (random, timestamp, fifo)
116 final public function getOrder() {
121 * @return Array Subset of (random, timestamp, fifo)
123 abstract protected function supportedOrders();
126 * @return string One of (random, timestamp, fifo)
128 abstract protected function optimalOrder();
131 * Quickly check if the queue is empty (has no available jobs).
132 * Queue classes should use caching if they are any slower without memcached.
134 * If caching is used, this might return false when there are actually no jobs.
135 * If pop() is called and returns false then it should correct the cache. Also,
136 * calling flushCaches() first prevents this. However, this affect is typically
137 * not distinguishable from the race condition between isEmpty() and pop().
140 * @throws MWException
142 final public function isEmpty() {
143 wfProfileIn( __METHOD__
);
144 $res = $this->doIsEmpty();
145 wfProfileOut( __METHOD__
);
150 * @see JobQueue::isEmpty()
153 abstract protected function doIsEmpty();
156 * Get the number of available (unacquired) jobs in the queue.
157 * Queue classes should use caching if they are any slower without memcached.
159 * If caching is used, this number might be out of date for a minute.
162 * @throws MWException
164 final public function getSize() {
165 wfProfileIn( __METHOD__
);
166 $res = $this->doGetSize();
167 wfProfileOut( __METHOD__
);
172 * @see JobQueue::getSize()
175 abstract protected function doGetSize();
178 * Get the number of acquired jobs (these are temporarily out of the queue).
179 * Queue classes should use caching if they are any slower without memcached.
181 * If caching is used, this number might be out of date for a minute.
184 * @throws MWException
186 final public function getAcquiredCount() {
187 wfProfileIn( __METHOD__
);
188 $res = $this->doGetAcquiredCount();
189 wfProfileOut( __METHOD__
);
194 * @see JobQueue::getAcquiredCount()
197 abstract protected function doGetAcquiredCount();
200 * Push a single jobs into the queue.
201 * This does not require $wgJobClasses to be set for the given job type.
202 * Outside callers should use JobQueueGroup::push() instead of this function.
204 * @param $jobs Job|Array
205 * @param $flags integer Bitfield (supports JobQueue::QoS_Atomic)
206 * @return bool Returns false on failure
207 * @throws MWException
209 final public function push( $jobs, $flags = 0 ) {
210 return $this->batchPush( is_array( $jobs ) ?
$jobs : array( $jobs ), $flags );
214 * Push a batch of jobs into the queue.
215 * This does not require $wgJobClasses to be set for the given job type.
216 * Outside callers should use JobQueueGroup::push() instead of this function.
218 * @param array $jobs List of Jobs
219 * @param $flags integer Bitfield (supports JobQueue::QoS_Atomic)
220 * @return bool Returns false on failure
221 * @throws MWException
223 final public function batchPush( array $jobs, $flags = 0 ) {
224 if ( !count( $jobs ) ) {
225 return true; // nothing to do
228 foreach ( $jobs as $job ) {
229 if ( $job->getType() !== $this->type
) {
230 throw new MWException( "Got '{$job->getType()}' job; expected '{$this->type}'." );
234 wfProfileIn( __METHOD__
);
235 $ok = $this->doBatchPush( $jobs, $flags );
236 wfProfileOut( __METHOD__
);
241 * @see JobQueue::batchPush()
244 abstract protected function doBatchPush( array $jobs, $flags );
247 * Pop a job off of the queue.
248 * This requires $wgJobClasses to be set for the given job type.
249 * Outside callers should use JobQueueGroup::pop() instead of this function.
251 * @return Job|bool Returns false if there are no jobs
252 * @throws MWException
254 final public function pop() {
255 global $wgJobClasses;
257 if ( $this->wiki
!== wfWikiID() ) {
258 throw new MWException( "Cannot pop '{$this->type}' job off foreign wiki queue." );
259 } elseif ( !isset( $wgJobClasses[$this->type
] ) ) {
260 // Do not pop jobs if there is no class for the queue type
261 throw new MWException( "Unrecognized job type '{$this->type}'." );
264 wfProfileIn( __METHOD__
);
265 $job = $this->doPop();
266 wfProfileOut( __METHOD__
);
268 // Flag this job as an old duplicate based on its "root" job...
270 if ( $job && $this->isRootJobOldDuplicate( $job ) ) {
271 wfIncrStats( 'job-pop-duplicate' );
272 $job = DuplicateJob
::newFromJob( $job ); // convert to a no-op
274 } catch ( MWException
$e ) {} // don't lose jobs over this
280 * @see JobQueue::pop()
283 abstract protected function doPop();
286 * Acknowledge that a job was completed.
288 * This does nothing for certain queue classes or if "claimTTL" is not set.
289 * Outside callers should use JobQueueGroup::ack() instead of this function.
293 * @throws MWException
295 final public function ack( Job
$job ) {
296 if ( $job->getType() !== $this->type
) {
297 throw new MWException( "Got '{$job->getType()}' job; expected '{$this->type}'." );
299 wfProfileIn( __METHOD__
);
300 $ok = $this->doAck( $job );
301 wfProfileOut( __METHOD__
);
306 * @see JobQueue::ack()
309 abstract protected function doAck( Job
$job );
312 * Register the "root job" of a given job into the queue for de-duplication.
313 * This should only be called right *after* all the new jobs have been inserted.
314 * This is used to turn older, duplicate, job entries into no-ops. The root job
315 * information will remain in the registry until it simply falls out of cache.
317 * This requires that $job has two special fields in the "params" array:
318 * - rootJobSignature : hash (e.g. SHA1) that identifies the task
319 * - rootJobTimestamp : TS_MW timestamp of this instance of the task
321 * A "root job" is a conceptual job that consist of potentially many smaller jobs
322 * that are actually inserted into the queue. For example, "refreshLinks" jobs are
323 * spawned when a template is edited. One can think of the task as "update links
324 * of pages that use template X" and an instance of that task as a "root job".
325 * However, what actually goes into the queue are potentially many refreshLinks2 jobs.
326 * Since these jobs include things like page ID ranges and DB master positions, and morph
327 * into smaller refreshLinks2 jobs recursively, simple duplicate detection (like job_sha1)
328 * for individual jobs being identical is not useful.
330 * In the case of "refreshLinks", if these jobs are still in the queue when the template
331 * is edited again, we want all of these old refreshLinks jobs for that template to become
332 * no-ops. This can greatly reduce server load, since refreshLinks jobs involves parsing.
333 * Essentially, the new batch of jobs belong to a new "root job" and the older ones to a
334 * previous "root job" for the same task of "update links of pages that use template X".
336 * This does nothing for certain queue classes.
340 * @throws MWException
342 final public function deduplicateRootJob( Job
$job ) {
343 if ( $job->getType() !== $this->type
) {
344 throw new MWException( "Got '{$job->getType()}' job; expected '{$this->type}'." );
346 wfProfileIn( __METHOD__
);
347 $ok = $this->doDeduplicateRootJob( $job );
348 wfProfileOut( __METHOD__
);
353 * @see JobQueue::deduplicateRootJob()
357 protected function doDeduplicateRootJob( Job
$job ) {
360 $params = $job->getParams();
361 if ( !isset( $params['rootJobSignature'] ) ) {
362 throw new MWException( "Cannot register root job; missing 'rootJobSignature'." );
363 } elseif ( !isset( $params['rootJobTimestamp'] ) ) {
364 throw new MWException( "Cannot register root job; missing 'rootJobTimestamp'." );
366 $key = $this->getRootJobCacheKey( $params['rootJobSignature'] );
367 // Callers should call batchInsert() and then this function so that if the insert
368 // fails, the de-duplication registration will be aborted. Since the insert is
369 // deferred till "transaction idle", do the same here, so that the ordering is
370 // maintained. Having only the de-duplication registration succeed would cause
371 // jobs to become no-ops without any actual jobs that made them redundant.
372 $timestamp = $wgMemc->get( $key ); // current last timestamp of this job
373 if ( $timestamp && $timestamp >= $params['rootJobTimestamp'] ) {
374 return true; // a newer version of this root job was enqueued
377 // Update the timestamp of the last root job started at the location...
378 return $wgMemc->set( $key, $params['rootJobTimestamp'], JobQueueDB
::ROOTJOB_TTL
);
382 * Check if the "root" job of a given job has been superseded by a newer one
386 * @throws MWException
388 final protected function isRootJobOldDuplicate( Job
$job ) {
389 if ( $job->getType() !== $this->type
) {
390 throw new MWException( "Got '{$job->getType()}' job; expected '{$this->type}'." );
392 wfProfileIn( __METHOD__
);
393 $isDuplicate = $this->doIsRootJobOldDuplicate( $job );
394 wfProfileOut( __METHOD__
);
399 * @see JobQueue::isRootJobOldDuplicate()
403 protected function doIsRootJobOldDuplicate( Job
$job ) {
406 $params = $job->getParams();
407 if ( !isset( $params['rootJobSignature'] ) ) {
408 return false; // job has no de-deplication info
409 } elseif ( !isset( $params['rootJobTimestamp'] ) ) {
410 trigger_error( "Cannot check root job; missing 'rootJobTimestamp'." );
414 // Get the last time this root job was enqueued
415 $timestamp = $wgMemc->get( $this->getRootJobCacheKey( $params['rootJobSignature'] ) );
417 // Check if a new root job was started at the location after this one's...
418 return ( $timestamp && $timestamp > $params['rootJobTimestamp'] );
422 * @param string $signature Hash identifier of the root job
425 protected function getRootJobCacheKey( $signature ) {
426 list( $db, $prefix ) = wfSplitWikiID( $this->wiki
);
427 return wfForeignMemcKey( $db, $prefix, 'jobqueue', $this->type
, 'rootjob', $signature );
431 * Wait for any slaves or backup servers to catch up.
433 * This does nothing for certain queue classes.
436 * @throws MWException
438 final public function waitForBackups() {
439 wfProfileIn( __METHOD__
);
440 $this->doWaitForBackups();
441 wfProfileOut( __METHOD__
);
445 * @see JobQueue::waitForBackups()
448 protected function doWaitForBackups() {}
451 * Return a map of task names to task definition maps.
452 * A "task" is a fast periodic queue maintenance action.
453 * Mutually exclusive tasks must implement their own locking in the callback.
455 * Each task value is an associative array with:
456 * - name : the name of the task
457 * - callback : a PHP callable that performs the task
458 * - period : the period in seconds corresponding to the task frequency
462 final public function getPeriodicTasks() {
463 $tasks = $this->doGetPeriodicTasks();
464 foreach ( $tasks as $name => &$def ) {
465 $def['name'] = $name;
471 * @see JobQueue::getPeriodicTasks()
474 protected function doGetPeriodicTasks() {
479 * Clear any process and persistent caches
483 final public function flushCaches() {
484 wfProfileIn( __METHOD__
);
485 $this->doFlushCaches();
486 wfProfileOut( __METHOD__
);
490 * @see JobQueue::flushCaches()
493 protected function doFlushCaches() {}
496 * Get an iterator to traverse over all of the jobs in this queue.
497 * This does not include jobs that are current acquired. In general,
498 * this should only be called on a queue that is no longer being popped.
500 * @return Iterator|Traversable|Array
501 * @throws MWException
503 abstract public function getAllQueuedJobs();
506 * Namespace the queue with a key to isolate it for testing
510 * @throws MWException
512 public function setTestingPrefix( $key ) {
513 throw new MWException( "Queue namespacing not supported for this queue type." );