Localisation updates from https://translatewiki.net.
[mediawiki.git] / includes / jobqueue / JobQueueGroup.php
blob462735710ad0f69c02617dc32c93b5adf7badc55
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
18 * @file
21 use MediaWiki\Deferred\DeferredUpdates;
22 use MediaWiki\Deferred\JobQueueEnqueueUpdate;
23 use MediaWiki\MediaWikiServices;
24 use Wikimedia\ObjectCache\WANObjectCache;
25 use Wikimedia\Rdbms\ReadOnlyMode;
26 use Wikimedia\Stats\IBufferingStatsdDataFactory;
27 use Wikimedia\UUID\GlobalIdGenerator;
29 /**
30 * Handle enqueueing of background jobs.
32 * @warning This service class supports queuing jobs to foreign wikis via JobQueueGroupFactory,
33 * but other operations may be called for the local wiki only. Exceptions may be thrown if you
34 * attempt to inspect, pop, or execute a foreign wiki's job queue.
36 * @since 1.21
37 * @ingroup JobQueue
39 class JobQueueGroup {
40 /** @var MapCacheLRU */
41 protected $cache;
43 /** @var string Wiki domain ID */
44 protected $domain;
45 /** @var ReadOnlyMode Read only mode */
46 protected $readOnlyMode;
47 /** @var array|null */
48 private $localJobClasses;
49 /** @var array */
50 private $jobTypeConfiguration;
51 /** @var array */
52 private $jobTypesExcludedFromDefaultQueue;
53 /** @var IBufferingStatsdDataFactory */
54 private $statsdDataFactory;
55 /** @var WANObjectCache */
56 private $wanCache;
57 /** @var GlobalIdGenerator */
58 private $globalIdGenerator;
60 /** @var array Map of (bucket => (queue => JobQueue, types => list of types) */
61 protected $coalescedQueues;
63 public const TYPE_DEFAULT = 1; // integer; jobs popped by default
64 private const TYPE_ANY = 2; // integer; any job
66 public const USE_CACHE = 1; // integer; use process or persistent cache
68 private const PROC_CACHE_TTL = 15; // integer; seconds
70 /**
71 * @internal Use MediaWikiServices::getJobQueueGroupFactory
73 * @param string $domain Wiki domain ID
74 * @param ReadOnlyMode $readOnlyMode Read-only mode
75 * @param array|null $localJobClasses
76 * @param array $jobTypeConfiguration
77 * @param array $jobTypesExcludedFromDefaultQueue
78 * @param IBufferingStatsdDataFactory $statsdDataFactory
79 * @param WANObjectCache $wanCache
80 * @param GlobalIdGenerator $globalIdGenerator
83 public function __construct(
84 $domain,
85 ReadOnlyMode $readOnlyMode,
86 ?array $localJobClasses,
87 array $jobTypeConfiguration,
88 array $jobTypesExcludedFromDefaultQueue,
89 IBufferingStatsdDataFactory $statsdDataFactory,
90 WANObjectCache $wanCache,
91 GlobalIdGenerator $globalIdGenerator
92 ) {
93 $this->domain = $domain;
94 $this->readOnlyMode = $readOnlyMode;
95 $this->cache = new MapCacheLRU( 10 );
96 $this->localJobClasses = $localJobClasses;
97 $this->jobTypeConfiguration = $jobTypeConfiguration;
98 $this->jobTypesExcludedFromDefaultQueue = $jobTypesExcludedFromDefaultQueue;
99 $this->statsdDataFactory = $statsdDataFactory;
100 $this->wanCache = $wanCache;
101 $this->globalIdGenerator = $globalIdGenerator;
105 * Get the job queue object for a given queue type
107 * @param string $type
108 * @return JobQueue
110 public function get( $type ) {
111 $conf = [ 'domain' => $this->domain, 'type' => $type ];
112 $conf += $this->jobTypeConfiguration[$type] ?? $this->jobTypeConfiguration['default'];
113 if ( !isset( $conf['readOnlyReason'] ) ) {
114 $conf['readOnlyReason'] = $this->readOnlyMode->getConfiguredReason();
117 $conf['stats'] = $this->statsdDataFactory;
118 $conf['wanCache'] = $this->wanCache;
119 $conf['idGenerator'] = $this->globalIdGenerator;
121 return JobQueue::factory( $conf );
125 * Insert jobs into the respective queues of which they belong
127 * This inserts the jobs into the queue specified by $wgJobTypeConf
128 * and updates the aggregate job queue information cache as needed.
130 * @param IJobSpecification|IJobSpecification[] $jobs A single Job or a list of Jobs
131 * @return void
133 public function push( $jobs ) {
134 $jobs = is_array( $jobs ) ? $jobs : [ $jobs ];
135 if ( $jobs === [] ) {
136 return;
139 $this->assertValidJobs( $jobs );
141 $jobsByType = []; // (job type => list of jobs)
142 foreach ( $jobs as $job ) {
143 $type = $job->getType();
144 if ( isset( $this->jobTypeConfiguration[$type] ) ) {
145 $jobsByType[$type][] = $job;
146 } else {
147 if (
148 isset( $this->jobTypeConfiguration['default']['typeAgnostic'] ) &&
149 $this->jobTypeConfiguration['default']['typeAgnostic']
151 $jobsByType['default'][] = $job;
152 } else {
153 $jobsByType[$type][] = $job;
158 foreach ( $jobsByType as $type => $jobs ) {
159 $this->get( $type )->push( $jobs );
162 if ( $this->cache->hasField( 'queues-ready', 'list' ) ) {
163 $list = $this->cache->getField( 'queues-ready', 'list' );
164 if ( count( array_diff( array_keys( $jobsByType ), $list ) ) ) {
165 $this->cache->clear( 'queues-ready' );
169 $cache = MediaWikiServices::getInstance()->getObjectCacheFactory()->getLocalClusterInstance();
170 $cache->set(
171 $cache->makeGlobalKey( 'jobqueue', $this->domain, 'hasjobs', self::TYPE_ANY ),
172 'true',
175 if ( array_diff( array_keys( $jobsByType ), $this->jobTypesExcludedFromDefaultQueue ) ) {
176 $cache->set(
177 $cache->makeGlobalKey( 'jobqueue', $this->domain, 'hasjobs', self::TYPE_DEFAULT ),
178 'true',
185 * Buffer jobs for insertion via push() or call it now if in CLI mode
187 * @param IJobSpecification|IJobSpecification[] $jobs A single Job or a list of Jobs
188 * @return void
189 * @since 1.26
191 public function lazyPush( $jobs ) {
192 if ( PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg' ) {
193 $this->push( $jobs );
194 return;
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 DeferredUpdates::addUpdate( new JobQueueEnqueueUpdate( $this->domain, $jobs ) );
206 * Pop one job off a job queue
208 * @warning May not be called on foreign wikis!
210 * This pops a job off a queue as specified by $wgJobTypeConf and
211 * updates the aggregate job queue information cache as needed.
213 * @param int|string $qtype JobQueueGroup::TYPE_* constant or job type string
214 * @param int $flags Bitfield of JobQueueGroup::USE_* constants
215 * @param array $ignored List of job types to ignore
216 * @return RunnableJob|false Returns false on failure
217 * @throws JobQueueError
219 public function pop( $qtype = self::TYPE_DEFAULT, $flags = 0, array $ignored = [] ) {
220 $job = false;
222 if ( !$this->localJobClasses ) {
223 throw new JobQueueError(
224 "Cannot pop '{$qtype}' job off foreign '{$this->domain}' wiki queue." );
226 if ( is_string( $qtype ) && !isset( $this->localJobClasses[$qtype] ) ) {
227 // Do not pop jobs if there is no class for the queue type
228 throw new JobQueueError( "Unrecognized job type '$qtype'." );
231 if ( is_string( $qtype ) ) { // specific job type
232 if ( !in_array( $qtype, $ignored ) ) {
233 $job = $this->get( $qtype )->pop();
235 } else { // any job in the "default" jobs types
236 if ( $flags & self::USE_CACHE ) {
237 if ( !$this->cache->hasField( 'queues-ready', 'list', self::PROC_CACHE_TTL ) ) {
238 $this->cache->setField( 'queues-ready', 'list', $this->getQueuesWithJobs() );
240 $types = $this->cache->getField( 'queues-ready', 'list' );
241 } else {
242 $types = $this->getQueuesWithJobs();
245 if ( $qtype == self::TYPE_DEFAULT ) {
246 $types = array_intersect( $types, $this->getDefaultQueueTypes() );
249 $types = array_diff( $types, $ignored ); // avoid selected types
250 shuffle( $types ); // avoid starvation
252 foreach ( $types as $type ) { // for each queue...
253 $job = $this->get( $type )->pop();
254 if ( $job ) { // found
255 break;
256 } else { // not found
257 $this->cache->clear( 'queues-ready' );
262 return $job;
266 * Acknowledge that a job was completed
268 * @param RunnableJob $job
269 * @return void
271 public function ack( RunnableJob $job ) {
272 $this->get( $job->getType() )->ack( $job );
276 * Register the "root job" of a given job into the queue for de-duplication.
277 * This should only be called right *after* all the new jobs have been inserted.
279 * @deprecated since 1.40
280 * @param RunnableJob $job
281 * @return bool
283 public function deduplicateRootJob( RunnableJob $job ) {
284 wfDeprecated( __METHOD__, '1.40' );
285 return true;
289 * Wait for any replica DBs or backup queue servers to catch up.
291 * This does nothing for certain queue classes.
293 * @deprecated since 1.41, use JobQueue::waitForBackups() instead.
295 * @return void
297 public function waitForBackups() {
298 wfDeprecated( __METHOD__, '1.41' );
299 // Try to avoid doing this more than once per queue storage medium
300 foreach ( $this->jobTypeConfiguration as $type => $conf ) {
301 $this->get( $type )->waitForBackups();
306 * Get the list of queue types
308 * @warning May not be called on foreign wikis!
310 * @return string[]
312 public function getQueueTypes() {
313 if ( !$this->localJobClasses ) {
314 throw new JobQueueError( 'Cannot inspect job queue from foreign wiki' );
316 return array_keys( $this->localJobClasses );
320 * Get the list of default queue types
322 * @warning May not be called on foreign wikis!
324 * @return string[]
326 public function getDefaultQueueTypes() {
327 return array_diff( $this->getQueueTypes(), $this->jobTypesExcludedFromDefaultQueue );
331 * Check if there are any queues with jobs (this is cached)
333 * @warning May not be called on foreign wikis!
335 * @since 1.23
336 * @param int $type JobQueueGroup::TYPE_* constant
337 * @return bool
339 public function queuesHaveJobs( $type = self::TYPE_ANY ) {
340 $cache = MediaWikiServices::getInstance()->getObjectCacheFactory()->getLocalClusterInstance();
341 $key = $cache->makeGlobalKey( 'jobqueue', $this->domain, 'hasjobs', $type );
343 $value = $cache->get( $key );
344 if ( $value === false ) {
345 $queues = $this->getQueuesWithJobs();
346 if ( $type == self::TYPE_DEFAULT ) {
347 $queues = array_intersect( $queues, $this->getDefaultQueueTypes() );
349 $value = count( $queues ) ? 'true' : 'false';
350 $cache->add( $key, $value, 15 );
353 return ( $value === 'true' );
357 * Get the list of job types that have non-empty queues
359 * @warning May not be called on foreign wikis!
361 * @return string[] List of job types that have non-empty queues
363 public function getQueuesWithJobs() {
364 $types = [];
365 foreach ( $this->getCoalescedQueues() as $info ) {
366 /** @var JobQueue $queue */
367 $queue = $info['queue'];
368 $nonEmpty = $queue->getSiblingQueuesWithJobs( $this->getQueueTypes() );
369 if ( is_array( $nonEmpty ) ) { // batching features supported
370 $types = array_merge( $types, $nonEmpty );
371 } else { // we have to go through the queues in the bucket one-by-one
372 foreach ( $info['types'] as $type ) {
373 if ( !$this->get( $type )->isEmpty() ) {
374 $types[] = $type;
380 return $types;
384 * Get the size of the queues for a list of job types
386 * @warning May not be called on foreign wikis!
388 * @return int[] Map of (job type => size)
390 public function getQueueSizes() {
391 $sizeMap = [];
392 foreach ( $this->getCoalescedQueues() as $info ) {
393 /** @var JobQueue $queue */
394 $queue = $info['queue'];
395 $sizes = $queue->getSiblingQueueSizes( $this->getQueueTypes() );
396 if ( is_array( $sizes ) ) { // batching features supported
397 $sizeMap += $sizes;
398 } else { // we have to go through the queues in the bucket one-by-one
399 foreach ( $info['types'] as $type ) {
400 $sizeMap[$type] = $this->get( $type )->getSize();
405 return $sizeMap;
409 * @return array[]
410 * @phan-return array<string,array{queue:JobQueue,types:array<string,class-string>}>
412 protected function getCoalescedQueues() {
413 if ( $this->coalescedQueues === null ) {
414 $this->coalescedQueues = [];
415 foreach ( $this->jobTypeConfiguration as $type => $conf ) {
416 $conf['domain'] = $this->domain;
417 $conf['type'] = 'null';
418 $conf['stats'] = $this->statsdDataFactory;
419 $conf['wanCache'] = $this->wanCache;
420 $conf['idGenerator'] = $this->globalIdGenerator;
422 $queue = JobQueue::factory( $conf );
423 $loc = $queue->getCoalesceLocationInternal();
424 if ( !isset( $this->coalescedQueues[$loc] ) ) {
425 $this->coalescedQueues[$loc]['queue'] = $queue;
426 $this->coalescedQueues[$loc]['types'] = [];
428 if ( $type === 'default' ) {
429 $this->coalescedQueues[$loc]['types'] = array_merge(
430 $this->coalescedQueues[$loc]['types'],
431 array_diff( $this->getQueueTypes(), array_keys( $this->jobTypeConfiguration ) )
433 } else {
434 $this->coalescedQueues[$loc]['types'][] = $type;
439 return $this->coalescedQueues;
443 * @param array $jobs
445 private function assertValidJobs( array $jobs ) {
446 foreach ( $jobs as $job ) {
447 if ( !( $job instanceof IJobSpecification ) ) {
448 $type = get_debug_type( $job );
449 throw new InvalidArgumentException( "Expected IJobSpecification objects, got " . $type );