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 * @author Aaron Schulz
25 * Class to handle enqueueing of background jobs
32 protected static $instances = array();
34 /** @var ProcessCacheLRU */
37 protected $wiki; // string; wiki ID
39 /** @var array Map of (bucket => (queue => JobQueue, types => list of types) */
40 protected $coalescedQueues;
42 const TYPE_DEFAULT
= 1; // integer; jobs popped by default
43 const TYPE_ANY
= 2; // integer; any job
45 const USE_CACHE
= 1; // integer; use process or persistent cache
46 const USE_PRIORITY
= 2; // integer; respect deprioritization
48 const PROC_CACHE_TTL
= 15; // integer; seconds
50 const CACHE_VERSION
= 1; // integer; cache version
53 * @param string $wiki Wiki ID
55 protected function __construct( $wiki ) {
57 $this->cache
= new ProcessCacheLRU( 10 );
61 * @param string $wiki Wiki ID
62 * @return JobQueueGroup
64 public static function singleton( $wiki = false ) {
65 $wiki = ( $wiki === false ) ?
wfWikiID() : $wiki;
66 if ( !isset( self
::$instances[$wiki] ) ) {
67 self
::$instances[$wiki] = new self( $wiki );
69 return self
::$instances[$wiki];
73 * Destroy the singleton instances
77 public static function destroySingletons() {
78 self
::$instances = array();
82 * Get the job queue object for a given queue type
87 public function get( $type ) {
88 global $wgJobTypeConf;
90 $conf = array( 'wiki' => $this->wiki
, 'type' => $type );
91 if ( isset( $wgJobTypeConf[$type] ) ) {
92 $conf = $conf +
$wgJobTypeConf[$type];
94 $conf = $conf +
$wgJobTypeConf['default'];
97 return JobQueue
::factory( $conf );
101 * Insert jobs into the respective queues of with the belong.
103 * This inserts the jobs into the queue specified by $wgJobTypeConf
104 * and updates the aggregate job queue information cache as needed.
106 * @param $jobs Job|array A single Job or a list of Jobs
107 * @throws MWException
110 public function push( $jobs ) {
111 $jobs = is_array( $jobs ) ?
$jobs : array( $jobs );
113 $jobsByType = array(); // (job type => list of jobs)
114 foreach ( $jobs as $job ) {
115 if ( $job instanceof Job
) {
116 $jobsByType[$job->getType()][] = $job;
118 throw new MWException( "Attempted to push a non-Job object into a queue." );
123 foreach ( $jobsByType as $type => $jobs ) {
124 if ( $this->get( $type )->push( $jobs ) ) {
125 JobQueueAggregator
::singleton()->notifyQueueNonEmpty( $this->wiki
, $type );
131 if ( $this->cache
->has( 'queues-ready', 'list' ) ) {
132 $list = $this->cache
->get( 'queues-ready', 'list' );
133 if ( count( array_diff( array_keys( $jobsByType ), $list ) ) ) {
134 $this->cache
->clear( 'queues-ready' );
142 * Pop a job off one of the job queues
144 * This pops a job off a queue as specified by $wgJobTypeConf and
145 * updates the aggregate job queue information cache as needed.
147 * @param $qtype integer|string JobQueueGroup::TYPE_DEFAULT or type string
148 * @param $flags integer Bitfield of JobQueueGroup::USE_* constants
149 * @return Job|bool Returns false on failure
151 public function pop( $qtype = self
::TYPE_DEFAULT
, $flags = 0 ) {
152 if ( is_string( $qtype ) ) { // specific job type
153 if ( ( $flags & self
::USE_PRIORITY
) && $this->isQueueDeprioritized( $qtype ) ) {
154 return false; // back off
156 $job = $this->get( $qtype )->pop();
158 JobQueueAggregator
::singleton()->notifyQueueEmpty( $this->wiki
, $qtype );
161 } else { // any job in the "default" jobs types
162 if ( $flags & self
::USE_CACHE
) {
163 if ( !$this->cache
->has( 'queues-ready', 'list', self
::PROC_CACHE_TTL
) ) {
164 $this->cache
->set( 'queues-ready', 'list', $this->getQueuesWithJobs() );
166 $types = $this->cache
->get( 'queues-ready', 'list' );
168 $types = $this->getQueuesWithJobs();
171 if ( $qtype == self
::TYPE_DEFAULT
) {
172 $types = array_intersect( $types, $this->getDefaultQueueTypes() );
174 shuffle( $types ); // avoid starvation
176 foreach ( $types as $type ) { // for each queue...
177 if ( ( $flags & self
::USE_PRIORITY
) && $this->isQueueDeprioritized( $type ) ) {
178 continue; // back off
180 $job = $this->get( $type )->pop();
181 if ( $job ) { // found
183 } else { // not found
184 JobQueueAggregator
::singleton()->notifyQueueEmpty( $this->wiki
, $type );
185 $this->cache
->clear( 'queues-ready' );
189 return false; // no jobs found
194 * Acknowledge that a job was completed
199 public function ack( Job
$job ) {
200 return $this->get( $job->getType() )->ack( $job );
204 * Register the "root job" of a given job into the queue for de-duplication.
205 * This should only be called right *after* all the new jobs have been inserted.
210 public function deduplicateRootJob( Job
$job ) {
211 return $this->get( $job->getType() )->deduplicateRootJob( $job );
215 * Wait for any slaves or backup queue servers to catch up.
217 * This does nothing for certain queue classes.
220 * @throws MWException
222 public function waitForBackups() {
223 global $wgJobTypeConf;
225 wfProfileIn( __METHOD__
);
226 // Try to avoid doing this more than once per queue storage medium
227 foreach ( $wgJobTypeConf as $type => $conf ) {
228 $this->get( $type )->waitForBackups();
230 wfProfileOut( __METHOD__
);
234 * Get the list of queue types
236 * @return array List of strings
238 public function getQueueTypes() {
239 return array_keys( $this->getCachedConfigVar( 'wgJobClasses' ) );
243 * Get the list of default queue types
245 * @return array List of strings
247 public function getDefaultQueueTypes() {
248 global $wgJobTypesExcludedFromDefaultQueue;
250 return array_diff( $this->getQueueTypes(), $wgJobTypesExcludedFromDefaultQueue );
254 * Get the list of job types that have non-empty queues
256 * @return Array List of job types that have non-empty queues
258 public function getQueuesWithJobs() {
260 foreach ( $this->getCoalescedQueues() as $info ) {
261 $nonEmpty = $info['queue']->getSiblingQueuesWithJobs( $this->getQueueTypes() );
262 if ( is_array( $nonEmpty ) ) { // batching features supported
263 $types = array_merge( $types, $nonEmpty );
264 } else { // we have to go through the queues in the bucket one-by-one
265 foreach ( $info['types'] as $type ) {
266 if ( !$this->get( $type )->isEmpty() ) {
276 * Get the size of the queus for a list of job types
278 * @return Array Map of (job type => size)
280 public function getQueueSizes() {
282 foreach ( $this->getCoalescedQueues() as $info ) {
283 $sizes = $info['queue']->getSiblingQueueSizes( $this->getQueueTypes() );
284 if ( is_array( $sizes ) ) { // batching features supported
285 $sizeMap = $sizeMap +
$sizes;
286 } else { // we have to go through the queues in the bucket one-by-one
287 foreach ( $info['types'] as $type ) {
288 $sizeMap[$type] = $this->get( $type )->getSize();
298 protected function getCoalescedQueues() {
299 global $wgJobTypeConf;
301 if ( $this->coalescedQueues
=== null ) {
302 $this->coalescedQueues
= array();
303 foreach ( $wgJobTypeConf as $type => $conf ) {
304 $queue = JobQueue
::factory(
305 array( 'wiki' => $this->wiki
, 'type' => 'null' ) +
$conf );
306 $loc = $queue->getCoalesceLocationInternal();
307 if ( !isset( $this->coalescedQueues
[$loc] ) ) {
308 $this->coalescedQueues
[$loc]['queue'] = $queue;
309 $this->coalescedQueues
[$loc]['types'] = array();
311 if ( $type === 'default' ) {
312 $this->coalescedQueues
[$loc]['types'] = array_merge(
313 $this->coalescedQueues
[$loc]['types'],
314 array_diff( $this->getQueueTypes(), array_keys( $wgJobTypeConf ) )
317 $this->coalescedQueues
[$loc]['types'][] = $type;
322 return $this->coalescedQueues
;
326 * Check if jobs should not be popped of a queue right now.
327 * This is only used for performance, such as to avoid spamming
328 * the queue with many sub-jobs before they actually get run.
330 * @param $type string
333 public function isQueueDeprioritized( $type ) {
334 if ( $this->cache
->has( 'isDeprioritized', $type, 5 ) ) {
335 return $this->cache
->get( 'isDeprioritized', $type );
337 if ( $type === 'refreshLinks2' ) {
338 // Don't keep converting refreshLinks2 => refreshLinks jobs if the
339 // later jobs have not been done yet. This helps throttle queue spam.
340 $deprioritized = !$this->get( 'refreshLinks' )->isEmpty();
341 $this->cache
->set( 'isDeprioritized', $type, $deprioritized );
342 return $deprioritized;
348 * Execute any due periodic queue maintenance tasks for all queues.
350 * A task is "due" if the time ellapsed since the last run is greater than
351 * the defined run period. Concurrent calls to this function will cause tasks
352 * to be attempted twice, so they may need their own methods of mutual exclusion.
354 * @return integer Number of tasks run
356 public function executeReadyPeriodicTasks() {
359 list( $db, $prefix ) = wfSplitWikiID( $this->wiki
);
360 $key = wfForeignMemcKey( $db, $prefix, 'jobqueuegroup', 'taskruns', 'v1' );
361 $lastRuns = $wgMemc->get( $key ); // (queue => task => UNIX timestamp)
364 $tasksRun = array(); // (queue => task => UNIX timestamp)
365 foreach ( $this->getQueueTypes() as $type ) {
366 $queue = $this->get( $type );
367 foreach ( $queue->getPeriodicTasks() as $task => $definition ) {
368 if ( $definition['period'] <= 0 ) {
369 continue; // disabled
370 } elseif ( !isset( $lastRuns[$type][$task] )
371 ||
$lastRuns[$type][$task] < ( time() - $definition['period'] ) )
374 if ( call_user_func( $definition['callback'] ) !== null ) {
375 $tasksRun[$type][$task] = time();
378 } catch ( JobQueueError
$e ) {
379 wfDebugLog( 'exception', $e->getLogMessage() );
385 $wgMemc->merge( $key, function( $cache, $key, $lastRuns ) use ( $tasksRun ) {
386 if ( is_array( $lastRuns ) ) {
387 foreach ( $tasksRun as $type => $tasks ) {
388 foreach ( $tasks as $task => $timestamp ) {
389 if ( !isset( $lastRuns[$type][$task] )
390 ||
$timestamp > $lastRuns[$type][$task] )
392 $lastRuns[$type][$task] = $timestamp;
397 $lastRuns = $tasksRun;
406 * @param $name string
409 private function getCachedConfigVar( $name ) {
410 global $wgConf, $wgMemc;
412 if ( $this->wiki
=== wfWikiID() ) {
413 return $GLOBALS[$name]; // common case
415 list( $db, $prefix ) = wfSplitWikiID( $this->wiki
);
416 $key = wfForeignMemcKey( $db, $prefix, 'configvalue', $name );
417 $value = $wgMemc->get( $key ); // ('v' => ...) or false
418 if ( is_array( $value ) ) {
421 $value = $wgConf->getConfig( $this->wiki
, $name );
422 $wgMemc->set( $key, array( 'v' => $value ), 86400 +
mt_rand( 0, 86400 ) );