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 /** @var string Wiki ID */
40 /** @var array Map of (bucket => (queue => JobQueue, types => list of types) */
41 protected $coalescedQueues;
43 const TYPE_DEFAULT
= 1; // integer; jobs popped by default
44 const TYPE_ANY
= 2; // integer; any job
46 const USE_CACHE
= 1; // integer; use process or persistent cache
47 const USE_PRIORITY
= 2; // integer; respect deprioritization
49 const PROC_CACHE_TTL
= 15; // integer; seconds
51 const CACHE_VERSION
= 1; // integer; cache version
54 * @param string $wiki Wiki ID
56 protected function __construct( $wiki ) {
58 $this->cache
= new ProcessCacheLRU( 10 );
62 * @param bool|string $wiki Wiki ID
63 * @return JobQueueGroup
65 public static function singleton( $wiki = false ) {
66 $wiki = ( $wiki === false ) ?
wfWikiID() : $wiki;
67 if ( !isset( self
::$instances[$wiki] ) ) {
68 self
::$instances[$wiki] = new self( $wiki );
71 return self
::$instances[$wiki];
75 * Destroy the singleton instances
79 public static function destroySingletons() {
80 self
::$instances = array();
84 * Get the job queue object for a given queue type
89 public function get( $type ) {
90 global $wgJobTypeConf;
92 $conf = array( 'wiki' => $this->wiki
, 'type' => $type );
93 if ( isset( $wgJobTypeConf[$type] ) ) {
94 $conf = $conf +
$wgJobTypeConf[$type];
96 $conf = $conf +
$wgJobTypeConf['default'];
99 return JobQueue
::factory( $conf );
103 * Insert jobs into the respective queues of with the belong.
105 * This inserts the jobs into the queue specified by $wgJobTypeConf
106 * and updates the aggregate job queue information cache as needed.
108 * @param Job|array $jobs A single Job or a list of Jobs
109 * @throws MWException
112 public function push( $jobs ) {
113 $jobs = is_array( $jobs ) ?
$jobs : array( $jobs );
114 if ( !count( $jobs ) ) {
118 $jobsByType = array(); // (job type => list of jobs)
119 foreach ( $jobs as $job ) {
120 if ( $job instanceof Job
) {
121 $jobsByType[$job->getType()][] = $job;
123 throw new MWException( "Attempted to push a non-Job object into a queue." );
128 foreach ( $jobsByType as $type => $jobs ) {
129 if ( $this->get( $type )->push( $jobs ) ) {
130 JobQueueAggregator
::singleton()->notifyQueueNonEmpty( $this->wiki
, $type );
136 if ( $this->cache
->has( 'queues-ready', 'list' ) ) {
137 $list = $this->cache
->get( 'queues-ready', 'list' );
138 if ( count( array_diff( array_keys( $jobsByType ), $list ) ) ) {
139 $this->cache
->clear( 'queues-ready' );
147 * Pop a job off one of the job queues
149 * This pops a job off a queue as specified by $wgJobTypeConf and
150 * updates the aggregate job queue information cache as needed.
152 * @param int|string $qtype JobQueueGroup::TYPE_DEFAULT or type string
153 * @param int $flags Bitfield of JobQueueGroup::USE_* constants
154 * @return Job|bool Returns false on failure
156 public function pop( $qtype = self
::TYPE_DEFAULT
, $flags = 0 ) {
157 if ( is_string( $qtype ) ) { // specific job type
158 $job = $this->get( $qtype )->pop();
160 JobQueueAggregator
::singleton()->notifyQueueEmpty( $this->wiki
, $qtype );
164 } else { // any job in the "default" jobs types
165 if ( $flags & self
::USE_CACHE
) {
166 if ( !$this->cache
->has( 'queues-ready', 'list', self
::PROC_CACHE_TTL
) ) {
167 $this->cache
->set( 'queues-ready', 'list', $this->getQueuesWithJobs() );
169 $types = $this->cache
->get( 'queues-ready', 'list' );
171 $types = $this->getQueuesWithJobs();
174 if ( $qtype == self
::TYPE_DEFAULT
) {
175 $types = array_intersect( $types, $this->getDefaultQueueTypes() );
177 shuffle( $types ); // avoid starvation
179 foreach ( $types as $type ) { // for each queue...
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() ) {
277 * Get the size of the queus for a list of job types
279 * @return array Map of (job type => size)
281 public function getQueueSizes() {
283 foreach ( $this->getCoalescedQueues() as $info ) {
284 $sizes = $info['queue']->getSiblingQueueSizes( $this->getQueueTypes() );
285 if ( is_array( $sizes ) ) { // batching features supported
286 $sizeMap = $sizeMap +
$sizes;
287 } else { // we have to go through the queues in the bucket one-by-one
288 foreach ( $info['types'] as $type ) {
289 $sizeMap[$type] = $this->get( $type )->getSize();
300 protected function getCoalescedQueues() {
301 global $wgJobTypeConf;
303 if ( $this->coalescedQueues
=== null ) {
304 $this->coalescedQueues
= array();
305 foreach ( $wgJobTypeConf as $type => $conf ) {
306 $queue = JobQueue
::factory(
307 array( 'wiki' => $this->wiki
, 'type' => 'null' ) +
$conf );
308 $loc = $queue->getCoalesceLocationInternal();
309 if ( !isset( $this->coalescedQueues
[$loc] ) ) {
310 $this->coalescedQueues
[$loc]['queue'] = $queue;
311 $this->coalescedQueues
[$loc]['types'] = array();
313 if ( $type === 'default' ) {
314 $this->coalescedQueues
[$loc]['types'] = array_merge(
315 $this->coalescedQueues
[$loc]['types'],
316 array_diff( $this->getQueueTypes(), array_keys( $wgJobTypeConf ) )
319 $this->coalescedQueues
[$loc]['types'][] = $type;
324 return $this->coalescedQueues
;
328 * Execute any due periodic queue maintenance tasks for all queues.
330 * A task is "due" if the time ellapsed since the last run is greater than
331 * the defined run period. Concurrent calls to this function will cause tasks
332 * to be attempted twice, so they may need their own methods of mutual exclusion.
334 * @return int Number of tasks run
336 public function executeReadyPeriodicTasks() {
339 list( $db, $prefix ) = wfSplitWikiID( $this->wiki
);
340 $key = wfForeignMemcKey( $db, $prefix, 'jobqueuegroup', 'taskruns', 'v1' );
341 $lastRuns = $wgMemc->get( $key ); // (queue => task => UNIX timestamp)
344 $tasksRun = array(); // (queue => task => UNIX timestamp)
345 foreach ( $this->getQueueTypes() as $type ) {
346 $queue = $this->get( $type );
347 foreach ( $queue->getPeriodicTasks() as $task => $definition ) {
348 if ( $definition['period'] <= 0 ) {
349 continue; // disabled
350 } elseif ( !isset( $lastRuns[$type][$task] )
351 ||
$lastRuns[$type][$task] < ( time() - $definition['period'] )
354 if ( call_user_func( $definition['callback'] ) !== null ) {
355 $tasksRun[$type][$task] = time();
358 } catch ( JobQueueError
$e ) {
359 MWExceptionHandler
::logException( $e );
363 // The tasks may have recycled jobs or release delayed jobs into the queue
364 if ( isset( $tasksRun[$type] ) && !$queue->isEmpty() ) {
365 JobQueueAggregator
::singleton()->notifyQueueNonEmpty( $this->wiki
, $type );
369 $wgMemc->merge( $key, function ( $cache, $key, $lastRuns ) use ( $tasksRun ) {
370 if ( is_array( $lastRuns ) ) {
371 foreach ( $tasksRun as $type => $tasks ) {
372 foreach ( $tasks as $task => $timestamp ) {
373 if ( !isset( $lastRuns[$type][$task] )
374 ||
$timestamp > $lastRuns[$type][$task]
376 $lastRuns[$type][$task] = $timestamp;
381 $lastRuns = $tasksRun;
391 * @param $name string
394 private function getCachedConfigVar( $name ) {
395 global $wgConf, $wgMemc;
397 if ( $this->wiki
=== wfWikiID() ) {
398 return $GLOBALS[$name]; // common case
400 list( $db, $prefix ) = wfSplitWikiID( $this->wiki
);
401 $key = wfForeignMemcKey( $db, $prefix, 'configvalue', $name );
402 $value = $wgMemc->get( $key ); // ('v' => ...) or false
403 if ( is_array( $value ) ) {
406 $value = $wgConf->getConfig( $this->wiki
, $name );
407 $wgMemc->set( $key, array( 'v' => $value ), 86400 +
mt_rand( 0, 86400 ) );