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
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 bool|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 );
70 return self
::$instances[$wiki];
74 * Destroy the singleton instances
78 public static function destroySingletons() {
79 self
::$instances = array();
83 * Get the job queue object for a given queue type
88 public function get( $type ) {
89 global $wgJobTypeConf;
91 $conf = array( 'wiki' => $this->wiki
, 'type' => $type );
92 if ( isset( $wgJobTypeConf[$type] ) ) {
93 $conf = $conf +
$wgJobTypeConf[$type];
95 $conf = $conf +
$wgJobTypeConf['default'];
98 return JobQueue
::factory( $conf );
102 * Insert jobs into the respective queues of with the belong.
104 * This inserts the jobs into the queue specified by $wgJobTypeConf
105 * and updates the aggregate job queue information cache as needed.
107 * @param Job|Job[] $jobs A single Job or a list of Jobs
108 * @throws MWException
111 public function push( $jobs ) {
112 $jobs = is_array( $jobs ) ?
$jobs : array( $jobs );
113 if ( !count( $jobs ) ) {
117 $jobsByType = array(); // (job type => list of jobs)
118 foreach ( $jobs as $job ) {
119 if ( $job instanceof IJobSpecification
) {
120 $jobsByType[$job->getType()][] = $job;
122 throw new MWException( "Attempted to push a non-Job object into a queue." );
126 foreach ( $jobsByType as $type => $jobs ) {
127 $this->get( $type )->push( $jobs );
128 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' );
140 * Pop a job off one of the job queues
142 * This pops a job off a queue as specified by $wgJobTypeConf and
143 * updates the aggregate job queue information cache as needed.
145 * @param int|string $qtype JobQueueGroup::TYPE_* constant or job type string
146 * @param int $flags Bitfield of JobQueueGroup::USE_* constants
147 * @param array $blacklist List of job types to ignore
148 * @return Job|bool Returns false on failure
150 public function pop( $qtype = self
::TYPE_DEFAULT
, $flags = 0, array $blacklist = array() ) {
153 if ( is_string( $qtype ) ) { // specific job type
154 if ( !in_array( $qtype, $blacklist ) ) {
155 $job = $this->get( $qtype )->pop();
157 JobQueueAggregator
::singleton()->notifyQueueEmpty( $this->wiki
, $qtype );
160 } else { // any job in the "default" jobs types
161 if ( $flags & self
::USE_CACHE
) {
162 if ( !$this->cache
->has( 'queues-ready', 'list', self
::PROC_CACHE_TTL
) ) {
163 $this->cache
->set( 'queues-ready', 'list', $this->getQueuesWithJobs() );
165 $types = $this->cache
->get( 'queues-ready', 'list' );
167 $types = $this->getQueuesWithJobs();
170 if ( $qtype == self
::TYPE_DEFAULT
) {
171 $types = array_intersect( $types, $this->getDefaultQueueTypes() );
174 $types = array_diff( $types, $blacklist ); // avoid selected types
175 shuffle( $types ); // avoid starvation
177 foreach ( $types as $type ) { // for each queue...
178 $job = $this->get( $type )->pop();
179 if ( $job ) { // found
181 } else { // not found
182 JobQueueAggregator
::singleton()->notifyQueueEmpty( $this->wiki
, $type );
183 $this->cache
->clear( 'queues-ready' );
192 * Acknowledge that a job was completed
197 public function ack( Job
$job ) {
198 return $this->get( $job->getType() )->ack( $job );
202 * Register the "root job" of a given job into the queue for de-duplication.
203 * This should only be called right *after* all the new jobs have been inserted.
208 public function deduplicateRootJob( Job
$job ) {
209 return $this->get( $job->getType() )->deduplicateRootJob( $job );
213 * Wait for any slaves or backup queue servers to catch up.
215 * This does nothing for certain queue classes.
218 * @throws MWException
220 public function waitForBackups() {
221 global $wgJobTypeConf;
223 wfProfileIn( __METHOD__
);
224 // Try to avoid doing this more than once per queue storage medium
225 foreach ( $wgJobTypeConf as $type => $conf ) {
226 $this->get( $type )->waitForBackups();
228 wfProfileOut( __METHOD__
);
232 * Get the list of queue types
234 * @return array List of strings
236 public function getQueueTypes() {
237 return array_keys( $this->getCachedConfigVar( 'wgJobClasses' ) );
241 * Get the list of default queue types
243 * @return array List of strings
245 public function getDefaultQueueTypes() {
246 global $wgJobTypesExcludedFromDefaultQueue;
248 return array_diff( $this->getQueueTypes(), $wgJobTypesExcludedFromDefaultQueue );
252 * Check if there are any queues with jobs (this is cached)
254 * @param int $type JobQueueGroup::TYPE_* constant
258 public function queuesHaveJobs( $type = self
::TYPE_ANY
) {
261 $key = wfMemcKey( 'jobqueue', 'queueshavejobs', $type );
263 $value = $wgMemc->get( $key );
264 if ( $value === false ) {
265 $queues = $this->getQueuesWithJobs();
266 if ( $type == self
::TYPE_DEFAULT
) {
267 $queues = array_intersect( $queues, $this->getDefaultQueueTypes() );
269 $value = count( $queues ) ?
'true' : 'false';
270 $wgMemc->add( $key, $value, 15 );
273 return ( $value === 'true' );
277 * Get the list of job types that have non-empty queues
279 * @return array List of job types that have non-empty queues
281 public function getQueuesWithJobs() {
283 foreach ( $this->getCoalescedQueues() as $info ) {
284 $nonEmpty = $info['queue']->getSiblingQueuesWithJobs( $this->getQueueTypes() );
285 if ( is_array( $nonEmpty ) ) { // batching features supported
286 $types = array_merge( $types, $nonEmpty );
287 } else { // we have to go through the queues in the bucket one-by-one
288 foreach ( $info['types'] as $type ) {
289 if ( !$this->get( $type )->isEmpty() ) {
300 * Get the size of the queus for a list of job types
302 * @return array Map of (job type => size)
304 public function getQueueSizes() {
306 foreach ( $this->getCoalescedQueues() as $info ) {
307 $sizes = $info['queue']->getSiblingQueueSizes( $this->getQueueTypes() );
308 if ( is_array( $sizes ) ) { // batching features supported
309 $sizeMap = $sizeMap +
$sizes;
310 } else { // we have to go through the queues in the bucket one-by-one
311 foreach ( $info['types'] as $type ) {
312 $sizeMap[$type] = $this->get( $type )->getSize();
323 protected function getCoalescedQueues() {
324 global $wgJobTypeConf;
326 if ( $this->coalescedQueues
=== null ) {
327 $this->coalescedQueues
= array();
328 foreach ( $wgJobTypeConf as $type => $conf ) {
329 $queue = JobQueue
::factory(
330 array( 'wiki' => $this->wiki
, 'type' => 'null' ) +
$conf );
331 $loc = $queue->getCoalesceLocationInternal();
332 if ( !isset( $this->coalescedQueues
[$loc] ) ) {
333 $this->coalescedQueues
[$loc]['queue'] = $queue;
334 $this->coalescedQueues
[$loc]['types'] = array();
336 if ( $type === 'default' ) {
337 $this->coalescedQueues
[$loc]['types'] = array_merge(
338 $this->coalescedQueues
[$loc]['types'],
339 array_diff( $this->getQueueTypes(), array_keys( $wgJobTypeConf ) )
342 $this->coalescedQueues
[$loc]['types'][] = $type;
347 return $this->coalescedQueues
;
351 * Execute any due periodic queue maintenance tasks for all queues.
353 * A task is "due" if the time ellapsed since the last run is greater than
354 * the defined run period. Concurrent calls to this function will cause tasks
355 * to be attempted twice, so they may need their own methods of mutual exclusion.
357 * @return int Number of tasks run
359 public function executeReadyPeriodicTasks() {
362 list( $db, $prefix ) = wfSplitWikiID( $this->wiki
);
363 $key = wfForeignMemcKey( $db, $prefix, 'jobqueuegroup', 'taskruns', 'v1' );
364 $lastRuns = $wgMemc->get( $key ); // (queue => task => UNIX timestamp)
367 $tasksRun = array(); // (queue => task => UNIX timestamp)
368 foreach ( $this->getQueueTypes() as $type ) {
369 $queue = $this->get( $type );
370 foreach ( $queue->getPeriodicTasks() as $task => $definition ) {
371 if ( $definition['period'] <= 0 ) {
372 continue; // disabled
373 } elseif ( !isset( $lastRuns[$type][$task] )
374 ||
$lastRuns[$type][$task] < ( time() - $definition['period'] )
377 if ( call_user_func( $definition['callback'] ) !== null ) {
378 $tasksRun[$type][$task] = time();
381 } catch ( JobQueueError
$e ) {
382 MWExceptionHandler
::logException( $e );
386 // The tasks may have recycled jobs or release delayed jobs into the queue
387 if ( isset( $tasksRun[$type] ) && !$queue->isEmpty() ) {
388 JobQueueAggregator
::singleton()->notifyQueueNonEmpty( $this->wiki
, $type );
392 if ( $count === 0 ) {
393 return $count; // nothing to update
396 $wgMemc->merge( $key, function ( $cache, $key, $lastRuns ) use ( $tasksRun ) {
397 if ( is_array( $lastRuns ) ) {
398 foreach ( $tasksRun as $type => $tasks ) {
399 foreach ( $tasks as $task => $timestamp ) {
400 if ( !isset( $lastRuns[$type][$task] )
401 ||
$timestamp > $lastRuns[$type][$task]
403 $lastRuns[$type][$task] = $timestamp;
408 $lastRuns = $tasksRun;
418 * @param string $name
421 private function getCachedConfigVar( $name ) {
422 global $wgConf, $wgMemc;
424 if ( $this->wiki
=== wfWikiID() ) {
425 return $GLOBALS[$name]; // common case
427 list( $db, $prefix ) = wfSplitWikiID( $this->wiki
);
428 $key = wfForeignMemcKey( $db, $prefix, 'configvalue', $name );
429 $value = $wgMemc->get( $key ); // ('v' => ...) or false
430 if ( is_array( $value ) ) {
433 $value = $wgConf->getConfig( $this->wiki
, $name );
434 $wgMemc->set( $key, array( 'v' => $value ), 86400 +
mt_rand( 0, 86400 ) );