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;
40 /** @var bool Whether the wiki is not recognized in configuration */
41 protected $invalidWiki = false;
43 /** @var array Map of (bucket => (queue => JobQueue, types => list of types) */
44 protected $coalescedQueues;
47 protected $bufferedJobs = [];
49 const TYPE_DEFAULT
= 1; // integer; jobs popped by default
50 const TYPE_ANY
= 2; // integer; any job
52 const USE_CACHE
= 1; // integer; use process or persistent cache
54 const PROC_CACHE_TTL
= 15; // integer; seconds
56 const CACHE_VERSION
= 1; // integer; cache version
59 * @param string $wiki Wiki ID
60 * @param string|bool $readOnlyReason Read-only reason or false
62 protected function __construct( $wiki, $readOnlyReason ) {
64 $this->readOnlyReason
= $readOnlyReason;
65 $this->cache
= new MapCacheLRU( 10 );
69 * @param bool|string $wiki Wiki ID
70 * @return JobQueueGroup
72 public static function singleton( $wiki = false ) {
73 global $wgLocalDatabases;
75 $wiki = ( $wiki === false ) ?
wfWikiID() : $wiki;
77 if ( !isset( self
::$instances[$wiki] ) ) {
78 self
::$instances[$wiki] = new self( $wiki, 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 if ( $wiki !== wfWikiID() && !in_array( $wiki, $wgLocalDatabases ) ) {
82 self
::$instances[$wiki]->invalidWiki
= true;
86 return self
::$instances[$wiki];
90 * Destroy the singleton instances
94 public static function destroySingletons() {
95 self
::$instances = [];
99 * Get the job queue object for a given queue type
101 * @param string $type
104 public function get( $type ) {
105 global $wgJobTypeConf;
107 $conf = [ 'wiki' => $this->wiki
, 'type' => $type ];
108 $conf +
= $wgJobTypeConf[$type] ??
$wgJobTypeConf['default'];
109 $conf['aggregator'] = JobQueueAggregator
::singleton();
110 if ( !isset( $conf['readOnlyReason'] ) ) {
111 $conf['readOnlyReason'] = $this->readOnlyReason
;
114 return JobQueue
::factory( $conf );
118 * Insert jobs into the respective queues of which they belong
120 * This inserts the jobs into the queue specified by $wgJobTypeConf
121 * and updates the aggregate job queue information cache as needed.
123 * @param IJobSpecification|IJobSpecification[] $jobs A single Job or a list of Jobs
124 * @throws InvalidArgumentException
127 public function push( $jobs ) {
128 global $wgJobTypesExcludedFromDefaultQueue;
130 if ( $this->invalidWiki
) {
131 // Do not enqueue job that cannot be run (T171371)
132 $e = new LogicException( "Domain '{$this->wiki}' is not recognized." );
133 MWExceptionHandler
::logException( $e );
137 $jobs = is_array( $jobs ) ?
$jobs : [ $jobs ];
138 if ( !count( $jobs ) ) {
142 $this->assertValidJobs( $jobs );
144 $jobsByType = []; // (job type => list of jobs)
145 foreach ( $jobs as $job ) {
146 $jobsByType[$job->getType()][] = $job;
149 foreach ( $jobsByType as $type => $jobs ) {
150 $this->get( $type )->push( $jobs );
153 if ( $this->cache
->hasField( 'queues-ready', 'list' ) ) {
154 $list = $this->cache
->getField( 'queues-ready', 'list' );
155 if ( count( array_diff( array_keys( $jobsByType ), $list ) ) ) {
156 $this->cache
->clear( 'queues-ready' );
160 $cache = ObjectCache
::getLocalClusterInstance();
162 $cache->makeGlobalKey( 'jobqueue', $this->wiki
, 'hasjobs', self
::TYPE_ANY
),
166 if ( array_diff( array_keys( $jobsByType ), $wgJobTypesExcludedFromDefaultQueue ) ) {
168 $cache->makeGlobalKey( 'jobqueue', $this->wiki
, 'hasjobs', self
::TYPE_DEFAULT
),
176 * Buffer jobs for insertion via push() or call it now if in CLI mode
178 * Note that pushLazyJobs() is registered as a deferred update just before
179 * DeferredUpdates::doUpdates() in MediaWiki and JobRunner classes in order
180 * to be executed as the very last deferred update (T100085, T154425).
182 * @param IJobSpecification|IJobSpecification[] $jobs A single Job or a list of Jobs
186 public function lazyPush( $jobs ) {
187 if ( $this->invalidWiki
) {
188 // Do not enqueue job that cannot be run (T171371)
189 throw new LogicException( "Domain '{$this->wiki}' is not recognized." );
192 if ( PHP_SAPI
=== 'cli' || PHP_SAPI
=== 'phpdbg' ) {
193 $this->push( $jobs );
197 $jobs = is_array( $jobs ) ?
$jobs : [ $jobs ];
199 // Throw errors now instead of on push(), when other jobs may be buffered
200 $this->assertValidJobs( $jobs );
202 $this->bufferedJobs
= array_merge( $this->bufferedJobs
, $jobs );
206 * Push all jobs buffered via lazyPush() into their respective queues
211 public static function pushLazyJobs() {
212 foreach ( self
::$instances as $group ) {
214 $group->push( $group->bufferedJobs
);
215 $group->bufferedJobs
= [];
216 } catch ( Exception
$e ) {
217 // Get in as many jobs as possible and let other post-send updates happen
218 MWExceptionHandler
::logException( $e );
224 * Pop a job off one of the job queues
226 * This pops a job off a queue as specified by $wgJobTypeConf and
227 * updates the aggregate job queue information cache as needed.
229 * @param int|string $qtype JobQueueGroup::TYPE_* constant or job type string
230 * @param int $flags Bitfield of JobQueueGroup::USE_* constants
231 * @param array $blacklist List of job types to ignore
232 * @return Job|bool Returns false on failure
234 public function pop( $qtype = self
::TYPE_DEFAULT
, $flags = 0, array $blacklist = [] ) {
237 if ( is_string( $qtype ) ) { // specific job type
238 if ( !in_array( $qtype, $blacklist ) ) {
239 $job = $this->get( $qtype )->pop();
241 } else { // any job in the "default" jobs types
242 if ( $flags & self
::USE_CACHE
) {
243 if ( !$this->cache
->hasField( 'queues-ready', 'list', self
::PROC_CACHE_TTL
) ) {
244 $this->cache
->setField( 'queues-ready', 'list', $this->getQueuesWithJobs() );
246 $types = $this->cache
->getField( 'queues-ready', 'list' );
248 $types = $this->getQueuesWithJobs();
251 if ( $qtype == self
::TYPE_DEFAULT
) {
252 $types = array_intersect( $types, $this->getDefaultQueueTypes() );
255 $types = array_diff( $types, $blacklist ); // avoid selected types
256 shuffle( $types ); // avoid starvation
258 foreach ( $types as $type ) { // for each queue...
259 $job = $this->get( $type )->pop();
260 if ( $job ) { // found
262 } else { // not found
263 $this->cache
->clear( 'queues-ready' );
272 * Acknowledge that a job was completed
277 public function ack( Job
$job ) {
278 $this->get( $job->getType() )->ack( $job );
282 * Register the "root job" of a given job into the queue for de-duplication.
283 * This should only be called right *after* all the new jobs have been inserted.
288 public function deduplicateRootJob( Job
$job ) {
289 return $this->get( $job->getType() )->deduplicateRootJob( $job );
293 * Wait for any replica DBs or backup queue servers to catch up.
295 * This does nothing for certain queue classes.
299 public function waitForBackups() {
300 global $wgJobTypeConf;
302 // Try to avoid doing this more than once per queue storage medium
303 foreach ( $wgJobTypeConf as $type => $conf ) {
304 $this->get( $type )->waitForBackups();
309 * Get the list of queue types
311 * @return array List of strings
313 public function getQueueTypes() {
314 return array_keys( $this->getCachedConfigVar( 'wgJobClasses' ) );
318 * Get the list of default queue types
320 * @return array List of strings
322 public function getDefaultQueueTypes() {
323 global $wgJobTypesExcludedFromDefaultQueue;
325 return array_diff( $this->getQueueTypes(), $wgJobTypesExcludedFromDefaultQueue );
329 * Check if there are any queues with jobs (this is cached)
331 * @param int $type JobQueueGroup::TYPE_* constant
335 public function queuesHaveJobs( $type = self
::TYPE_ANY
) {
336 $cache = ObjectCache
::getLocalClusterInstance();
337 $key = $cache->makeGlobalKey( 'jobqueue', $this->wiki
, 'hasjobs', $type );
339 $value = $cache->get( $key );
340 if ( $value === false ) {
341 $queues = $this->getQueuesWithJobs();
342 if ( $type == self
::TYPE_DEFAULT
) {
343 $queues = array_intersect( $queues, $this->getDefaultQueueTypes() );
345 $value = count( $queues ) ?
'true' : 'false';
346 $cache->add( $key, $value, 15 );
349 return ( $value === 'true' );
353 * Get the list of job types that have non-empty queues
355 * @return array List of job types that have non-empty queues
357 public function getQueuesWithJobs() {
359 foreach ( $this->getCoalescedQueues() as $info ) {
360 $nonEmpty = $info['queue']->getSiblingQueuesWithJobs( $this->getQueueTypes() );
361 if ( is_array( $nonEmpty ) ) { // batching features supported
362 $types = array_merge( $types, $nonEmpty );
363 } else { // we have to go through the queues in the bucket one-by-one
364 foreach ( $info['types'] as $type ) {
365 if ( !$this->get( $type )->isEmpty() ) {
376 * Get the size of the queus for a list of job types
378 * @return array Map of (job type => size)
380 public function getQueueSizes() {
382 foreach ( $this->getCoalescedQueues() as $info ) {
383 $sizes = $info['queue']->getSiblingQueueSizes( $this->getQueueTypes() );
384 if ( is_array( $sizes ) ) { // batching features supported
385 $sizeMap = $sizeMap +
$sizes;
386 } else { // we have to go through the queues in the bucket one-by-one
387 foreach ( $info['types'] as $type ) {
388 $sizeMap[$type] = $this->get( $type )->getSize();
399 protected function getCoalescedQueues() {
400 global $wgJobTypeConf;
402 if ( $this->coalescedQueues
=== null ) {
403 $this->coalescedQueues
= [];
404 foreach ( $wgJobTypeConf as $type => $conf ) {
405 $queue = JobQueue
::factory(
406 [ 'wiki' => $this->wiki
, 'type' => 'null' ] +
$conf );
407 $loc = $queue->getCoalesceLocationInternal();
408 if ( !isset( $this->coalescedQueues
[$loc] ) ) {
409 $this->coalescedQueues
[$loc]['queue'] = $queue;
410 $this->coalescedQueues
[$loc]['types'] = [];
412 if ( $type === 'default' ) {
413 $this->coalescedQueues
[$loc]['types'] = array_merge(
414 $this->coalescedQueues
[$loc]['types'],
415 array_diff( $this->getQueueTypes(), array_keys( $wgJobTypeConf ) )
418 $this->coalescedQueues
[$loc]['types'][] = $type;
423 return $this->coalescedQueues
;
427 * @param string $name
430 private function getCachedConfigVar( $name ) {
431 // @TODO: cleanup this whole method with a proper config system
432 if ( $this->wiki
=== wfWikiID() ) {
433 return $GLOBALS[$name]; // common case
436 $cache = ObjectCache
::getMainWANInstance();
437 $value = $cache->getWithSetCallback(
438 $cache->makeGlobalKey( 'jobqueue', 'configvalue', $wiki, $name ),
439 $cache::TTL_DAY +
mt_rand( 0, $cache::TTL_DAY
),
440 function () use ( $wiki, $name ) {
443 return [ 'v' => $wgConf->getConfig( $wiki, $name ) ];
445 [ 'pcTTL' => WANObjectCache
::TTL_PROC_LONG
]
454 * @throws InvalidArgumentException
456 private function assertValidJobs( array $jobs ) {
457 foreach ( $jobs as $job ) { // sanity checks
458 if ( !( $job instanceof IJobSpecification
) ) {
459 throw new InvalidArgumentException( "Expected IJobSpecification objects" );
464 function __destruct() {
465 $n = count( $this->bufferedJobs
);
467 $type = implode( ', ', array_unique( array_map( 'get_class', $this->bufferedJobs
) ) );
468 trigger_error( __METHOD__
. ": $n buffered job(s) of type(s) $type never inserted." );