Refactor diffs
[mediawiki.git] / includes / job / JobQueue.php
blob6556ee85c7e2de3f5e99af340a295e8836cbf24e
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 /** @var BagOStuff */
40 protected $dupCache;
42 const QOS_ATOMIC = 1; // integer; "all-or-nothing" job insertions
44 const ROOTJOB_TTL = 2419200; // integer; seconds to remember root jobs (28 days)
46 /**
47 * @param $params array
49 protected function __construct( array $params ) {
50 $this->wiki = $params['wiki'];
51 $this->type = $params['type'];
52 $this->claimTTL = isset( $params['claimTTL'] ) ? $params['claimTTL'] : 0;
53 $this->maxTries = isset( $params['maxTries'] ) ? $params['maxTries'] : 3;
54 if ( isset( $params['order'] ) && $params['order'] !== 'any' ) {
55 $this->order = $params['order'];
56 } else {
57 $this->order = $this->optimalOrder();
59 if ( !in_array( $this->order, $this->supportedOrders() ) ) {
60 throw new MWException( __CLASS__ . " does not support '{$this->order}' order." );
62 $this->checkDelay = !empty( $params['checkDelay'] );
63 if ( $this->checkDelay && !$this->supportsDelayedJobs() ) {
64 throw new MWException( __CLASS__ . " does not support delayed jobs." );
66 $this->dupCache = wfGetCache( CACHE_ANYTHING );
69 /**
70 * Get a job queue object of the specified type.
71 * $params includes:
72 * - class : What job class to use (determines job type)
73 * - wiki : wiki ID of the wiki the jobs are for (defaults to current wiki)
74 * - type : The name of the job types this queue handles
75 * - order : Order that pop() selects jobs, one of "fifo", "timestamp" or "random".
76 * If "fifo" is used, the queue will effectively be FIFO. Note that job
77 * completion will not appear to be exactly FIFO if there are multiple
78 * job runners since jobs can take different times to finish once popped.
79 * If "timestamp" is used, the queue will at least be loosely ordered
80 * by timestamp, allowing for some jobs to be popped off out of order.
81 * If "random" is used, pop() will pick jobs in random order.
82 * Note that it may only be weakly random (e.g. a lottery of the oldest X).
83 * If "any" is choosen, the queue will use whatever order is the fastest.
84 * This might be useful for improving concurrency for job acquisition.
85 * - claimTTL : If supported, the queue will recycle jobs that have been popped
86 * but not acknowledged as completed after this many seconds. Recycling
87 * of jobs simple means re-inserting them into the queue. Jobs can be
88 * attempted up to three times before being discarded.
89 * - checkDelay : If supported, respect Job::getReleaseTimestamp() in the push functions.
90 * This lets delayed jobs wait in a staging area until a given timestamp is
91 * reached, at which point they will enter the queue. If this is not enabled
92 * or not supported, an exception will be thrown on delayed job insertion.
94 * Queue classes should throw an exception if they do not support the options given.
96 * @param $params array
97 * @return JobQueue
98 * @throws MWException
100 final public static function factory( array $params ) {
101 $class = $params['class'];
102 if ( !class_exists( $class ) ) {
103 throw new MWException( "Invalid job queue class '$class'." );
105 $obj = new $class( $params );
106 if ( !( $obj instanceof self ) ) {
107 throw new MWException( "Class '$class' is not a " . __CLASS__ . " class." );
109 return $obj;
113 * @return string Wiki ID
115 final public function getWiki() {
116 return $this->wiki;
120 * @return string Job type that this queue handles
122 final public function getType() {
123 return $this->type;
127 * @return string One of (random, timestamp, fifo, undefined)
129 final public function getOrder() {
130 return $this->order;
134 * @return bool Whether delayed jobs are enabled
135 * @since 1.22
137 final public function delayedJobsEnabled() {
138 return $this->checkDelay;
142 * Get the allowed queue orders for configuration validation
144 * @return Array Subset of (random, timestamp, fifo, undefined)
146 abstract protected function supportedOrders();
149 * Get the default queue order to use if configuration does not specify one
151 * @return string One of (random, timestamp, fifo, undefined)
153 abstract protected function optimalOrder();
156 * Find out if delayed jobs are supported for configuration validation
158 * @return boolean Whether delayed jobs are supported
160 protected function supportsDelayedJobs() {
161 return false; // not implemented
165 * Quickly check if the queue has no available (unacquired, non-delayed) jobs.
166 * Queue classes should use caching if they are any slower without memcached.
168 * If caching is used, this might return false when there are actually no jobs.
169 * If pop() is called and returns false then it should correct the cache. Also,
170 * calling flushCaches() first prevents this. However, this affect is typically
171 * not distinguishable from the race condition between isEmpty() and pop().
173 * @return bool
174 * @throws JobQueueError
176 final public function isEmpty() {
177 wfProfileIn( __METHOD__ );
178 $res = $this->doIsEmpty();
179 wfProfileOut( __METHOD__ );
180 return $res;
184 * @see JobQueue::isEmpty()
185 * @return bool
187 abstract protected function doIsEmpty();
190 * Get the number of available (unacquired, non-delayed) jobs in the queue.
191 * Queue classes should use caching if they are any slower without memcached.
193 * If caching is used, this number might be out of date for a minute.
195 * @return integer
196 * @throws JobQueueError
198 final public function getSize() {
199 wfProfileIn( __METHOD__ );
200 $res = $this->doGetSize();
201 wfProfileOut( __METHOD__ );
202 return $res;
206 * @see JobQueue::getSize()
207 * @return integer
209 abstract protected function doGetSize();
212 * Get the number of acquired jobs (these are temporarily out of the queue).
213 * Queue classes should use caching if they are any slower without memcached.
215 * If caching is used, this number might be out of date for a minute.
217 * @return integer
218 * @throws JobQueueError
220 final public function getAcquiredCount() {
221 wfProfileIn( __METHOD__ );
222 $res = $this->doGetAcquiredCount();
223 wfProfileOut( __METHOD__ );
224 return $res;
228 * @see JobQueue::getAcquiredCount()
229 * @return integer
231 abstract protected function doGetAcquiredCount();
234 * Get the number of delayed jobs (these are temporarily out of the queue).
235 * Queue classes should use caching if they are any slower without memcached.
237 * If caching is used, this number might be out of date for a minute.
239 * @return integer
240 * @throws JobQueueError
241 * @since 1.22
243 final public function getDelayedCount() {
244 wfProfileIn( __METHOD__ );
245 $res = $this->doGetDelayedCount();
246 wfProfileOut( __METHOD__ );
247 return $res;
251 * @see JobQueue::getDelayedCount()
252 * @return integer
254 protected function doGetDelayedCount() {
255 return 0; // not implemented
259 * Get the number of acquired jobs that can no longer be attempted.
260 * Queue classes should use caching if they are any slower without memcached.
262 * If caching is used, this number might be out of date for a minute.
264 * @return integer
265 * @throws JobQueueError
267 final public function getAbandonedCount() {
268 wfProfileIn( __METHOD__ );
269 $res = $this->doGetAbandonedCount();
270 wfProfileOut( __METHOD__ );
271 return $res;
275 * @see JobQueue::getAbandonedCount()
276 * @return integer
278 protected function doGetAbandonedCount() {
279 return 0; // not implemented
283 * Push a single jobs into the queue.
284 * This does not require $wgJobClasses to be set for the given job type.
285 * Outside callers should use JobQueueGroup::push() instead of this function.
287 * @param $jobs Job|Array
288 * @param $flags integer Bitfield (supports JobQueue::QOS_ATOMIC)
289 * @return bool Returns false on failure
290 * @throws JobQueueError
292 final public function push( $jobs, $flags = 0 ) {
293 return $this->batchPush( is_array( $jobs ) ? $jobs : array( $jobs ), $flags );
297 * Push a batch of jobs into the queue.
298 * This does not require $wgJobClasses to be set for the given job type.
299 * Outside callers should use JobQueueGroup::push() instead of this function.
301 * @param array $jobs List of Jobs
302 * @param $flags integer Bitfield (supports JobQueue::QOS_ATOMIC)
303 * @return bool Returns false on failure
304 * @throws JobQueueError
306 final public function batchPush( array $jobs, $flags = 0 ) {
307 if ( !count( $jobs ) ) {
308 return true; // nothing to do
311 foreach ( $jobs as $job ) {
312 if ( $job->getType() !== $this->type ) {
313 throw new MWException(
314 "Got '{$job->getType()}' job; expected a '{$this->type}' job." );
315 } elseif ( $job->getReleaseTimestamp() && !$this->checkDelay ) {
316 throw new MWException(
317 "Got delayed '{$job->getType()}' job; delays are not supported." );
321 wfProfileIn( __METHOD__ );
322 $ok = $this->doBatchPush( $jobs, $flags );
323 wfProfileOut( __METHOD__ );
324 return $ok;
328 * @see JobQueue::batchPush()
329 * @return bool
331 abstract protected function doBatchPush( array $jobs, $flags );
334 * Pop a job off of the queue.
335 * This requires $wgJobClasses to be set for the given job type.
336 * Outside callers should use JobQueueGroup::pop() instead of this function.
338 * @return Job|bool Returns false if there are no jobs
339 * @throws JobQueueError
341 final public function pop() {
342 global $wgJobClasses;
344 if ( $this->wiki !== wfWikiID() ) {
345 throw new MWException( "Cannot pop '{$this->type}' job off foreign wiki queue." );
346 } elseif ( !isset( $wgJobClasses[$this->type] ) ) {
347 // Do not pop jobs if there is no class for the queue type
348 throw new MWException( "Unrecognized job type '{$this->type}'." );
351 wfProfileIn( __METHOD__ );
352 $job = $this->doPop();
353 wfProfileOut( __METHOD__ );
355 // Flag this job as an old duplicate based on its "root" job...
356 try {
357 if ( $job && $this->isRootJobOldDuplicate( $job ) ) {
358 JobQueue::incrStats( 'job-pop-duplicate', $this->type );
359 $job = DuplicateJob::newFromJob( $job ); // convert to a no-op
361 } catch ( MWException $e ) {} // don't lose jobs over this
363 return $job;
367 * @see JobQueue::pop()
368 * @return Job
370 abstract protected function doPop();
373 * Acknowledge that a job was completed.
375 * This does nothing for certain queue classes or if "claimTTL" is not set.
376 * Outside callers should use JobQueueGroup::ack() instead of this function.
378 * @param $job Job
379 * @return bool
380 * @throws JobQueueError
382 final public function ack( Job $job ) {
383 if ( $job->getType() !== $this->type ) {
384 throw new MWException( "Got '{$job->getType()}' job; expected '{$this->type}'." );
386 wfProfileIn( __METHOD__ );
387 $ok = $this->doAck( $job );
388 wfProfileOut( __METHOD__ );
389 return $ok;
393 * @see JobQueue::ack()
394 * @return bool
396 abstract protected function doAck( Job $job );
399 * Register the "root job" of a given job into the queue for de-duplication.
400 * This should only be called right *after* all the new jobs have been inserted.
401 * This is used to turn older, duplicate, job entries into no-ops. The root job
402 * information will remain in the registry until it simply falls out of cache.
404 * This requires that $job has two special fields in the "params" array:
405 * - rootJobSignature : hash (e.g. SHA1) that identifies the task
406 * - rootJobTimestamp : TS_MW timestamp of this instance of the task
408 * A "root job" is a conceptual job that consist of potentially many smaller jobs
409 * that are actually inserted into the queue. For example, "refreshLinks" jobs are
410 * spawned when a template is edited. One can think of the task as "update links
411 * of pages that use template X" and an instance of that task as a "root job".
412 * However, what actually goes into the queue are potentially many refreshLinks2 jobs.
413 * Since these jobs include things like page ID ranges and DB master positions, and morph
414 * into smaller refreshLinks2 jobs recursively, simple duplicate detection (like job_sha1)
415 * for individual jobs being identical is not useful.
417 * In the case of "refreshLinks", if these jobs are still in the queue when the template
418 * is edited again, we want all of these old refreshLinks jobs for that template to become
419 * no-ops. This can greatly reduce server load, since refreshLinks jobs involves parsing.
420 * Essentially, the new batch of jobs belong to a new "root job" and the older ones to a
421 * previous "root job" for the same task of "update links of pages that use template X".
423 * This does nothing for certain queue classes.
425 * @param $job Job
426 * @return bool
427 * @throws JobQueueError
429 final public function deduplicateRootJob( Job $job ) {
430 if ( $job->getType() !== $this->type ) {
431 throw new MWException( "Got '{$job->getType()}' job; expected '{$this->type}'." );
433 wfProfileIn( __METHOD__ );
434 $ok = $this->doDeduplicateRootJob( $job );
435 wfProfileOut( __METHOD__ );
436 return $ok;
440 * @see JobQueue::deduplicateRootJob()
441 * @param $job Job
442 * @return bool
444 protected function doDeduplicateRootJob( Job $job ) {
445 if ( !$job->hasRootJobParams() ) {
446 throw new MWException( "Cannot register root job; missing parameters." );
448 $params = $job->getRootJobParams();
450 $key = $this->getRootJobCacheKey( $params['rootJobSignature'] );
451 // Callers should call batchInsert() and then this function so that if the insert
452 // fails, the de-duplication registration will be aborted. Since the insert is
453 // deferred till "transaction idle", do the same here, so that the ordering is
454 // maintained. Having only the de-duplication registration succeed would cause
455 // jobs to become no-ops without any actual jobs that made them redundant.
456 $timestamp = $this->dupCache->get( $key ); // current last timestamp of this job
457 if ( $timestamp && $timestamp >= $params['rootJobTimestamp'] ) {
458 return true; // a newer version of this root job was enqueued
461 // Update the timestamp of the last root job started at the location...
462 return $this->dupCache->set( $key, $params['rootJobTimestamp'], JobQueueDB::ROOTJOB_TTL );
466 * Check if the "root" job of a given job has been superseded by a newer one
468 * @param $job Job
469 * @return bool
470 * @throws JobQueueError
472 final protected function isRootJobOldDuplicate( Job $job ) {
473 if ( $job->getType() !== $this->type ) {
474 throw new MWException( "Got '{$job->getType()}' job; expected '{$this->type}'." );
476 wfProfileIn( __METHOD__ );
477 $isDuplicate = $this->doIsRootJobOldDuplicate( $job );
478 wfProfileOut( __METHOD__ );
479 return $isDuplicate;
483 * @see JobQueue::isRootJobOldDuplicate()
484 * @param Job $job
485 * @return bool
487 protected function doIsRootJobOldDuplicate( Job $job ) {
488 if ( !$job->hasRootJobParams() ) {
489 return false; // job has no de-deplication info
491 $params = $job->getRootJobParams();
493 $key = $this->getRootJobCacheKey( $params['rootJobSignature'] );
494 // Get the last time this root job was enqueued
495 $timestamp = $this->dupCache->get( $key );
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 JobQueueError
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 JobQueueError
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 JobQueueError
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 JobQueueError
613 * @since 1.22
615 public function getAllDelayedJobs() {
616 return new ArrayIterator( array() ); // not implemented
620 * Do not use this function outside of JobQueue/JobQueueGroup
622 * @return string
623 * @since 1.22
625 public function getCoalesceLocationInternal() {
626 return null;
630 * Check whether each of the given queues are empty.
631 * This is used for batching checks for queues stored at the same place.
633 * @param array $types List of queues types
634 * @return array|null (list of non-empty queue types) or null if unsupported
635 * @throws MWException
636 * @since 1.22
638 final public function getSiblingQueuesWithJobs( array $types ) {
639 $section = new ProfileSection( __METHOD__ );
640 return $this->doGetSiblingQueuesWithJobs( $types );
644 * @see JobQueue::getSiblingQueuesWithJobs()
645 * @param array $types List of queues types
646 * @return array|null (list of queue types) or null if unsupported
648 protected function doGetSiblingQueuesWithJobs( array $types ) {
649 return null; // not supported
653 * Check the size of each of the given queues.
654 * For queues not served by the same store as this one, 0 is returned.
655 * This is used for batching checks for queues stored at the same place.
657 * @param array $types List of queues types
658 * @return array|null (job type => whether queue is empty) or null if unsupported
659 * @throws MWException
660 * @since 1.22
662 final public function getSiblingQueueSizes( array $types ) {
663 $section = new ProfileSection( __METHOD__ );
664 return $this->doGetSiblingQueueSizes( $types );
668 * @see JobQueue::getSiblingQueuesSize()
669 * @param array $types List of queues types
670 * @return array|null (list of queue types) or null if unsupported
672 protected function doGetSiblingQueueSizes( array $types ) {
673 return null; // not supported
677 * Call wfIncrStats() for the queue overall and for the queue type
679 * @param string $key Event type
680 * @param string $type Job type
681 * @param integer $delta
682 * @since 1.22
684 public static function incrStats( $key, $type, $delta = 1 ) {
685 wfIncrStats( $key, $delta );
686 wfIncrStats( "{$key}-{$type}", $delta );
690 * Namespace the queue with a key to isolate it for testing
692 * @param $key string
693 * @return void
694 * @throws MWException
696 public function setTestingPrefix( $key ) {
697 throw new MWException( "Queue namespacing not supported for this queue type." );
702 * @ingroup JobQueue
703 * @since 1.22
705 class JobQueueError extends MWException {}
706 class JobQueueConnectionError extends JobQueueError {}