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.
133 * @throws MWException
135 final public function isEmpty() {
136 wfProfileIn( __METHOD__
);
137 $res = $this->doIsEmpty();
138 wfProfileOut( __METHOD__
);
143 * @see JobQueue::isEmpty()
146 abstract protected function doIsEmpty();
149 * Get the number of available jobs in the queue.
150 * Queue classes should use caching if they are any slower without memcached.
153 * @throws MWException
155 final public function getSize() {
156 wfProfileIn( __METHOD__
);
157 $res = $this->doGetSize();
158 wfProfileOut( __METHOD__
);
163 * @see JobQueue::getSize()
166 abstract protected function doGetSize();
169 * Get the number of acquired jobs (these are temporarily out of the queue).
170 * Queue classes should use caching if they are any slower without memcached.
173 * @throws MWException
175 final public function getAcquiredCount() {
176 wfProfileIn( __METHOD__
);
177 $res = $this->doGetAcquiredCount();
178 wfProfileOut( __METHOD__
);
183 * @see JobQueue::getAcquiredCount()
186 abstract protected function doGetAcquiredCount();
189 * Push a single jobs into the queue.
190 * This does not require $wgJobClasses to be set for the given job type.
191 * Outside callers should use JobQueueGroup::push() instead of this function.
193 * @param $jobs Job|Array
194 * @param $flags integer Bitfield (supports JobQueue::QoS_Atomic)
195 * @return bool Returns false on failure
196 * @throws MWException
198 final public function push( $jobs, $flags = 0 ) {
199 return $this->batchPush( is_array( $jobs ) ?
$jobs : array( $jobs ), $flags );
203 * Push a batch of jobs into the queue.
204 * This does not require $wgJobClasses to be set for the given job type.
205 * Outside callers should use JobQueueGroup::push() instead of this function.
207 * @param $jobs array List of Jobs
208 * @param $flags integer Bitfield (supports JobQueue::QoS_Atomic)
209 * @return bool Returns false on failure
210 * @throws MWException
212 final public function batchPush( array $jobs, $flags = 0 ) {
213 if ( !count( $jobs ) ) {
214 return true; // nothing to do
216 foreach ( $jobs as $job ) {
217 if ( $job->getType() !== $this->type
) {
218 throw new MWException( "Got '{$job->getType()}' job; expected '{$this->type}'." );
222 wfProfileIn( __METHOD__
);
223 $ok = $this->doBatchPush( $jobs, $flags );
224 wfProfileOut( __METHOD__
);
229 * @see JobQueue::batchPush()
232 abstract protected function doBatchPush( array $jobs, $flags );
235 * Pop a job off of the queue.
236 * This requires $wgJobClasses to be set for the given job type.
237 * Outside callers should use JobQueueGroup::pop() instead of this function.
239 * @return Job|bool Returns false if there are no jobs
240 * @throws MWException
242 final public function pop() {
243 global $wgJobClasses;
245 if ( $this->wiki
!== wfWikiID() ) {
246 throw new MWException( "Cannot pop '{$this->type}' job off foreign wiki queue." );
247 } elseif ( !isset( $wgJobClasses[$this->type
] ) ) {
248 // Do not pop jobs if there is no class for the queue type
249 throw new MWException( "Unrecognized job type '{$this->type}'." );
252 wfProfileIn( __METHOD__
);
253 $job = $this->doPop();
254 wfProfileOut( __METHOD__
);
259 * @see JobQueue::pop()
262 abstract protected function doPop();
265 * Acknowledge that a job was completed.
267 * This does nothing for certain queue classes or if "claimTTL" is not set.
268 * Outside callers should use JobQueueGroup::ack() instead of this function.
272 * @throws MWException
274 final public function ack( Job
$job ) {
275 if ( $job->getType() !== $this->type
) {
276 throw new MWException( "Got '{$job->getType()}' job; expected '{$this->type}'." );
278 wfProfileIn( __METHOD__
);
279 $ok = $this->doAck( $job );
280 wfProfileOut( __METHOD__
);
285 * @see JobQueue::ack()
288 abstract protected function doAck( Job
$job );
291 * Register the "root job" of a given job into the queue for de-duplication.
292 * This should only be called right *after* all the new jobs have been inserted.
293 * This is used to turn older, duplicate, job entries into no-ops. The root job
294 * information will remain in the registry until it simply falls out of cache.
296 * This requires that $job has two special fields in the "params" array:
297 * - rootJobSignature : hash (e.g. SHA1) that identifies the task
298 * - rootJobTimestamp : TS_MW timestamp of this instance of the task
300 * A "root job" is a conceptual job that consist of potentially many smaller jobs
301 * that are actually inserted into the queue. For example, "refreshLinks" jobs are
302 * spawned when a template is edited. One can think of the task as "update links
303 * of pages that use template X" and an instance of that task as a "root job".
304 * However, what actually goes into the queue are potentially many refreshLinks2 jobs.
305 * Since these jobs include things like page ID ranges and DB master positions, and morph
306 * into smaller refreshLinks2 jobs recursively, simple duplicate detection (like job_sha1)
307 * for individual jobs being identical is not useful.
309 * In the case of "refreshLinks", if these jobs are still in the queue when the template
310 * is edited again, we want all of these old refreshLinks jobs for that template to become
311 * no-ops. This can greatly reduce server load, since refreshLinks jobs involves parsing.
312 * Essentially, the new batch of jobs belong to a new "root job" and the older ones to a
313 * previous "root job" for the same task of "update links of pages that use template X".
315 * This does nothing for certain queue classes.
319 * @throws MWException
321 final public function deduplicateRootJob( Job
$job ) {
322 if ( $job->getType() !== $this->type
) {
323 throw new MWException( "Got '{$job->getType()}' job; expected '{$this->type}'." );
325 wfProfileIn( __METHOD__
);
326 $ok = $this->doDeduplicateRootJob( $job );
327 wfProfileOut( __METHOD__
);
332 * @see JobQueue::deduplicateRootJob()
336 protected function doDeduplicateRootJob( Job
$job ) {
341 * Wait for any slaves or backup servers to catch up.
343 * This does nothing for certain queue classes.
346 * @throws MWException
348 final public function waitForBackups() {
349 wfProfileIn( __METHOD__
);
350 $this->doWaitForBackups();
351 wfProfileOut( __METHOD__
);
355 * @see JobQueue::waitForBackups()
358 protected function doWaitForBackups() {}
361 * Return a map of task names to task definition maps.
362 * A "task" is a fast periodic queue maintenance action.
363 * Mutually exclusive tasks must implement their own locking in the callback.
365 * Each task value is an associative array with:
366 * - name : the name of the task
367 * - callback : a PHP callable that performs the task
368 * - period : the period in seconds corresponding to the task frequency
372 final public function getPeriodicTasks() {
373 $tasks = $this->doGetPeriodicTasks();
374 foreach ( $tasks as $name => &$def ) {
375 $def['name'] = $name;
381 * @see JobQueue::getPeriodicTasks()
384 protected function doGetPeriodicTasks() {
389 * Clear any process and persistent caches
393 final public function flushCaches() {
394 wfProfileIn( __METHOD__
);
395 $this->doFlushCaches();
396 wfProfileOut( __METHOD__
);
400 * @see JobQueue::flushCaches()
403 protected function doFlushCaches() {}
406 * Get an iterator to traverse over all of the jobs in this queue.
407 * This does not include jobs that are current acquired. In general,
408 * this should only be called on a queue that is no longer being popped.
410 * @return Iterator|Traversable|Array
411 * @throws MWException
413 abstract public function getAllQueuedJobs();
416 * Namespace the queue with a key to isolate it for testing
420 * @throws MWException
422 public function setTestingPrefix( $key ) {
423 throw new MWException( "Queue namespacing not supported for this queue type." );