Merge "Special:ListGroupRights: Display the legend at the top"
[mediawiki.git] / includes / job / JobQueue.php
blobaa47432ff3f671ea4e6b440fe5aca103e7ca65b4
1 <?php
2 /**
3 * Job queue base code.
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
20 * @file
21 * @defgroup JobQueue JobQueue
22 * @author Aaron Schulz
25 /**
26 * Class to handle enqueueing and running of background jobs
28 * @ingroup JobQueue
29 * @since 1.21
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)
44 /**
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'];
54 } else {
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." );
66 /**
67 * Get a job queue object of the specified type.
68 * $params includes:
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
94 * @return JobQueue
95 * @throws MWException
97 final public static function factory( array $params ) {
98 $class = $params['class'];
99 if ( !class_exists( $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." );
106 return $obj;
110 * @return string Wiki ID
112 final public function getWiki() {
113 return $this->wiki;
117 * @return string Job type that this queue handles
119 final public function getType() {
120 return $this->type;
124 * @return string One of (random, timestamp, fifo, undefined)
126 final public function getOrder() {
127 return $this->order;
131 * @return bool Whether delayed jobs are enabled
132 * @since 1.22
134 final public function delayedJobsEnabled() {
135 return $this->checkDelay;
139 * Get the allowed queue orders for configuration validation
141 * @return Array Subset of (random, timestamp, fifo, undefined)
143 abstract protected function supportedOrders();
146 * Get the default queue order to use if configuration does not specify one
148 * @return string One of (random, timestamp, fifo, undefined)
150 abstract protected function optimalOrder();
153 * Find out if delayed jobs are supported for configuration validation
155 * @return boolean Whether delayed jobs are supported
157 protected function supportsDelayedJobs() {
158 return false; // not implemented
162 * Quickly check if the queue has no available (unacquired, non-delayed) jobs.
163 * Queue classes should use caching if they are any slower without memcached.
165 * If caching is used, this might return false when there are actually no jobs.
166 * If pop() is called and returns false then it should correct the cache. Also,
167 * calling flushCaches() first prevents this. However, this affect is typically
168 * not distinguishable from the race condition between isEmpty() and pop().
170 * @return bool
171 * @throws MWException
173 final public function isEmpty() {
174 wfProfileIn( __METHOD__ );
175 $res = $this->doIsEmpty();
176 wfProfileOut( __METHOD__ );
177 return $res;
181 * @see JobQueue::isEmpty()
182 * @return bool
184 abstract protected function doIsEmpty();
187 * Get the number of available (unacquired, non-delayed) jobs in the queue.
188 * Queue classes should use caching if they are any slower without memcached.
190 * If caching is used, this number might be out of date for a minute.
192 * @return integer
193 * @throws MWException
195 final public function getSize() {
196 wfProfileIn( __METHOD__ );
197 $res = $this->doGetSize();
198 wfProfileOut( __METHOD__ );
199 return $res;
203 * @see JobQueue::getSize()
204 * @return integer
206 abstract protected function doGetSize();
209 * Get the number of acquired jobs (these are temporarily out of the queue).
210 * Queue classes should use caching if they are any slower without memcached.
212 * If caching is used, this number might be out of date for a minute.
214 * @return integer
215 * @throws MWException
217 final public function getAcquiredCount() {
218 wfProfileIn( __METHOD__ );
219 $res = $this->doGetAcquiredCount();
220 wfProfileOut( __METHOD__ );
221 return $res;
225 * @see JobQueue::getAcquiredCount()
226 * @return integer
228 abstract protected function doGetAcquiredCount();
231 * Get the number of delayed jobs (these are temporarily out of the queue).
232 * Queue classes should use caching if they are any slower without memcached.
234 * If caching is used, this number might be out of date for a minute.
236 * @return integer
237 * @throws MWException
238 * @since 1.22
240 final public function getDelayedCount() {
241 wfProfileIn( __METHOD__ );
242 $res = $this->doGetDelayedCount();
243 wfProfileOut( __METHOD__ );
244 return $res;
248 * @see JobQueue::getDelayedCount()
249 * @return integer
251 protected function doGetDelayedCount() {
252 return 0; // not implemented
256 * Get the number of acquired jobs that can no longer be attempted.
257 * Queue classes should use caching if they are any slower without memcached.
259 * If caching is used, this number might be out of date for a minute.
261 * @return integer
262 * @throws MWException
264 final public function getAbandonedCount() {
265 wfProfileIn( __METHOD__ );
266 $res = $this->doGetAbandonedCount();
267 wfProfileOut( __METHOD__ );
268 return $res;
272 * @see JobQueue::getAbandonedCount()
273 * @return integer
275 protected function doGetAbandonedCount() {
276 return 0; // not implemented
280 * Push a single jobs into the queue.
281 * This does not require $wgJobClasses to be set for the given job type.
282 * Outside callers should use JobQueueGroup::push() instead of this function.
284 * @param $jobs Job|Array
285 * @param $flags integer Bitfield (supports JobQueue::QOS_ATOMIC)
286 * @return bool Returns false on failure
287 * @throws MWException
289 final public function push( $jobs, $flags = 0 ) {
290 return $this->batchPush( is_array( $jobs ) ? $jobs : array( $jobs ), $flags );
294 * Push a batch of jobs into the queue.
295 * This does not require $wgJobClasses to be set for the given job type.
296 * Outside callers should use JobQueueGroup::push() instead of this function.
298 * @param array $jobs List of Jobs
299 * @param $flags integer Bitfield (supports JobQueue::QOS_ATOMIC)
300 * @return bool Returns false on failure
301 * @throws MWException
303 final public function batchPush( array $jobs, $flags = 0 ) {
304 if ( !count( $jobs ) ) {
305 return true; // nothing to do
308 foreach ( $jobs as $job ) {
309 if ( $job->getType() !== $this->type ) {
310 throw new MWException(
311 "Got '{$job->getType()}' job; expected a '{$this->type}' job." );
312 } elseif ( $job->getReleaseTimestamp() && !$this->checkDelay ) {
313 throw new MWException(
314 "Got delayed '{$job->getType()}' job; delays are not supported." );
318 wfProfileIn( __METHOD__ );
319 $ok = $this->doBatchPush( $jobs, $flags );
320 wfProfileOut( __METHOD__ );
321 return $ok;
325 * @see JobQueue::batchPush()
326 * @return bool
328 abstract protected function doBatchPush( array $jobs, $flags );
331 * Pop a job off of the queue.
332 * This requires $wgJobClasses to be set for the given job type.
333 * Outside callers should use JobQueueGroup::pop() instead of this function.
335 * @return Job|bool Returns false if there are no jobs
336 * @throws MWException
338 final public function pop() {
339 global $wgJobClasses;
341 if ( $this->wiki !== wfWikiID() ) {
342 throw new MWException( "Cannot pop '{$this->type}' job off foreign wiki queue." );
343 } elseif ( !isset( $wgJobClasses[$this->type] ) ) {
344 // Do not pop jobs if there is no class for the queue type
345 throw new MWException( "Unrecognized job type '{$this->type}'." );
348 wfProfileIn( __METHOD__ );
349 $job = $this->doPop();
350 wfProfileOut( __METHOD__ );
352 // Flag this job as an old duplicate based on its "root" job...
353 try {
354 if ( $job && $this->isRootJobOldDuplicate( $job ) ) {
355 JobQueue::incrStats( 'job-pop-duplicate', $this->type );
356 $job = DuplicateJob::newFromJob( $job ); // convert to a no-op
358 } catch ( MWException $e ) {} // don't lose jobs over this
360 return $job;
364 * @see JobQueue::pop()
365 * @return Job
367 abstract protected function doPop();
370 * Acknowledge that a job was completed.
372 * This does nothing for certain queue classes or if "claimTTL" is not set.
373 * Outside callers should use JobQueueGroup::ack() instead of this function.
375 * @param $job Job
376 * @return bool
377 * @throws MWException
379 final public function ack( Job $job ) {
380 if ( $job->getType() !== $this->type ) {
381 throw new MWException( "Got '{$job->getType()}' job; expected '{$this->type}'." );
383 wfProfileIn( __METHOD__ );
384 $ok = $this->doAck( $job );
385 wfProfileOut( __METHOD__ );
386 return $ok;
390 * @see JobQueue::ack()
391 * @return bool
393 abstract protected function doAck( Job $job );
396 * Register the "root job" of a given job into the queue for de-duplication.
397 * This should only be called right *after* all the new jobs have been inserted.
398 * This is used to turn older, duplicate, job entries into no-ops. The root job
399 * information will remain in the registry until it simply falls out of cache.
401 * This requires that $job has two special fields in the "params" array:
402 * - rootJobSignature : hash (e.g. SHA1) that identifies the task
403 * - rootJobTimestamp : TS_MW timestamp of this instance of the task
405 * A "root job" is a conceptual job that consist of potentially many smaller jobs
406 * that are actually inserted into the queue. For example, "refreshLinks" jobs are
407 * spawned when a template is edited. One can think of the task as "update links
408 * of pages that use template X" and an instance of that task as a "root job".
409 * However, what actually goes into the queue are potentially many refreshLinks2 jobs.
410 * Since these jobs include things like page ID ranges and DB master positions, and morph
411 * into smaller refreshLinks2 jobs recursively, simple duplicate detection (like job_sha1)
412 * for individual jobs being identical is not useful.
414 * In the case of "refreshLinks", if these jobs are still in the queue when the template
415 * is edited again, we want all of these old refreshLinks jobs for that template to become
416 * no-ops. This can greatly reduce server load, since refreshLinks jobs involves parsing.
417 * Essentially, the new batch of jobs belong to a new "root job" and the older ones to a
418 * previous "root job" for the same task of "update links of pages that use template X".
420 * This does nothing for certain queue classes.
422 * @param $job Job
423 * @return bool
424 * @throws MWException
426 final public function deduplicateRootJob( Job $job ) {
427 if ( $job->getType() !== $this->type ) {
428 throw new MWException( "Got '{$job->getType()}' job; expected '{$this->type}'." );
430 wfProfileIn( __METHOD__ );
431 $ok = $this->doDeduplicateRootJob( $job );
432 wfProfileOut( __METHOD__ );
433 return $ok;
437 * @see JobQueue::deduplicateRootJob()
438 * @param $job Job
439 * @return bool
441 protected function doDeduplicateRootJob( Job $job ) {
442 global $wgMemc;
444 if ( !$job->hasRootJobParams() ) {
445 throw new MWException( "Cannot register root job; missing parameters." );
447 $params = $job->getRootJobParams();
449 $key = $this->getRootJobCacheKey( $params['rootJobSignature'] );
450 // Callers should call batchInsert() and then this function so that if the insert
451 // fails, the de-duplication registration will be aborted. Since the insert is
452 // deferred till "transaction idle", do the same here, so that the ordering is
453 // maintained. Having only the de-duplication registration succeed would cause
454 // jobs to become no-ops without any actual jobs that made them redundant.
455 $timestamp = $wgMemc->get( $key ); // current last timestamp of this job
456 if ( $timestamp && $timestamp >= $params['rootJobTimestamp'] ) {
457 return true; // a newer version of this root job was enqueued
460 // Update the timestamp of the last root job started at the location...
461 return $wgMemc->set( $key, $params['rootJobTimestamp'], JobQueueDB::ROOTJOB_TTL );
465 * Check if the "root" job of a given job has been superseded by a newer one
467 * @param $job Job
468 * @return bool
469 * @throws MWException
471 final protected function isRootJobOldDuplicate( Job $job ) {
472 if ( $job->getType() !== $this->type ) {
473 throw new MWException( "Got '{$job->getType()}' job; expected '{$this->type}'." );
475 wfProfileIn( __METHOD__ );
476 $isDuplicate = $this->doIsRootJobOldDuplicate( $job );
477 wfProfileOut( __METHOD__ );
478 return $isDuplicate;
482 * @see JobQueue::isRootJobOldDuplicate()
483 * @param Job $job
484 * @return bool
486 protected function doIsRootJobOldDuplicate( Job $job ) {
487 global $wgMemc;
489 if ( !$job->hasRootJobParams() ) {
490 return false; // job has no de-deplication info
492 $params = $job->getRootJobParams();
494 // Get the last time this root job was enqueued
495 $timestamp = $wgMemc->get( $this->getRootJobCacheKey( $params['rootJobSignature'] ) );
497 // Check if a new root job was started at the location after this one's...
498 return ( $timestamp && $timestamp > $params['rootJobTimestamp'] );
502 * @param string $signature Hash identifier of the root job
503 * @return string
505 protected function getRootJobCacheKey( $signature ) {
506 list( $db, $prefix ) = wfSplitWikiID( $this->wiki );
507 return wfForeignMemcKey( $db, $prefix, 'jobqueue', $this->type, 'rootjob', $signature );
511 * Deleted all unclaimed and delayed jobs from the queue
513 * @return bool Success
514 * @throws MWException
515 * @since 1.22
517 final public function delete() {
518 wfProfileIn( __METHOD__ );
519 $res = $this->doDelete();
520 wfProfileOut( __METHOD__ );
521 return $res;
525 * @see JobQueue::delete()
526 * @return bool Success
528 protected function doDelete() {
529 throw new MWException( "This method is not implemented." );
533 * Wait for any slaves or backup servers to catch up.
535 * This does nothing for certain queue classes.
537 * @return void
538 * @throws MWException
540 final public function waitForBackups() {
541 wfProfileIn( __METHOD__ );
542 $this->doWaitForBackups();
543 wfProfileOut( __METHOD__ );
547 * @see JobQueue::waitForBackups()
548 * @return void
550 protected function doWaitForBackups() {}
553 * Return a map of task names to task definition maps.
554 * A "task" is a fast periodic queue maintenance action.
555 * Mutually exclusive tasks must implement their own locking in the callback.
557 * Each task value is an associative array with:
558 * - name : the name of the task
559 * - callback : a PHP callable that performs the task
560 * - period : the period in seconds corresponding to the task frequency
562 * @return Array
564 final public function getPeriodicTasks() {
565 $tasks = $this->doGetPeriodicTasks();
566 foreach ( $tasks as $name => &$def ) {
567 $def['name'] = $name;
569 return $tasks;
573 * @see JobQueue::getPeriodicTasks()
574 * @return Array
576 protected function doGetPeriodicTasks() {
577 return array();
581 * Clear any process and persistent caches
583 * @return void
585 final public function flushCaches() {
586 wfProfileIn( __METHOD__ );
587 $this->doFlushCaches();
588 wfProfileOut( __METHOD__ );
592 * @see JobQueue::flushCaches()
593 * @return void
595 protected function doFlushCaches() {}
598 * Get an iterator to traverse over all available jobs in this queue.
599 * This does not include jobs that are currently acquired or delayed.
600 * Note: results may be stale if the queue is concurrently modified.
602 * @return Iterator
603 * @throws MWException
605 abstract public function getAllQueuedJobs();
608 * Get an iterator to traverse over all delayed jobs in this queue.
609 * Note: results may be stale if the queue is concurrently modified.
611 * @return Iterator
612 * @throws MWException
613 * @since 1.22
615 public function getAllDelayedJobs() {
616 return new ArrayIterator( array() ); // not implemented
620 * Call wfIncrStats() for the queue overall and for the queue type
622 * @param string $key Event type
623 * @param string $type Job type
624 * @param integer $delta
625 * @since 1.22
627 public static function incrStats( $key, $type, $delta = 1 ) {
628 wfIncrStats( $key, $delta );
629 wfIncrStats( "{$key}-{$type}", $delta );
633 * Namespace the queue with a key to isolate it for testing
635 * @param $key string
636 * @return void
637 * @throws MWException
639 public function setTestingPrefix( $key ) {
640 throw new MWException( "Queue namespacing not supported for this queue type." );