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
41 * @param $params array
43 protected function __construct( array $params ) {
44 $this->wiki
= $params['wiki'];
45 $this->type
= $params['type'];
46 $this->claimTTL
= isset( $params['claimTTL'] ) ?
$params['claimTTL'] : 0;
47 $this->maxTries
= isset( $params['maxTries'] ) ?
$params['maxTries'] : 3;
48 if ( isset( $params['order'] ) && $params['order'] !== 'any' ) {
49 $this->order
= $params['order'];
51 $this->order
= $this->optimalOrder();
53 if ( !in_array( $this->order
, $this->supportedOrders() ) ) {
54 throw new MWException( __CLASS__
. " does not support '{$this->order}' order." );
59 * Get a job queue object of the specified type.
61 * - class : What job class to use (determines job type)
62 * - wiki : wiki ID of the wiki the jobs are for (defaults to current wiki)
63 * - type : The name of the job types this queue handles
64 * - order : Order that pop() selects jobs, one of "fifo", "timestamp" or "random".
65 * If "fifo" is used, the queue will effectively be FIFO. Note that
66 * job completion will not appear to be exactly FIFO if there are multiple
67 * job runners since jobs can take different times to finish once popped.
68 * If "timestamp" is used, the queue will at least be loosely ordered
69 * by timestamp, allowing for some jobs to be popped off out of order.
70 * If "random" is used, pop() will pick jobs in random order.
71 * Note that it may only be weakly random (e.g. a lottery of the oldest X).
72 * If "any" is choosen, the queue will use whatever order is the fastest.
73 * This might be useful for improving concurrency for job acquisition.
74 * - claimTTL : If supported, the queue will recycle jobs that have been popped
75 * but not acknowledged as completed after this many seconds. Recycling
76 * of jobs simple means re-inserting them into the queue. Jobs can be
77 * attempted up to three times before being discarded.
79 * Queue classes should throw an exception if they do not support the options given.
81 * @param $params array
85 final public static function factory( array $params ) {
86 $class = $params['class'];
87 if ( !MWInit
::classExists( $class ) ) {
88 throw new MWException( "Invalid job queue class '$class'." );
90 $obj = new $class( $params );
91 if ( !( $obj instanceof self
) ) {
92 throw new MWException( "Class '$class' is not a " . __CLASS__
. " class." );
98 * @return string Wiki ID
100 final public function getWiki() {
105 * @return string Job type that this queue handles
107 final public function getType() {
112 * @return string One of (random, timestamp, fifo)
114 final public function getOrder() {
119 * @return Array Subset of (random, timestamp, fifo)
121 abstract protected function supportedOrders();
124 * @return string One of (random, timestamp, fifo)
126 abstract protected function optimalOrder();
129 * Quickly check if the queue is empty (has no available jobs).
130 * Queue classes should use caching if they are any slower without memcached.
132 * If caching is used, this might return false when there are actually no jobs.
133 * If pop() is called and returns false then it should correct the cache. Also,
134 * calling flushCaches() first prevents this. However, this affect is typically
135 * not distinguishable from the race condition between isEmpty() and pop().
138 * @throws MWException
140 final public function isEmpty() {
141 wfProfileIn( __METHOD__
);
142 $res = $this->doIsEmpty();
143 wfProfileOut( __METHOD__
);
148 * @see JobQueue::isEmpty()
151 abstract protected function doIsEmpty();
154 * Get the number of available (unacquired) jobs in the queue.
155 * Queue classes should use caching if they are any slower without memcached.
157 * If caching is used, this number might be out of date for a minute.
160 * @throws MWException
162 final public function getSize() {
163 wfProfileIn( __METHOD__
);
164 $res = $this->doGetSize();
165 wfProfileOut( __METHOD__
);
170 * @see JobQueue::getSize()
173 abstract protected function doGetSize();
176 * Get the number of acquired jobs (these are temporarily out of the queue).
177 * Queue classes should use caching if they are any slower without memcached.
179 * If caching is used, this number might be out of date for a minute.
182 * @throws MWException
184 final public function getAcquiredCount() {
185 wfProfileIn( __METHOD__
);
186 $res = $this->doGetAcquiredCount();
187 wfProfileOut( __METHOD__
);
192 * @see JobQueue::getAcquiredCount()
195 abstract protected function doGetAcquiredCount();
198 * Push a single jobs into the queue.
199 * This does not require $wgJobClasses to be set for the given job type.
200 * Outside callers should use JobQueueGroup::push() instead of this function.
202 * @param $jobs Job|Array
203 * @param $flags integer Bitfield (supports JobQueue::QoS_Atomic)
204 * @return bool Returns false on failure
205 * @throws MWException
207 final public function push( $jobs, $flags = 0 ) {
208 return $this->batchPush( is_array( $jobs ) ?
$jobs : array( $jobs ), $flags );
212 * Push a batch of jobs into the queue.
213 * This does not require $wgJobClasses to be set for the given job type.
214 * Outside callers should use JobQueueGroup::push() instead of this function.
216 * @param array $jobs List of Jobs
217 * @param $flags integer Bitfield (supports JobQueue::QoS_Atomic)
218 * @return bool Returns false on failure
219 * @throws MWException
221 final public function batchPush( array $jobs, $flags = 0 ) {
222 if ( !count( $jobs ) ) {
223 return true; // nothing to do
226 foreach ( $jobs as $job ) {
227 if ( $job->getType() !== $this->type
) {
228 throw new MWException( "Got '{$job->getType()}' job; expected '{$this->type}'." );
232 wfProfileIn( __METHOD__
);
233 $ok = $this->doBatchPush( $jobs, $flags );
234 wfProfileOut( __METHOD__
);
239 * @see JobQueue::batchPush()
242 abstract protected function doBatchPush( array $jobs, $flags );
245 * Pop a job off of the queue.
246 * This requires $wgJobClasses to be set for the given job type.
247 * Outside callers should use JobQueueGroup::pop() instead of this function.
249 * @return Job|bool Returns false if there are no jobs
250 * @throws MWException
252 final public function pop() {
253 global $wgJobClasses;
255 if ( $this->wiki
!== wfWikiID() ) {
256 throw new MWException( "Cannot pop '{$this->type}' job off foreign wiki queue." );
257 } elseif ( !isset( $wgJobClasses[$this->type
] ) ) {
258 // Do not pop jobs if there is no class for the queue type
259 throw new MWException( "Unrecognized job type '{$this->type}'." );
262 wfProfileIn( __METHOD__
);
263 $job = $this->doPop();
264 wfProfileOut( __METHOD__
);
269 * @see JobQueue::pop()
272 abstract protected function doPop();
275 * Acknowledge that a job was completed.
277 * This does nothing for certain queue classes or if "claimTTL" is not set.
278 * Outside callers should use JobQueueGroup::ack() instead of this function.
282 * @throws MWException
284 final public function ack( Job
$job ) {
285 if ( $job->getType() !== $this->type
) {
286 throw new MWException( "Got '{$job->getType()}' job; expected '{$this->type}'." );
288 wfProfileIn( __METHOD__
);
289 $ok = $this->doAck( $job );
290 wfProfileOut( __METHOD__
);
295 * @see JobQueue::ack()
298 abstract protected function doAck( Job
$job );
301 * Register the "root job" of a given job into the queue for de-duplication.
302 * This should only be called right *after* all the new jobs have been inserted.
303 * This is used to turn older, duplicate, job entries into no-ops. The root job
304 * information will remain in the registry until it simply falls out of cache.
306 * This requires that $job has two special fields in the "params" array:
307 * - rootJobSignature : hash (e.g. SHA1) that identifies the task
308 * - rootJobTimestamp : TS_MW timestamp of this instance of the task
310 * A "root job" is a conceptual job that consist of potentially many smaller jobs
311 * that are actually inserted into the queue. For example, "refreshLinks" jobs are
312 * spawned when a template is edited. One can think of the task as "update links
313 * of pages that use template X" and an instance of that task as a "root job".
314 * However, what actually goes into the queue are potentially many refreshLinks2 jobs.
315 * Since these jobs include things like page ID ranges and DB master positions, and morph
316 * into smaller refreshLinks2 jobs recursively, simple duplicate detection (like job_sha1)
317 * for individual jobs being identical is not useful.
319 * In the case of "refreshLinks", if these jobs are still in the queue when the template
320 * is edited again, we want all of these old refreshLinks jobs for that template to become
321 * no-ops. This can greatly reduce server load, since refreshLinks jobs involves parsing.
322 * Essentially, the new batch of jobs belong to a new "root job" and the older ones to a
323 * previous "root job" for the same task of "update links of pages that use template X".
325 * This does nothing for certain queue classes.
329 * @throws MWException
331 final public function deduplicateRootJob( Job
$job ) {
332 if ( $job->getType() !== $this->type
) {
333 throw new MWException( "Got '{$job->getType()}' job; expected '{$this->type}'." );
335 wfProfileIn( __METHOD__
);
336 $ok = $this->doDeduplicateRootJob( $job );
337 wfProfileOut( __METHOD__
);
342 * @see JobQueue::deduplicateRootJob()
346 protected function doDeduplicateRootJob( Job
$job ) {
351 * Wait for any slaves or backup servers to catch up.
353 * This does nothing for certain queue classes.
356 * @throws MWException
358 final public function waitForBackups() {
359 wfProfileIn( __METHOD__
);
360 $this->doWaitForBackups();
361 wfProfileOut( __METHOD__
);
365 * @see JobQueue::waitForBackups()
368 protected function doWaitForBackups() {}
371 * Return a map of task names to task definition maps.
372 * A "task" is a fast periodic queue maintenance action.
373 * Mutually exclusive tasks must implement their own locking in the callback.
375 * Each task value is an associative array with:
376 * - name : the name of the task
377 * - callback : a PHP callable that performs the task
378 * - period : the period in seconds corresponding to the task frequency
382 final public function getPeriodicTasks() {
383 $tasks = $this->doGetPeriodicTasks();
384 foreach ( $tasks as $name => &$def ) {
385 $def['name'] = $name;
391 * @see JobQueue::getPeriodicTasks()
394 protected function doGetPeriodicTasks() {
399 * Clear any process and persistent caches
403 final public function flushCaches() {
404 wfProfileIn( __METHOD__
);
405 $this->doFlushCaches();
406 wfProfileOut( __METHOD__
);
410 * @see JobQueue::flushCaches()
413 protected function doFlushCaches() {}
416 * Get an iterator to traverse over all of the jobs in this queue.
417 * This does not include jobs that are current acquired. In general,
418 * this should only be called on a queue that is no longer being popped.
420 * @return Iterator|Traversable|Array
421 * @throws MWException
423 abstract public function getAllQueuedJobs();
426 * Namespace the queue with a key to isolate it for testing
430 * @throws MWException
432 public function setTestingPrefix( $key ) {
433 throw new MWException( "Queue namespacing not supported for this queue type." );