Renamed /job to /jobqueue
[mediawiki.git] / includes / jobqueue / JobQueue.php
bloba537861f43802c94b7d511bd39e742ad6ff5ac23
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 wfProfileIn( __METHOD__ );
191 $res = $this->doIsEmpty();
192 wfProfileOut( __METHOD__ );
194 return $res;
198 * @see JobQueue::isEmpty()
199 * @return bool
201 abstract protected function doIsEmpty();
204 * Get the number of available (unacquired, non-delayed) jobs in the queue.
205 * Queue classes should use caching if they are any slower without memcached.
207 * If caching is used, this number might be out of date for a minute.
209 * @return int
210 * @throws JobQueueError
212 final public function getSize() {
213 wfProfileIn( __METHOD__ );
214 $res = $this->doGetSize();
215 wfProfileOut( __METHOD__ );
217 return $res;
221 * @see JobQueue::getSize()
222 * @return int
224 abstract protected function doGetSize();
227 * Get the number of acquired jobs (these are temporarily out of the queue).
228 * Queue classes should use caching if they are any slower without memcached.
230 * If caching is used, this number might be out of date for a minute.
232 * @return int
233 * @throws JobQueueError
235 final public function getAcquiredCount() {
236 wfProfileIn( __METHOD__ );
237 $res = $this->doGetAcquiredCount();
238 wfProfileOut( __METHOD__ );
240 return $res;
244 * @see JobQueue::getAcquiredCount()
245 * @return int
247 abstract protected function doGetAcquiredCount();
250 * Get the number of delayed jobs (these are temporarily out of the queue).
251 * Queue classes should use caching if they are any slower without memcached.
253 * If caching is used, this number might be out of date for a minute.
255 * @return int
256 * @throws JobQueueError
257 * @since 1.22
259 final public function getDelayedCount() {
260 wfProfileIn( __METHOD__ );
261 $res = $this->doGetDelayedCount();
262 wfProfileOut( __METHOD__ );
264 return $res;
268 * @see JobQueue::getDelayedCount()
269 * @return int
271 protected function doGetDelayedCount() {
272 return 0; // not implemented
276 * Get the number of acquired jobs that can no longer be attempted.
277 * Queue classes should use caching if they are any slower without memcached.
279 * If caching is used, this number might be out of date for a minute.
281 * @return int
282 * @throws JobQueueError
284 final public function getAbandonedCount() {
285 wfProfileIn( __METHOD__ );
286 $res = $this->doGetAbandonedCount();
287 wfProfileOut( __METHOD__ );
289 return $res;
293 * @see JobQueue::getAbandonedCount()
294 * @return int
296 protected function doGetAbandonedCount() {
297 return 0; // not implemented
301 * Push one or more jobs into the queue.
302 * This does not require $wgJobClasses to be set for the given job type.
303 * Outside callers should use JobQueueGroup::push() instead of this function.
305 * @param Job|array $jobs A single job or an array of Jobs
306 * @param int $flags Bitfield (supports JobQueue::QOS_ATOMIC)
307 * @return bool Returns false on failure
308 * @throws JobQueueError
310 final public function push( $jobs, $flags = 0 ) {
311 return $this->batchPush( is_array( $jobs ) ? $jobs : array( $jobs ), $flags );
315 * Push a batch of jobs into the queue.
316 * This does not require $wgJobClasses to be set for the given job type.
317 * Outside callers should use JobQueueGroup::push() instead of this function.
319 * @param array $jobs List of Jobs
320 * @param int $flags Bitfield (supports JobQueue::QOS_ATOMIC)
321 * @throws MWException
322 * @return bool Returns false on failure
324 final public function batchPush( array $jobs, $flags = 0 ) {
325 if ( !count( $jobs ) ) {
326 return true; // nothing to do
329 foreach ( $jobs as $job ) {
330 if ( $job->getType() !== $this->type ) {
331 throw new MWException(
332 "Got '{$job->getType()}' job; expected a '{$this->type}' job." );
333 } elseif ( $job->getReleaseTimestamp() && !$this->checkDelay ) {
334 throw new MWException(
335 "Got delayed '{$job->getType()}' job; delays are not supported." );
339 wfProfileIn( __METHOD__ );
340 $ok = $this->doBatchPush( $jobs, $flags );
341 wfProfileOut( __METHOD__ );
343 return $ok;
347 * @see JobQueue::batchPush()
348 * @param array $jobs
349 * @param $flags
350 * @return bool
352 abstract protected function doBatchPush( array $jobs, $flags );
355 * Pop a job off of the queue.
356 * This requires $wgJobClasses to be set for the given job type.
357 * Outside callers should use JobQueueGroup::pop() instead of this function.
359 * @throws MWException
360 * @return Job|bool Returns false if there are no jobs
362 final public function pop() {
363 global $wgJobClasses;
365 if ( $this->wiki !== wfWikiID() ) {
366 throw new MWException( "Cannot pop '{$this->type}' job off foreign wiki queue." );
367 } elseif ( !isset( $wgJobClasses[$this->type] ) ) {
368 // Do not pop jobs if there is no class for the queue type
369 throw new MWException( "Unrecognized job type '{$this->type}'." );
372 wfProfileIn( __METHOD__ );
373 $job = $this->doPop();
374 wfProfileOut( __METHOD__ );
376 // Flag this job as an old duplicate based on its "root" job...
377 try {
378 if ( $job && $this->isRootJobOldDuplicate( $job ) ) {
379 JobQueue::incrStats( 'job-pop-duplicate', $this->type );
380 $job = DuplicateJob::newFromJob( $job ); // convert to a no-op
382 } catch ( MWException $e ) {
383 // don't lose jobs over this
386 return $job;
390 * @see JobQueue::pop()
391 * @return Job
393 abstract protected function doPop();
396 * Acknowledge that a job was completed.
398 * This does nothing for certain queue classes or if "claimTTL" is not set.
399 * Outside callers should use JobQueueGroup::ack() instead of this function.
401 * @param Job $job
402 * @throws MWException
403 * @return bool
405 final public function ack( Job $job ) {
406 if ( $job->getType() !== $this->type ) {
407 throw new MWException( "Got '{$job->getType()}' job; expected '{$this->type}'." );
409 wfProfileIn( __METHOD__ );
410 $ok = $this->doAck( $job );
411 wfProfileOut( __METHOD__ );
413 return $ok;
417 * @see JobQueue::ack()
418 * @param Job $job
419 * @return bool
421 abstract protected function doAck( Job $job );
424 * Register the "root job" of a given job into the queue for de-duplication.
425 * This should only be called right *after* all the new jobs have been inserted.
426 * This is used to turn older, duplicate, job entries into no-ops. The root job
427 * information will remain in the registry until it simply falls out of cache.
429 * This requires that $job has two special fields in the "params" array:
430 * - rootJobSignature : hash (e.g. SHA1) that identifies the task
431 * - rootJobTimestamp : TS_MW timestamp of this instance of the task
433 * A "root job" is a conceptual job that consist of potentially many smaller jobs
434 * that are actually inserted into the queue. For example, "refreshLinks" jobs are
435 * spawned when a template is edited. One can think of the task as "update links
436 * of pages that use template X" and an instance of that task as a "root job".
437 * However, what actually goes into the queue are range and leaf job subtypes.
438 * Since these jobs include things like page ID ranges and DB master positions,
439 * and can morph into smaller jobs recursively, simple duplicate detection
440 * for individual jobs being identical (like that of job_sha1) is not useful.
442 * In the case of "refreshLinks", if these jobs are still in the queue when the template
443 * is edited again, we want all of these old refreshLinks jobs for that template to become
444 * no-ops. This can greatly reduce server load, since refreshLinks jobs involves parsing.
445 * Essentially, the new batch of jobs belong to a new "root job" and the older ones to a
446 * previous "root job" for the same task of "update links of pages that use template X".
448 * This does nothing for certain queue classes.
450 * @param Job $job
451 * @throws MWException
452 * @return bool
454 final public function deduplicateRootJob( Job $job ) {
455 if ( $job->getType() !== $this->type ) {
456 throw new MWException( "Got '{$job->getType()}' job; expected '{$this->type}'." );
458 wfProfileIn( __METHOD__ );
459 $ok = $this->doDeduplicateRootJob( $job );
460 wfProfileOut( __METHOD__ );
462 return $ok;
466 * @see JobQueue::deduplicateRootJob()
467 * @param Job $job
468 * @throws MWException
469 * @return bool
471 protected function doDeduplicateRootJob( Job $job ) {
472 if ( !$job->hasRootJobParams() ) {
473 throw new MWException( "Cannot register root job; missing parameters." );
475 $params = $job->getRootJobParams();
477 $key = $this->getRootJobCacheKey( $params['rootJobSignature'] );
478 // Callers should call batchInsert() and then this function so that if the insert
479 // fails, the de-duplication registration will be aborted. Since the insert is
480 // deferred till "transaction idle", do the same here, so that the ordering is
481 // maintained. Having only the de-duplication registration succeed would cause
482 // jobs to become no-ops without any actual jobs that made them redundant.
483 $timestamp = $this->dupCache->get( $key ); // current last timestamp of this job
484 if ( $timestamp && $timestamp >= $params['rootJobTimestamp'] ) {
485 return true; // a newer version of this root job was enqueued
488 // Update the timestamp of the last root job started at the location...
489 return $this->dupCache->set( $key, $params['rootJobTimestamp'], JobQueueDB::ROOTJOB_TTL );
493 * Check if the "root" job of a given job has been superseded by a newer one
495 * @param Job $job
496 * @throws MWException
497 * @return bool
499 final protected function isRootJobOldDuplicate( Job $job ) {
500 if ( $job->getType() !== $this->type ) {
501 throw new MWException( "Got '{$job->getType()}' job; expected '{$this->type}'." );
503 wfProfileIn( __METHOD__ );
504 $isDuplicate = $this->doIsRootJobOldDuplicate( $job );
505 wfProfileOut( __METHOD__ );
507 return $isDuplicate;
511 * @see JobQueue::isRootJobOldDuplicate()
512 * @param Job $job
513 * @return bool
515 protected function doIsRootJobOldDuplicate( Job $job ) {
516 if ( !$job->hasRootJobParams() ) {
517 return false; // job has no de-deplication info
519 $params = $job->getRootJobParams();
521 $key = $this->getRootJobCacheKey( $params['rootJobSignature'] );
522 // Get the last time this root job was enqueued
523 $timestamp = $this->dupCache->get( $key );
525 // Check if a new root job was started at the location after this one's...
526 return ( $timestamp && $timestamp > $params['rootJobTimestamp'] );
530 * @param string $signature Hash identifier of the root job
531 * @return string
533 protected function getRootJobCacheKey( $signature ) {
534 list( $db, $prefix ) = wfSplitWikiID( $this->wiki );
536 return wfForeignMemcKey( $db, $prefix, 'jobqueue', $this->type, 'rootjob', $signature );
540 * Deleted all unclaimed and delayed jobs from the queue
542 * @return bool Success
543 * @throws JobQueueError
544 * @since 1.22
546 final public function delete() {
547 wfProfileIn( __METHOD__ );
548 $res = $this->doDelete();
549 wfProfileOut( __METHOD__ );
551 return $res;
555 * @see JobQueue::delete()
556 * @throws MWException
557 * @return bool Success
559 protected function doDelete() {
560 throw new MWException( "This method is not implemented." );
564 * Wait for any slaves or backup servers to catch up.
566 * This does nothing for certain queue classes.
568 * @return void
569 * @throws JobQueueError
571 final public function waitForBackups() {
572 wfProfileIn( __METHOD__ );
573 $this->doWaitForBackups();
574 wfProfileOut( __METHOD__ );
578 * @see JobQueue::waitForBackups()
579 * @return void
581 protected function doWaitForBackups() {
585 * Return a map of task names to task definition maps.
586 * A "task" is a fast periodic queue maintenance action.
587 * Mutually exclusive tasks must implement their own locking in the callback.
589 * Each task value is an associative array with:
590 * - name : the name of the task
591 * - callback : a PHP callable that performs the task
592 * - period : the period in seconds corresponding to the task frequency
594 * @return array
596 final public function getPeriodicTasks() {
597 $tasks = $this->doGetPeriodicTasks();
598 foreach ( $tasks as $name => &$def ) {
599 $def['name'] = $name;
602 return $tasks;
606 * @see JobQueue::getPeriodicTasks()
607 * @return array
609 protected function doGetPeriodicTasks() {
610 return array();
614 * Clear any process and persistent caches
616 * @return void
618 final public function flushCaches() {
619 wfProfileIn( __METHOD__ );
620 $this->doFlushCaches();
621 wfProfileOut( __METHOD__ );
625 * @see JobQueue::flushCaches()
626 * @return void
628 protected function doFlushCaches() {
632 * Get an iterator to traverse over all available jobs in this queue.
633 * This does not include jobs that are currently acquired or delayed.
634 * Note: results may be stale if the queue is concurrently modified.
636 * @return Iterator
637 * @throws JobQueueError
639 abstract public function getAllQueuedJobs();
642 * Get an iterator to traverse over all delayed jobs in this queue.
643 * Note: results may be stale if the queue is concurrently modified.
645 * @return Iterator
646 * @throws JobQueueError
647 * @since 1.22
649 public function getAllDelayedJobs() {
650 return new ArrayIterator( array() ); // not implemented
654 * Do not use this function outside of JobQueue/JobQueueGroup
656 * @return string
657 * @since 1.22
659 public function getCoalesceLocationInternal() {
660 return null;
664 * Check whether each of the given queues are empty.
665 * This is used for batching checks for queues stored at the same place.
667 * @param array $types List of queues types
668 * @return array|null (list of non-empty queue types) or null if unsupported
669 * @throws MWException
670 * @since 1.22
672 final public function getSiblingQueuesWithJobs( array $types ) {
673 $section = new ProfileSection( __METHOD__ );
675 return $this->doGetSiblingQueuesWithJobs( $types );
679 * @see JobQueue::getSiblingQueuesWithJobs()
680 * @param array $types List of queues types
681 * @return array|null (list of queue types) or null if unsupported
683 protected function doGetSiblingQueuesWithJobs( array $types ) {
684 return null; // not supported
688 * Check the size of each of the given queues.
689 * For queues not served by the same store as this one, 0 is returned.
690 * This is used for batching checks for queues stored at the same place.
692 * @param array $types List of queues types
693 * @return array|null (job type => whether queue is empty) or null if unsupported
694 * @throws MWException
695 * @since 1.22
697 final public function getSiblingQueueSizes( array $types ) {
698 $section = new ProfileSection( __METHOD__ );
700 return $this->doGetSiblingQueueSizes( $types );
704 * @see JobQueue::getSiblingQueuesSize()
705 * @param array $types List of queues types
706 * @return array|null (list of queue types) or null if unsupported
708 protected function doGetSiblingQueueSizes( array $types ) {
709 return null; // not supported
713 * Call wfIncrStats() for the queue overall and for the queue type
715 * @param string $key Event type
716 * @param string $type Job type
717 * @param int $delta
718 * @since 1.22
720 public static function incrStats( $key, $type, $delta = 1 ) {
721 wfIncrStats( $key, $delta );
722 wfIncrStats( "{$key}-{$type}", $delta );
726 * Namespace the queue with a key to isolate it for testing
728 * @param string $key
729 * @return void
730 * @throws MWException
732 public function setTestingPrefix( $key ) {
733 throw new MWException( "Queue namespacing not supported for this queue type." );
738 * @ingroup JobQueue
739 * @since 1.22
741 class JobQueueError extends MWException {
744 class JobQueueConnectionError extends JobQueueError {