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
24 * Class to handle enqueueing of background jobs
30 /** @var JobQueueGroup[] */
31 protected static $instances = [];
33 /** @var ProcessCacheLRU */
36 /** @var string Wiki ID */
38 /** @var string|bool Read only rationale (or false if r/w) */
39 protected $readOnlyReason;
41 /** @var array Map of (bucket => (queue => JobQueue, types => list of types) */
42 protected $coalescedQueues;
45 protected $bufferedJobs = [];
47 const TYPE_DEFAULT
= 1; // integer; jobs popped by default
48 const TYPE_ANY
= 2; // integer; any job
50 const USE_CACHE
= 1; // integer; use process or persistent cache
52 const PROC_CACHE_TTL
= 15; // integer; seconds
54 const CACHE_VERSION
= 1; // integer; cache version
57 * @param string $wiki Wiki ID
58 * @param string|bool $readOnlyReason Read-only reason or false
60 protected function __construct( $wiki, $readOnlyReason ) {
62 $this->readOnlyReason
= $readOnlyReason;
63 $this->cache
= new ProcessCacheLRU( 10 );
67 * @param bool|string $wiki Wiki ID
68 * @return JobQueueGroup
70 public static function singleton( $wiki = false ) {
71 $wiki = ( $wiki === false ) ?
wfWikiID() : $wiki;
72 if ( !isset( self
::$instances[$wiki] ) ) {
73 self
::$instances[$wiki] = new self( $wiki, wfConfiguredReadOnlyReason() );
76 return self
::$instances[$wiki];
80 * Destroy the singleton instances
84 public static function destroySingletons() {
85 self
::$instances = [];
89 * Get the job queue object for a given queue type
94 public function get( $type ) {
95 global $wgJobTypeConf;
97 $conf = [ 'wiki' => $this->wiki
, 'type' => $type ];
98 if ( isset( $wgJobTypeConf[$type] ) ) {
99 $conf = $conf +
$wgJobTypeConf[$type];
101 $conf = $conf +
$wgJobTypeConf['default'];
103 $conf['aggregator'] = JobQueueAggregator
::singleton();
104 if ( $this->readOnlyReason
!== false ) {
105 $conf['readOnlyReason'] = $this->readOnlyReason
;
108 return JobQueue
::factory( $conf );
112 * Insert jobs into the respective queues of which they belong
114 * This inserts the jobs into the queue specified by $wgJobTypeConf
115 * and updates the aggregate job queue information cache as needed.
117 * @param IJobSpecification|IJobSpecification[] $jobs A single Job or a list of Jobs
118 * @throws InvalidArgumentException
121 public function push( $jobs ) {
122 global $wgJobTypesExcludedFromDefaultQueue;
124 $jobs = is_array( $jobs ) ?
$jobs : [ $jobs ];
125 if ( !count( $jobs ) ) {
129 $this->assertValidJobs( $jobs );
131 $jobsByType = []; // (job type => list of jobs)
132 foreach ( $jobs as $job ) {
133 $jobsByType[$job->getType()][] = $job;
136 foreach ( $jobsByType as $type => $jobs ) {
137 $this->get( $type )->push( $jobs );
140 if ( $this->cache
->has( 'queues-ready', 'list' ) ) {
141 $list = $this->cache
->get( 'queues-ready', 'list' );
142 if ( count( array_diff( array_keys( $jobsByType ), $list ) ) ) {
143 $this->cache
->clear( 'queues-ready' );
147 $cache = ObjectCache
::getLocalClusterInstance();
149 $cache->makeGlobalKey( 'jobqueue', $this->wiki
, 'hasjobs', self
::TYPE_ANY
),
153 if ( array_diff( array_keys( $jobsByType ), $wgJobTypesExcludedFromDefaultQueue ) ) {
155 $cache->makeGlobalKey( 'jobqueue', $this->wiki
, 'hasjobs', self
::TYPE_DEFAULT
),
163 * Buffer jobs for insertion via push() or call it now if in CLI mode
165 * Note that pushLazyJobs() is registered as a deferred update just before
166 * DeferredUpdates::doUpdates() in MediaWiki and JobRunner classes in order
167 * to be executed as the very last deferred update (T100085, T154425).
169 * @param IJobSpecification|IJobSpecification[] $jobs A single Job or a list of Jobs
173 public function lazyPush( $jobs ) {
174 if ( PHP_SAPI
=== 'cli' || PHP_SAPI
=== 'phpdbg' ) {
175 $this->push( $jobs );
179 $jobs = is_array( $jobs ) ?
$jobs : [ $jobs ];
181 // Throw errors now instead of on push(), when other jobs may be buffered
182 $this->assertValidJobs( $jobs );
184 $this->bufferedJobs
= array_merge( $this->bufferedJobs
, $jobs );
188 * Push all jobs buffered via lazyPush() into their respective queues
193 public static function pushLazyJobs() {
194 foreach ( self
::$instances as $group ) {
196 $group->push( $group->bufferedJobs
);
197 $group->bufferedJobs
= [];
198 } catch ( Exception
$e ) {
199 // Get in as many jobs as possible and let other post-send updates happen
200 MWExceptionHandler
::logException( $e );
206 * Pop a job off one of the job queues
208 * This pops a job off a queue as specified by $wgJobTypeConf and
209 * updates the aggregate job queue information cache as needed.
211 * @param int|string $qtype JobQueueGroup::TYPE_* constant or job type string
212 * @param int $flags Bitfield of JobQueueGroup::USE_* constants
213 * @param array $blacklist List of job types to ignore
214 * @return Job|bool Returns false on failure
216 public function pop( $qtype = self
::TYPE_DEFAULT
, $flags = 0, array $blacklist = [] ) {
219 if ( is_string( $qtype ) ) { // specific job type
220 if ( !in_array( $qtype, $blacklist ) ) {
221 $job = $this->get( $qtype )->pop();
223 } else { // any job in the "default" jobs types
224 if ( $flags & self
::USE_CACHE
) {
225 if ( !$this->cache
->has( 'queues-ready', 'list', self
::PROC_CACHE_TTL
) ) {
226 $this->cache
->set( 'queues-ready', 'list', $this->getQueuesWithJobs() );
228 $types = $this->cache
->get( 'queues-ready', 'list' );
230 $types = $this->getQueuesWithJobs();
233 if ( $qtype == self
::TYPE_DEFAULT
) {
234 $types = array_intersect( $types, $this->getDefaultQueueTypes() );
237 $types = array_diff( $types, $blacklist ); // avoid selected types
238 shuffle( $types ); // avoid starvation
240 foreach ( $types as $type ) { // for each queue...
241 $job = $this->get( $type )->pop();
242 if ( $job ) { // found
244 } else { // not found
245 $this->cache
->clear( 'queues-ready' );
254 * Acknowledge that a job was completed
259 public function ack( Job
$job ) {
260 $this->get( $job->getType() )->ack( $job );
264 * Register the "root job" of a given job into the queue for de-duplication.
265 * This should only be called right *after* all the new jobs have been inserted.
270 public function deduplicateRootJob( Job
$job ) {
271 return $this->get( $job->getType() )->deduplicateRootJob( $job );
275 * Wait for any replica DBs or backup queue servers to catch up.
277 * This does nothing for certain queue classes.
281 public function waitForBackups() {
282 global $wgJobTypeConf;
284 // Try to avoid doing this more than once per queue storage medium
285 foreach ( $wgJobTypeConf as $type => $conf ) {
286 $this->get( $type )->waitForBackups();
291 * Get the list of queue types
293 * @return array List of strings
295 public function getQueueTypes() {
296 return array_keys( $this->getCachedConfigVar( 'wgJobClasses' ) );
300 * Get the list of default queue types
302 * @return array List of strings
304 public function getDefaultQueueTypes() {
305 global $wgJobTypesExcludedFromDefaultQueue;
307 return array_diff( $this->getQueueTypes(), $wgJobTypesExcludedFromDefaultQueue );
311 * Check if there are any queues with jobs (this is cached)
313 * @param int $type JobQueueGroup::TYPE_* constant
317 public function queuesHaveJobs( $type = self
::TYPE_ANY
) {
318 $cache = ObjectCache
::getLocalClusterInstance();
319 $key = $cache->makeGlobalKey( 'jobqueue', $this->wiki
, 'hasjobs', $type );
321 $value = $cache->get( $key );
322 if ( $value === false ) {
323 $queues = $this->getQueuesWithJobs();
324 if ( $type == self
::TYPE_DEFAULT
) {
325 $queues = array_intersect( $queues, $this->getDefaultQueueTypes() );
327 $value = count( $queues ) ?
'true' : 'false';
328 $cache->add( $key, $value, 15 );
331 return ( $value === 'true' );
335 * Get the list of job types that have non-empty queues
337 * @return array List of job types that have non-empty queues
339 public function getQueuesWithJobs() {
341 foreach ( $this->getCoalescedQueues() as $info ) {
342 $nonEmpty = $info['queue']->getSiblingQueuesWithJobs( $this->getQueueTypes() );
343 if ( is_array( $nonEmpty ) ) { // batching features supported
344 $types = array_merge( $types, $nonEmpty );
345 } else { // we have to go through the queues in the bucket one-by-one
346 foreach ( $info['types'] as $type ) {
347 if ( !$this->get( $type )->isEmpty() ) {
358 * Get the size of the queus for a list of job types
360 * @return array Map of (job type => size)
362 public function getQueueSizes() {
364 foreach ( $this->getCoalescedQueues() as $info ) {
365 $sizes = $info['queue']->getSiblingQueueSizes( $this->getQueueTypes() );
366 if ( is_array( $sizes ) ) { // batching features supported
367 $sizeMap = $sizeMap +
$sizes;
368 } else { // we have to go through the queues in the bucket one-by-one
369 foreach ( $info['types'] as $type ) {
370 $sizeMap[$type] = $this->get( $type )->getSize();
381 protected function getCoalescedQueues() {
382 global $wgJobTypeConf;
384 if ( $this->coalescedQueues
=== null ) {
385 $this->coalescedQueues
= [];
386 foreach ( $wgJobTypeConf as $type => $conf ) {
387 $queue = JobQueue
::factory(
388 [ 'wiki' => $this->wiki
, 'type' => 'null' ] +
$conf );
389 $loc = $queue->getCoalesceLocationInternal();
390 if ( !isset( $this->coalescedQueues
[$loc] ) ) {
391 $this->coalescedQueues
[$loc]['queue'] = $queue;
392 $this->coalescedQueues
[$loc]['types'] = [];
394 if ( $type === 'default' ) {
395 $this->coalescedQueues
[$loc]['types'] = array_merge(
396 $this->coalescedQueues
[$loc]['types'],
397 array_diff( $this->getQueueTypes(), array_keys( $wgJobTypeConf ) )
400 $this->coalescedQueues
[$loc]['types'][] = $type;
405 return $this->coalescedQueues
;
409 * @param string $name
412 private function getCachedConfigVar( $name ) {
413 // @TODO: cleanup this whole method with a proper config system
414 if ( $this->wiki
=== wfWikiID() ) {
415 return $GLOBALS[$name]; // common case
418 $cache = ObjectCache
::getMainWANInstance();
419 $value = $cache->getWithSetCallback(
420 $cache->makeGlobalKey( 'jobqueue', 'configvalue', $wiki, $name ),
421 $cache::TTL_DAY +
mt_rand( 0, $cache::TTL_DAY
),
422 function () use ( $wiki, $name ) {
425 return [ 'v' => $wgConf->getConfig( $wiki, $name ) ];
427 [ 'pcTTL' => WANObjectCache
::TTL_PROC_LONG
]
436 * @throws InvalidArgumentException
438 private function assertValidJobs( array $jobs ) {
439 foreach ( $jobs as $job ) { // sanity checks
440 if ( !( $job instanceof IJobSpecification
) ) {
441 throw new InvalidArgumentException( "Expected IJobSpecification objects" );
446 function __destruct() {
447 $n = count( $this->bufferedJobs
);
449 $type = implode( ', ', array_unique( array_map( 'get_class', $this->bufferedJobs
) ) );
450 trigger_error( __METHOD__
. ": $n buffered job(s) of type(s) $type never inserted." );