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
31 /** @var JobQueueGroup[] */
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;
44 protected $bufferedJobs = array();
46 const TYPE_DEFAULT
= 1; // integer; jobs popped by default
47 const TYPE_ANY
= 2; // integer; any job
49 const USE_CACHE
= 1; // integer; use process or persistent cache
51 const PROC_CACHE_TTL
= 15; // integer; seconds
53 const CACHE_VERSION
= 1; // integer; cache version
56 * @param string $wiki Wiki ID
58 protected function __construct( $wiki ) {
60 $this->cache
= new ProcessCacheLRU( 10 );
64 * @param bool|string $wiki Wiki ID
65 * @return JobQueueGroup
67 public static function singleton( $wiki = false ) {
68 $wiki = ( $wiki === false ) ?
wfWikiID() : $wiki;
69 if ( !isset( self
::$instances[$wiki] ) ) {
70 self
::$instances[$wiki] = new self( $wiki );
73 return self
::$instances[$wiki];
77 * Destroy the singleton instances
81 public static function destroySingletons() {
82 self
::$instances = array();
86 * Get the job queue object for a given queue type
91 public function get( $type ) {
92 global $wgJobTypeConf;
94 $conf = array( 'wiki' => $this->wiki
, 'type' => $type );
95 if ( isset( $wgJobTypeConf[$type] ) ) {
96 $conf = $conf +
$wgJobTypeConf[$type];
98 $conf = $conf +
$wgJobTypeConf['default'];
100 $conf['aggregator'] = JobQueueAggregator
::singleton();
102 return JobQueue
::factory( $conf );
106 * Insert jobs into the respective queues of which they belong
108 * This inserts the jobs into the queue specified by $wgJobTypeConf
109 * and updates the aggregate job queue information cache as needed.
111 * @param IJobSpecification|IJobSpecification[] $jobs A single Job or a list of Jobs
112 * @throws InvalidArgumentException
115 public function push( $jobs ) {
116 $jobs = is_array( $jobs ) ?
$jobs : array( $jobs );
117 if ( !count( $jobs ) ) {
121 $this->assertValidJobs( $jobs );
123 $jobsByType = array(); // (job type => list of jobs)
124 foreach ( $jobs as $job ) {
125 $jobsByType[$job->getType()][] = $job;
128 foreach ( $jobsByType as $type => $jobs ) {
129 $this->get( $type )->push( $jobs );
132 if ( $this->cache
->has( 'queues-ready', 'list' ) ) {
133 $list = $this->cache
->get( 'queues-ready', 'list' );
134 if ( count( array_diff( array_keys( $jobsByType ), $list ) ) ) {
135 $this->cache
->clear( 'queues-ready' );
141 * Buffer jobs for insertion via push() or call it now if in CLI mode
143 * Note that MediaWiki::restInPeace() calls pushLazyJobs()
145 * @param IJobSpecification|IJobSpecification[] $jobs A single Job or a list of Jobs
149 public function lazyPush( $jobs ) {
150 if ( PHP_SAPI
=== 'cli' ) {
151 $this->push( $jobs );
155 $jobs = is_array( $jobs ) ?
$jobs : array( $jobs );
157 // Throw errors now instead of on push(), when other jobs may be buffered
158 $this->assertValidJobs( $jobs );
160 $this->bufferedJobs
= array_merge( $this->bufferedJobs
, $jobs );
164 * Push all jobs buffered via lazyPush() into their respective queues
169 public static function pushLazyJobs() {
170 foreach ( self
::$instances as $group ) {
171 $group->push( $group->bufferedJobs
);
172 $group->bufferedJobs
= array();
177 * Pop a job off one of the job queues
179 * This pops a job off a queue as specified by $wgJobTypeConf and
180 * updates the aggregate job queue information cache as needed.
182 * @param int|string $qtype JobQueueGroup::TYPE_* constant or job type string
183 * @param int $flags Bitfield of JobQueueGroup::USE_* constants
184 * @param array $blacklist List of job types to ignore
185 * @return Job|bool Returns false on failure
187 public function pop( $qtype = self
::TYPE_DEFAULT
, $flags = 0, array $blacklist = array() ) {
190 if ( is_string( $qtype ) ) { // specific job type
191 if ( !in_array( $qtype, $blacklist ) ) {
192 $job = $this->get( $qtype )->pop();
194 } else { // any job in the "default" jobs types
195 if ( $flags & self
::USE_CACHE
) {
196 if ( !$this->cache
->has( 'queues-ready', 'list', self
::PROC_CACHE_TTL
) ) {
197 $this->cache
->set( 'queues-ready', 'list', $this->getQueuesWithJobs() );
199 $types = $this->cache
->get( 'queues-ready', 'list' );
201 $types = $this->getQueuesWithJobs();
204 if ( $qtype == self
::TYPE_DEFAULT
) {
205 $types = array_intersect( $types, $this->getDefaultQueueTypes() );
208 $types = array_diff( $types, $blacklist ); // avoid selected types
209 shuffle( $types ); // avoid starvation
211 foreach ( $types as $type ) { // for each queue...
212 $job = $this->get( $type )->pop();
213 if ( $job ) { // found
215 } else { // not found
216 $this->cache
->clear( 'queues-ready' );
225 * Acknowledge that a job was completed
230 public function ack( Job
$job ) {
231 $this->get( $job->getType() )->ack( $job );
235 * Register the "root job" of a given job into the queue for de-duplication.
236 * This should only be called right *after* all the new jobs have been inserted.
241 public function deduplicateRootJob( Job
$job ) {
242 return $this->get( $job->getType() )->deduplicateRootJob( $job );
246 * Wait for any slaves or backup queue servers to catch up.
248 * This does nothing for certain queue classes.
252 public function waitForBackups() {
253 global $wgJobTypeConf;
255 // Try to avoid doing this more than once per queue storage medium
256 foreach ( $wgJobTypeConf as $type => $conf ) {
257 $this->get( $type )->waitForBackups();
262 * Get the list of queue types
264 * @return array List of strings
266 public function getQueueTypes() {
267 return array_keys( $this->getCachedConfigVar( 'wgJobClasses' ) );
271 * Get the list of default queue types
273 * @return array List of strings
275 public function getDefaultQueueTypes() {
276 global $wgJobTypesExcludedFromDefaultQueue;
278 return array_diff( $this->getQueueTypes(), $wgJobTypesExcludedFromDefaultQueue );
282 * Check if there are any queues with jobs (this is cached)
284 * @param int $type JobQueueGroup::TYPE_* constant
288 public function queuesHaveJobs( $type = self
::TYPE_ANY
) {
289 $key = wfMemcKey( 'jobqueue', 'queueshavejobs', $type );
290 $cache = ObjectCache
::getLocalClusterInstance();
292 $value = $cache->get( $key );
293 if ( $value === false ) {
294 $queues = $this->getQueuesWithJobs();
295 if ( $type == self
::TYPE_DEFAULT
) {
296 $queues = array_intersect( $queues, $this->getDefaultQueueTypes() );
298 $value = count( $queues ) ?
'true' : 'false';
299 $cache->add( $key, $value, 15 );
302 return ( $value === 'true' );
306 * Get the list of job types that have non-empty queues
308 * @return array List of job types that have non-empty queues
310 public function getQueuesWithJobs() {
312 foreach ( $this->getCoalescedQueues() as $info ) {
313 $nonEmpty = $info['queue']->getSiblingQueuesWithJobs( $this->getQueueTypes() );
314 if ( is_array( $nonEmpty ) ) { // batching features supported
315 $types = array_merge( $types, $nonEmpty );
316 } else { // we have to go through the queues in the bucket one-by-one
317 foreach ( $info['types'] as $type ) {
318 if ( !$this->get( $type )->isEmpty() ) {
329 * Get the size of the queus for a list of job types
331 * @return array Map of (job type => size)
333 public function getQueueSizes() {
335 foreach ( $this->getCoalescedQueues() as $info ) {
336 $sizes = $info['queue']->getSiblingQueueSizes( $this->getQueueTypes() );
337 if ( is_array( $sizes ) ) { // batching features supported
338 $sizeMap = $sizeMap +
$sizes;
339 } else { // we have to go through the queues in the bucket one-by-one
340 foreach ( $info['types'] as $type ) {
341 $sizeMap[$type] = $this->get( $type )->getSize();
352 protected function getCoalescedQueues() {
353 global $wgJobTypeConf;
355 if ( $this->coalescedQueues
=== null ) {
356 $this->coalescedQueues
= array();
357 foreach ( $wgJobTypeConf as $type => $conf ) {
358 $queue = JobQueue
::factory(
359 array( 'wiki' => $this->wiki
, 'type' => 'null' ) +
$conf );
360 $loc = $queue->getCoalesceLocationInternal();
361 if ( !isset( $this->coalescedQueues
[$loc] ) ) {
362 $this->coalescedQueues
[$loc]['queue'] = $queue;
363 $this->coalescedQueues
[$loc]['types'] = array();
365 if ( $type === 'default' ) {
366 $this->coalescedQueues
[$loc]['types'] = array_merge(
367 $this->coalescedQueues
[$loc]['types'],
368 array_diff( $this->getQueueTypes(), array_keys( $wgJobTypeConf ) )
371 $this->coalescedQueues
[$loc]['types'][] = $type;
376 return $this->coalescedQueues
;
380 * @param string $name
383 private function getCachedConfigVar( $name ) {
384 // @TODO: cleanup this whole method with a proper config system
385 if ( $this->wiki
=== wfWikiID() ) {
386 return $GLOBALS[$name]; // common case
389 $cache = ObjectCache
::getMainWANInstance();
390 $value = $cache->getWithSetCallback(
391 $cache->makeGlobalKey( 'jobqueue', 'configvalue', $wiki, $name ),
392 $cache::TTL_DAY +
mt_rand( 0, $cache::TTL_DAY
),
393 function () use ( $wiki, $name ) {
396 return array( 'v' => $wgConf->getConfig( $wiki, $name ) );
398 array( 'pcTTL' => 30 )
407 * @throws InvalidArgumentException
409 private function assertValidJobs( array $jobs ) {
410 foreach ( $jobs as $job ) { // sanity checks
411 if ( !( $job instanceof IJobSpecification
) ) {
412 throw new InvalidArgumentException( "Expected IJobSpecification objects" );
417 function __destruct() {
418 $n = count( $this->bufferedJobs
);
420 $type = implode( ', ', array_unique( array_map( 'get_class', $this->bufferedJobs
) ) );
421 trigger_error( __METHOD__
. ": $n buffered job(s) of type(s) $type never inserted." );