Fix hook situation for Skin::doEditSectionLink
[mediawiki.git] / includes / jobqueue / JobQueue.php
blob53fcaeeda04b60109712c00f4542507cb3c135aa
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 /** @var string Wiki ID */
33 protected $wiki;
35 /** @var string Job type */
36 protected $type;
38 /** @var string Job priority for pop() */
39 protected $order;
41 /** @var int Time to live in seconds */
42 protected $claimTTL;
44 /** @var int Maximum number of times to try a job */
45 protected $maxTries;
47 /** @var bool Allow delayed jobs */
48 protected $checkDelay;
50 /** @var BagOStuff */
51 protected $dupCache;
53 const QOS_ATOMIC = 1; // integer; "all-or-nothing" job insertions
55 const ROOTJOB_TTL = 2419200; // integer; seconds to remember root jobs (28 days)
57 /**
58 * @param array $params
59 * @throws MWException
61 protected function __construct( array $params ) {
62 $this->wiki = $params['wiki'];
63 $this->type = $params['type'];
64 $this->claimTTL = isset( $params['claimTTL'] ) ? $params['claimTTL'] : 0;
65 $this->maxTries = isset( $params['maxTries'] ) ? $params['maxTries'] : 3;
66 if ( isset( $params['order'] ) && $params['order'] !== 'any' ) {
67 $this->order = $params['order'];
68 } else {
69 $this->order = $this->optimalOrder();
71 if ( !in_array( $this->order, $this->supportedOrders() ) ) {
72 throw new MWException( __CLASS__ . " does not support '{$this->order}' order." );
74 $this->checkDelay = !empty( $params['checkDelay'] );
75 if ( $this->checkDelay && !$this->supportsDelayedJobs() ) {
76 throw new MWException( __CLASS__ . " does not support delayed jobs." );
78 $this->dupCache = wfGetCache( CACHE_ANYTHING );
81 /**
82 * Get a job queue object of the specified type.
83 * $params includes:
84 * - class : What job class to use (determines job type)
85 * - wiki : wiki ID of the wiki the jobs are for (defaults to current wiki)
86 * - type : The name of the job types this queue handles
87 * - order : Order that pop() selects jobs, one of "fifo", "timestamp" or "random".
88 * If "fifo" is used, the queue will effectively be FIFO. Note that job
89 * completion will not appear to be exactly FIFO if there are multiple
90 * job runners since jobs can take different times to finish once popped.
91 * If "timestamp" is used, the queue will at least be loosely ordered
92 * by timestamp, allowing for some jobs to be popped off out of order.
93 * If "random" is used, pop() will pick jobs in random order.
94 * Note that it may only be weakly random (e.g. a lottery of the oldest X).
95 * If "any" is choosen, the queue will use whatever order is the fastest.
96 * This might be useful for improving concurrency for job acquisition.
97 * - claimTTL : If supported, the queue will recycle jobs that have been popped
98 * but not acknowledged as completed after this many seconds. Recycling
99 * of jobs simple means re-inserting them into the queue. Jobs can be
100 * attempted up to three times before being discarded.
101 * - checkDelay : If supported, respect Job::getReleaseTimestamp() in the push functions.
102 * This lets delayed jobs wait in a staging area until a given timestamp is
103 * reached, at which point they will enter the queue. If this is not enabled
104 * or not supported, an exception will be thrown on delayed job insertion.
106 * Queue classes should throw an exception if they do not support the options given.
108 * @param array $params
109 * @return JobQueue
110 * @throws MWException
112 final public static function factory( array $params ) {
113 $class = $params['class'];
114 if ( !class_exists( $class ) ) {
115 throw new MWException( "Invalid job queue class '$class'." );
117 $obj = new $class( $params );
118 if ( !( $obj instanceof self ) ) {
119 throw new MWException( "Class '$class' is not a " . __CLASS__ . " class." );
122 return $obj;
126 * @return string Wiki ID
128 final public function getWiki() {
129 return $this->wiki;
133 * @return string Job type that this queue handles
135 final public function getType() {
136 return $this->type;
140 * @return string One of (random, timestamp, fifo, undefined)
142 final public function getOrder() {
143 return $this->order;
147 * @return bool Whether delayed jobs are enabled
148 * @since 1.22
150 final public function delayedJobsEnabled() {
151 return $this->checkDelay;
155 * Get the allowed queue orders for configuration validation
157 * @return array Subset of (random, timestamp, fifo, undefined)
159 abstract protected function supportedOrders();
162 * Get the default queue order to use if configuration does not specify one
164 * @return string One of (random, timestamp, fifo, undefined)
166 abstract protected function optimalOrder();
169 * Find out if delayed jobs are supported for configuration validation
171 * @return bool Whether delayed jobs are supported
173 protected function supportsDelayedJobs() {
174 return false; // not implemented
178 * Quickly check if the queue has no available (unacquired, non-delayed) jobs.
179 * Queue classes should use caching if they are any slower without memcached.
181 * If caching is used, this might return false when there are actually no jobs.
182 * If pop() is called and returns false then it should correct the cache. Also,
183 * calling flushCaches() first prevents this. However, this affect is typically
184 * not distinguishable from the race condition between isEmpty() and pop().
186 * @return bool
187 * @throws JobQueueError
189 final public function isEmpty() {
190 $res = $this->doIsEmpty();
192 return $res;
196 * @see JobQueue::isEmpty()
197 * @return bool
199 abstract protected function doIsEmpty();
202 * Get the number of available (unacquired, non-delayed) jobs in the queue.
203 * Queue classes should use caching if they are any slower without memcached.
205 * If caching is used, this number might be out of date for a minute.
207 * @return int
208 * @throws JobQueueError
210 final public function getSize() {
211 $res = $this->doGetSize();
213 return $res;
217 * @see JobQueue::getSize()
218 * @return int
220 abstract protected function doGetSize();
223 * Get the number of acquired jobs (these are temporarily out of the queue).
224 * Queue classes should use caching if they are any slower without memcached.
226 * If caching is used, this number might be out of date for a minute.
228 * @return int
229 * @throws JobQueueError
231 final public function getAcquiredCount() {
232 $res = $this->doGetAcquiredCount();
234 return $res;
238 * @see JobQueue::getAcquiredCount()
239 * @return int
241 abstract protected function doGetAcquiredCount();
244 * Get the number of delayed jobs (these are temporarily out of the queue).
245 * Queue classes should use caching if they are any slower without memcached.
247 * If caching is used, this number might be out of date for a minute.
249 * @return int
250 * @throws JobQueueError
251 * @since 1.22
253 final public function getDelayedCount() {
254 $res = $this->doGetDelayedCount();
256 return $res;
260 * @see JobQueue::getDelayedCount()
261 * @return int
263 protected function doGetDelayedCount() {
264 return 0; // not implemented
268 * Get the number of acquired jobs that can no longer be attempted.
269 * Queue classes should use caching if they are any slower without memcached.
271 * If caching is used, this number might be out of date for a minute.
273 * @return int
274 * @throws JobQueueError
276 final public function getAbandonedCount() {
277 $res = $this->doGetAbandonedCount();
279 return $res;
283 * @see JobQueue::getAbandonedCount()
284 * @return int
286 protected function doGetAbandonedCount() {
287 return 0; // not implemented
291 * Push one or more jobs into the queue.
292 * This does not require $wgJobClasses to be set for the given job type.
293 * Outside callers should use JobQueueGroup::push() instead of this function.
295 * @param Job|array $jobs A single job or an array of Jobs
296 * @param int $flags Bitfield (supports JobQueue::QOS_ATOMIC)
297 * @return void
298 * @throws JobQueueError
300 final public function push( $jobs, $flags = 0 ) {
301 $this->batchPush( is_array( $jobs ) ? $jobs : array( $jobs ), $flags );
305 * Push a batch of jobs into the queue.
306 * This does not require $wgJobClasses to be set for the given job type.
307 * Outside callers should use JobQueueGroup::push() instead of this function.
309 * @param array $jobs List of Jobs
310 * @param int $flags Bitfield (supports JobQueue::QOS_ATOMIC)
311 * @return void
312 * @throws MWException
314 final public function batchPush( array $jobs, $flags = 0 ) {
315 if ( !count( $jobs ) ) {
316 return; // nothing to do
319 foreach ( $jobs as $job ) {
320 if ( $job->getType() !== $this->type ) {
321 throw new MWException(
322 "Got '{$job->getType()}' job; expected a '{$this->type}' job." );
323 } elseif ( $job->getReleaseTimestamp() && !$this->checkDelay ) {
324 throw new MWException(
325 "Got delayed '{$job->getType()}' job; delays are not supported." );
329 $this->doBatchPush( $jobs, $flags );
333 * @see JobQueue::batchPush()
334 * @param array $jobs
335 * @param int $flags
337 abstract protected function doBatchPush( array $jobs, $flags );
340 * Pop a job off of the queue.
341 * This requires $wgJobClasses to be set for the given job type.
342 * Outside callers should use JobQueueGroup::pop() instead of this function.
344 * @throws MWException
345 * @return Job|bool Returns false if there are no jobs
347 final public function pop() {
348 global $wgJobClasses;
350 if ( $this->wiki !== wfWikiID() ) {
351 throw new MWException( "Cannot pop '{$this->type}' job off foreign wiki queue." );
352 } elseif ( !isset( $wgJobClasses[$this->type] ) ) {
353 // Do not pop jobs if there is no class for the queue type
354 throw new MWException( "Unrecognized job type '{$this->type}'." );
357 $job = $this->doPop();
359 // Flag this job as an old duplicate based on its "root" job...
360 try {
361 if ( $job && $this->isRootJobOldDuplicate( $job ) ) {
362 JobQueue::incrStats( 'job-pop-duplicate', $this->type, 1, $this->wiki );
363 $job = DuplicateJob::newFromJob( $job ); // convert to a no-op
365 } catch ( Exception $e ) {
366 // don't lose jobs over this
369 return $job;
373 * @see JobQueue::pop()
374 * @return Job
376 abstract protected function doPop();
379 * Acknowledge that a job was completed.
381 * This does nothing for certain queue classes or if "claimTTL" is not set.
382 * Outside callers should use JobQueueGroup::ack() instead of this function.
384 * @param Job $job
385 * @return void
386 * @throws MWException
388 final public function ack( Job $job ) {
389 if ( $job->getType() !== $this->type ) {
390 throw new MWException( "Got '{$job->getType()}' job; expected '{$this->type}'." );
392 $this->doAck( $job );
396 * @see JobQueue::ack()
397 * @param Job $job
399 abstract protected function doAck( Job $job );
402 * Register the "root job" of a given job into the queue for de-duplication.
403 * This should only be called right *after* all the new jobs have been inserted.
404 * This is used to turn older, duplicate, job entries into no-ops. The root job
405 * information will remain in the registry until it simply falls out of cache.
407 * This requires that $job has two special fields in the "params" array:
408 * - rootJobSignature : hash (e.g. SHA1) that identifies the task
409 * - rootJobTimestamp : TS_MW timestamp of this instance of the task
411 * A "root job" is a conceptual job that consist of potentially many smaller jobs
412 * that are actually inserted into the queue. For example, "refreshLinks" jobs are
413 * spawned when a template is edited. One can think of the task as "update links
414 * of pages that use template X" and an instance of that task as a "root job".
415 * However, what actually goes into the queue are range and leaf job subtypes.
416 * Since these jobs include things like page ID ranges and DB master positions,
417 * and can morph into smaller jobs recursively, simple duplicate detection
418 * for individual jobs being identical (like that of job_sha1) is not useful.
420 * In the case of "refreshLinks", if these jobs are still in the queue when the template
421 * is edited again, we want all of these old refreshLinks jobs for that template to become
422 * no-ops. This can greatly reduce server load, since refreshLinks jobs involves parsing.
423 * Essentially, the new batch of jobs belong to a new "root job" and the older ones to a
424 * previous "root job" for the same task of "update links of pages that use template X".
426 * This does nothing for certain queue classes.
428 * @param Job $job
429 * @throws MWException
430 * @return bool
432 final public function deduplicateRootJob( Job $job ) {
433 if ( $job->getType() !== $this->type ) {
434 throw new MWException( "Got '{$job->getType()}' job; expected '{$this->type}'." );
436 $ok = $this->doDeduplicateRootJob( $job );
438 return $ok;
442 * @see JobQueue::deduplicateRootJob()
443 * @param Job $job
444 * @throws MWException
445 * @return bool
447 protected function doDeduplicateRootJob( Job $job ) {
448 if ( !$job->hasRootJobParams() ) {
449 throw new MWException( "Cannot register root job; missing parameters." );
451 $params = $job->getRootJobParams();
453 $key = $this->getRootJobCacheKey( $params['rootJobSignature'] );
454 // Callers should call batchInsert() and then this function so that if the insert
455 // fails, the de-duplication registration will be aborted. Since the insert is
456 // deferred till "transaction idle", do the same here, so that the ordering is
457 // maintained. Having only the de-duplication registration succeed would cause
458 // jobs to become no-ops without any actual jobs that made them redundant.
459 $timestamp = $this->dupCache->get( $key ); // current last timestamp of this job
460 if ( $timestamp && $timestamp >= $params['rootJobTimestamp'] ) {
461 return true; // a newer version of this root job was enqueued
464 // Update the timestamp of the last root job started at the location...
465 return $this->dupCache->set( $key, $params['rootJobTimestamp'], JobQueueDB::ROOTJOB_TTL );
469 * Check if the "root" job of a given job has been superseded by a newer one
471 * @param Job $job
472 * @throws MWException
473 * @return bool
475 final protected function isRootJobOldDuplicate( Job $job ) {
476 if ( $job->getType() !== $this->type ) {
477 throw new MWException( "Got '{$job->getType()}' job; expected '{$this->type}'." );
479 $isDuplicate = $this->doIsRootJobOldDuplicate( $job );
481 return $isDuplicate;
485 * @see JobQueue::isRootJobOldDuplicate()
486 * @param Job $job
487 * @return bool
489 protected function doIsRootJobOldDuplicate( Job $job ) {
490 if ( !$job->hasRootJobParams() ) {
491 return false; // job has no de-deplication info
493 $params = $job->getRootJobParams();
495 $key = $this->getRootJobCacheKey( $params['rootJobSignature'] );
496 // Get the last time this root job was enqueued
497 $timestamp = $this->dupCache->get( $key );
499 // Check if a new root job was started at the location after this one's...
500 return ( $timestamp && $timestamp > $params['rootJobTimestamp'] );
504 * @param string $signature Hash identifier of the root job
505 * @return string
507 protected function getRootJobCacheKey( $signature ) {
508 list( $db, $prefix ) = wfSplitWikiID( $this->wiki );
510 return wfForeignMemcKey( $db, $prefix, 'jobqueue', $this->type, 'rootjob', $signature );
514 * Deleted all unclaimed and delayed jobs from the queue
516 * @throws JobQueueError
517 * @since 1.22
518 * @return void
520 final public function delete() {
521 $this->doDelete();
525 * @see JobQueue::delete()
526 * @throws MWException
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 JobQueueError
540 final public function waitForBackups() {
541 $this->doWaitForBackups();
545 * @see JobQueue::waitForBackups()
546 * @return void
548 protected function doWaitForBackups() {
552 * Return a map of task names to task definition maps.
553 * A "task" is a fast periodic queue maintenance action.
554 * Mutually exclusive tasks must implement their own locking in the callback.
556 * Each task value is an associative array with:
557 * - name : the name of the task
558 * - callback : a PHP callable that performs the task
559 * - period : the period in seconds corresponding to the task frequency
561 * @return array
563 final public function getPeriodicTasks() {
564 $tasks = $this->doGetPeriodicTasks();
565 foreach ( $tasks as $name => &$def ) {
566 $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 $this->doFlushCaches();
590 * @see JobQueue::flushCaches()
591 * @return void
593 protected function doFlushCaches() {
597 * Get an iterator to traverse over all available jobs in this queue.
598 * This does not include jobs that are currently acquired or delayed.
599 * Note: results may be stale if the queue is concurrently modified.
601 * @return Iterator
602 * @throws JobQueueError
604 abstract public function getAllQueuedJobs();
607 * Get an iterator to traverse over all delayed jobs in this queue.
608 * Note: results may be stale if the queue is concurrently modified.
610 * @return Iterator
611 * @throws JobQueueError
612 * @since 1.22
614 public function getAllDelayedJobs() {
615 return new ArrayIterator( array() ); // not implemented
619 * Do not use this function outside of JobQueue/JobQueueGroup
621 * @return string
622 * @since 1.22
624 public function getCoalesceLocationInternal() {
625 return null;
629 * Check whether each of the given queues are empty.
630 * This is used for batching checks for queues stored at the same place.
632 * @param array $types List of queues types
633 * @return array|null (list of non-empty queue types) or null if unsupported
634 * @throws MWException
635 * @since 1.22
637 final public function getSiblingQueuesWithJobs( array $types ) {
639 return $this->doGetSiblingQueuesWithJobs( $types );
643 * @see JobQueue::getSiblingQueuesWithJobs()
644 * @param array $types List of queues types
645 * @return array|null (list of queue types) or null if unsupported
647 protected function doGetSiblingQueuesWithJobs( array $types ) {
648 return null; // not supported
652 * Check the size of each of the given queues.
653 * For queues not served by the same store as this one, 0 is returned.
654 * This is used for batching checks for queues stored at the same place.
656 * @param array $types List of queues types
657 * @return array|null (job type => whether queue is empty) or null if unsupported
658 * @throws MWException
659 * @since 1.22
661 final public function getSiblingQueueSizes( array $types ) {
663 return $this->doGetSiblingQueueSizes( $types );
667 * @see JobQueue::getSiblingQueuesSize()
668 * @param array $types List of queues types
669 * @return array|null (list of queue types) or null if unsupported
671 protected function doGetSiblingQueueSizes( array $types ) {
672 return null; // not supported
676 * Call wfIncrStats() for the queue overall and for the queue type
678 * @param string $key Event type
679 * @param string $type Job type
680 * @param int $delta
681 * @param string $wiki Wiki ID (added in 1.23)
682 * @since 1.22
684 public static function incrStats( $key, $type, $delta = 1, $wiki = null ) {
685 wfIncrStats( $key, $delta );
686 wfIncrStats( "{$key}-{$type}", $delta );
687 if ( $wiki !== null ) {
688 wfIncrStats( "{$key}-{$type}-{$wiki}", $delta );
693 * Namespace the queue with a key to isolate it for testing
695 * @param string $key
696 * @return void
697 * @throws MWException
699 public function setTestingPrefix( $key ) {
700 throw new MWException( "Queue namespacing not supported for this queue type." );
705 * @ingroup JobQueue
706 * @since 1.22
708 class JobQueueError extends MWException {
711 class JobQueueConnectionError extends JobQueueError {