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
22 use MediaWiki\MediaWikiServices
;
25 * Class to handle enqueueing of background jobs
31 /** @var JobQueueGroup[] */
32 protected static $instances = [];
34 /** @var MapCacheLRU */
37 /** @var string Wiki domain ID */
39 /** @var string|bool Read only rationale (or false if r/w) */
40 protected $readOnlyReason;
41 /** @var bool Whether the wiki is not recognized in configuration */
42 protected $invalidDomain = false;
44 /** @var array Map of (bucket => (queue => JobQueue, types => list of types) */
45 protected $coalescedQueues;
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 $domain Wiki domain ID
58 * @param string|bool $readOnlyReason Read-only reason or false
60 protected function __construct( $domain, $readOnlyReason ) {
61 $this->domain
= $domain;
62 $this->readOnlyReason
= $readOnlyReason;
63 $this->cache
= new MapCacheLRU( 10 );
67 * @param bool|string $domain Wiki domain ID
68 * @return JobQueueGroup
70 public static function singleton( $domain = false ) {
71 global $wgLocalDatabases;
73 if ( $domain === false ) {
74 $domain = WikiMap
::getCurrentWikiDbDomain()->getId();
77 if ( !isset( self
::$instances[$domain] ) ) {
78 self
::$instances[$domain] = new self( $domain, wfConfiguredReadOnlyReason() );
79 // Make sure jobs are not getting pushed to bogus wikis. This can confuse
80 // the job runner system into spawning endless RPC requests that fail (T171371).
81 $wikiId = WikiMap
::getWikiIdFromDbDomain( $domain );
83 !WikiMap
::isCurrentWikiDbDomain( $domain ) &&
84 !in_array( $wikiId, $wgLocalDatabases )
86 self
::$instances[$domain]->invalidDomain
= true;
90 return self
::$instances[$domain];
94 * Destroy the singleton instances
98 public static function destroySingletons() {
99 self
::$instances = [];
103 * Get the job queue object for a given queue type
105 * @param string $type
108 public function get( $type ) {
109 global $wgJobTypeConf;
111 $conf = [ 'domain' => $this->domain
, 'type' => $type ];
112 if ( isset( $wgJobTypeConf[$type] ) ) {
113 $conf = $conf +
$wgJobTypeConf[$type];
115 $conf = $conf +
$wgJobTypeConf['default'];
117 if ( !isset( $conf['readOnlyReason'] ) ) {
118 $conf['readOnlyReason'] = $this->readOnlyReason
;
121 $services = MediaWikiServices
::getInstance();
122 $conf['stats'] = $services->getStatsdDataFactory();
123 $conf['wanCache'] = $services->getMainWANObjectCache();
125 return JobQueue
::factory( $conf );
129 * Insert jobs into the respective queues of which they belong
131 * This inserts the jobs into the queue specified by $wgJobTypeConf
132 * and updates the aggregate job queue information cache as needed.
134 * @param IJobSpecification|IJobSpecification[] $jobs A single Job or a list of Jobs
135 * @throws InvalidArgumentException
138 public function push( $jobs ) {
139 global $wgJobTypesExcludedFromDefaultQueue;
141 if ( $this->invalidDomain
) {
142 // Do not enqueue job that cannot be run (T171371)
143 $e = new LogicException( "Domain '{$this->domain}' is not recognized." );
144 MWExceptionHandler
::logException( $e );
148 $jobs = is_array( $jobs ) ?
$jobs : [ $jobs ];
149 if ( $jobs === [] ) {
153 $this->assertValidJobs( $jobs );
155 $jobsByType = []; // (job type => list of jobs)
156 foreach ( $jobs as $job ) {
157 $jobsByType[$job->getType()][] = $job;
160 foreach ( $jobsByType as $type => $jobs ) {
161 $this->get( $type )->push( $jobs );
164 if ( $this->cache
->hasField( 'queues-ready', 'list' ) ) {
165 $list = $this->cache
->getField( 'queues-ready', 'list' );
166 if ( count( array_diff( array_keys( $jobsByType ), $list ) ) ) {
167 $this->cache
->clear( 'queues-ready' );
171 $cache = ObjectCache
::getLocalClusterInstance();
173 $cache->makeGlobalKey( 'jobqueue', $this->domain
, 'hasjobs', self
::TYPE_ANY
),
177 if ( array_diff( array_keys( $jobsByType ), $wgJobTypesExcludedFromDefaultQueue ) ) {
179 $cache->makeGlobalKey( 'jobqueue', $this->domain
, 'hasjobs', self
::TYPE_DEFAULT
),
187 * Buffer jobs for insertion via push() or call it now if in CLI mode
189 * @param IJobSpecification|IJobSpecification[] $jobs A single Job or a list of Jobs
193 public function lazyPush( $jobs ) {
194 if ( $this->invalidDomain
) {
195 // Do not enqueue job that cannot be run (T171371)
196 throw new LogicException( "Domain '{$this->domain}' is not recognized." );
199 if ( PHP_SAPI
=== 'cli' || PHP_SAPI
=== 'phpdbg' ) {
200 $this->push( $jobs );
204 $jobs = is_array( $jobs ) ?
$jobs : [ $jobs ];
206 // Throw errors now instead of on push(), when other jobs may be buffered
207 $this->assertValidJobs( $jobs );
209 DeferredUpdates
::addUpdate( new JobQueueEnqueueUpdate( $this->domain
, $jobs ) );
213 * Pop a job off one of the job queues
215 * This pops a job off a queue as specified by $wgJobTypeConf and
216 * updates the aggregate job queue information cache as needed.
218 * @param int|string $qtype JobQueueGroup::TYPE_* constant or job type string
219 * @param int $flags Bitfield of JobQueueGroup::USE_* constants
220 * @param array $blacklist List of job types to ignore
221 * @return RunnableJob|bool Returns false on failure
223 public function pop( $qtype = self
::TYPE_DEFAULT
, $flags = 0, array $blacklist = [] ) {
224 global $wgJobClasses;
228 if ( !WikiMap
::isCurrentWikiDbDomain( $this->domain
) ) {
229 throw new JobQueueError(
230 "Cannot pop '{$qtype}' job off foreign '{$this->domain}' wiki queue." );
231 } elseif ( is_string( $qtype ) && !isset( $wgJobClasses[$qtype] ) ) {
232 // Do not pop jobs if there is no class for the queue type
233 throw new JobQueueError( "Unrecognized job type '$qtype'." );
236 if ( is_string( $qtype ) ) { // specific job type
237 if ( !in_array( $qtype, $blacklist ) ) {
238 $job = $this->get( $qtype )->pop();
240 } else { // any job in the "default" jobs types
241 if ( $flags & self
::USE_CACHE
) {
242 if ( !$this->cache
->hasField( 'queues-ready', 'list', self
::PROC_CACHE_TTL
) ) {
243 $this->cache
->setField( 'queues-ready', 'list', $this->getQueuesWithJobs() );
245 $types = $this->cache
->getField( 'queues-ready', 'list' );
247 $types = $this->getQueuesWithJobs();
250 if ( $qtype == self
::TYPE_DEFAULT
) {
251 $types = array_intersect( $types, $this->getDefaultQueueTypes() );
254 $types = array_diff( $types, $blacklist ); // avoid selected types
255 shuffle( $types ); // avoid starvation
257 foreach ( $types as $type ) { // for each queue...
258 $job = $this->get( $type )->pop();
259 if ( $job ) { // found
261 } else { // not found
262 $this->cache
->clear( 'queues-ready' );
271 * Acknowledge that a job was completed
273 * @param RunnableJob $job
276 public function ack( RunnableJob
$job ) {
277 $this->get( $job->getType() )->ack( $job );
281 * Register the "root job" of a given job into the queue for de-duplication.
282 * This should only be called right *after* all the new jobs have been inserted.
284 * @param RunnableJob $job
287 public function deduplicateRootJob( RunnableJob
$job ) {
288 return $this->get( $job->getType() )->deduplicateRootJob( $job );
292 * Wait for any replica DBs or backup queue servers to catch up.
294 * This does nothing for certain queue classes.
298 public function waitForBackups() {
299 global $wgJobTypeConf;
301 // Try to avoid doing this more than once per queue storage medium
302 foreach ( $wgJobTypeConf as $type => $conf ) {
303 $this->get( $type )->waitForBackups();
308 * Get the list of queue types
310 * @return array List of strings
312 public function getQueueTypes() {
313 return array_keys( $this->getCachedConfigVar( 'wgJobClasses' ) );
317 * Get the list of default queue types
319 * @return array List of strings
321 public function getDefaultQueueTypes() {
322 global $wgJobTypesExcludedFromDefaultQueue;
324 return array_diff( $this->getQueueTypes(), $wgJobTypesExcludedFromDefaultQueue );
328 * Check if there are any queues with jobs (this is cached)
330 * @param int $type JobQueueGroup::TYPE_* constant
334 public function queuesHaveJobs( $type = self
::TYPE_ANY
) {
335 $cache = ObjectCache
::getLocalClusterInstance();
336 $key = $cache->makeGlobalKey( 'jobqueue', $this->domain
, 'hasjobs', $type );
338 $value = $cache->get( $key );
339 if ( $value === false ) {
340 $queues = $this->getQueuesWithJobs();
341 if ( $type == self
::TYPE_DEFAULT
) {
342 $queues = array_intersect( $queues, $this->getDefaultQueueTypes() );
344 $value = count( $queues ) ?
'true' : 'false';
345 $cache->add( $key, $value, 15 );
348 return ( $value === 'true' );
352 * Get the list of job types that have non-empty queues
354 * @return string[] List of job types that have non-empty queues
356 public function getQueuesWithJobs() {
358 foreach ( $this->getCoalescedQueues() as $info ) {
359 /** @var JobQueue $queue */
360 $queue = $info['queue'];
361 $nonEmpty = $queue->getSiblingQueuesWithJobs( $this->getQueueTypes() );
362 if ( is_array( $nonEmpty ) ) { // batching features supported
363 $types = array_merge( $types, $nonEmpty );
364 } else { // we have to go through the queues in the bucket one-by-one
365 foreach ( $info['types'] as $type ) {
366 if ( !$this->get( $type )->isEmpty() ) {
377 * Get the size of the queus for a list of job types
379 * @return int[] Map of (job type => size)
381 public function getQueueSizes() {
383 foreach ( $this->getCoalescedQueues() as $info ) {
384 /** @var JobQueue $queue */
385 $queue = $info['queue'];
386 $sizes = $queue->getSiblingQueueSizes( $this->getQueueTypes() );
387 if ( is_array( $sizes ) ) { // batching features supported
388 $sizeMap = $sizeMap +
$sizes;
389 } else { // we have to go through the queues in the bucket one-by-one
390 foreach ( $info['types'] as $type ) {
391 $sizeMap[$type] = $this->get( $type )->getSize();
401 * @phan-return array<string,array{queue:JobQueue,types:array<string,class-string>}>
403 protected function getCoalescedQueues() {
404 global $wgJobTypeConf;
406 if ( $this->coalescedQueues
=== null ) {
407 $this->coalescedQueues
= [];
408 foreach ( $wgJobTypeConf as $type => $conf ) {
409 $queue = JobQueue
::factory(
410 [ 'domain' => $this->domain
, 'type' => 'null' ] +
$conf );
411 $loc = $queue->getCoalesceLocationInternal();
412 if ( !isset( $this->coalescedQueues
[$loc] ) ) {
413 $this->coalescedQueues
[$loc]['queue'] = $queue;
414 $this->coalescedQueues
[$loc]['types'] = [];
416 if ( $type === 'default' ) {
417 $this->coalescedQueues
[$loc]['types'] = array_merge(
418 $this->coalescedQueues
[$loc]['types'],
419 array_diff( $this->getQueueTypes(), array_keys( $wgJobTypeConf ) )
422 $this->coalescedQueues
[$loc]['types'][] = $type;
427 return $this->coalescedQueues
;
431 * @param string $name
434 private function getCachedConfigVar( $name ) {
435 // @TODO: cleanup this whole method with a proper config system
436 if ( WikiMap
::isCurrentWikiDbDomain( $this->domain
) ) {
437 return $GLOBALS[$name]; // common case
439 $wiki = WikiMap
::getWikiIdFromDbDomain( $this->domain
);
440 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
441 $value = $cache->getWithSetCallback(
442 $cache->makeGlobalKey( 'jobqueue', 'configvalue', $this->domain
, $name ),
443 $cache::TTL_DAY +
mt_rand( 0, $cache::TTL_DAY
),
444 function () use ( $wiki, $name ) {
446 // @TODO: use the full domain ID here
447 return [ 'v' => $wgConf->getConfig( $wiki, $name ) ];
449 [ 'pcTTL' => WANObjectCache
::TTL_PROC_LONG
]
458 * @throws InvalidArgumentException
460 private function assertValidJobs( array $jobs ) {
461 foreach ( $jobs as $job ) { // sanity checks
462 if ( !( $job instanceof IJobSpecification
) ) {
463 throw new InvalidArgumentException( "Expected IJobSpecification objects" );