MediaWiki REL1_39
JobQueueGroup.php
Go to the documentation of this file.
1<?php
25
37 protected static $instances = [];
38
40 protected $cache;
41
43 protected $domain;
45 protected $readOnlyMode;
47 protected $invalidDomain = false;
49 private $jobClasses;
51 private $jobTypeConfiguration;
53 private $jobTypesExcludedFromDefaultQueue;
55 private $statsdDataFactory;
57 private $wanCache;
59 private $globalIdGenerator;
60
63
64 public const TYPE_DEFAULT = 1; // integer; jobs popped by default
65 private const TYPE_ANY = 2; // integer; any job
66
67 public const USE_CACHE = 1; // integer; use process or persistent cache
68
69 private const PROC_CACHE_TTL = 15; // integer; seconds
70
71 private const CACHE_VERSION = 1; // integer; cache version
72
86 public function __construct(
87 $domain,
88 ConfiguredReadOnlyMode $readOnlyMode,
89 bool $invalidDomain,
90 array $jobClasses,
91 array $jobTypeConfiguration,
92 array $jobTypesExcludedFromDefaultQueue,
93 IBufferingStatsdDataFactory $statsdDataFactory,
94 WANObjectCache $wanCache,
95 GlobalIdGenerator $globalIdGenerator
96 ) {
97 $this->domain = $domain;
98 $this->readOnlyMode = $readOnlyMode;
99 $this->cache = new MapCacheLRU( 10 );
100 $this->invalidDomain = $invalidDomain;
101 $this->jobClasses = $jobClasses;
102 $this->jobTypeConfiguration = $jobTypeConfiguration;
103 $this->jobTypesExcludedFromDefaultQueue = $jobTypesExcludedFromDefaultQueue;
104 $this->statsdDataFactory = $statsdDataFactory;
105 $this->wanCache = $wanCache;
106 $this->globalIdGenerator = $globalIdGenerator;
107 }
108
114 public static function singleton( $domain = false ) {
115 wfDeprecated( __METHOD__, '1.37' );
116 return MediaWikiServices::getInstance()->getJobQueueGroupFactory()->makeJobQueueGroup( $domain );
117 }
118
125 public static function destroySingletons() {
126 wfDeprecated( __METHOD__, '1.37' );
127 }
128
135 public function get( $type ) {
136 $conf = [ 'domain' => $this->domain, 'type' => $type ];
137 $conf += $this->jobTypeConfiguration[$type] ?? $this->jobTypeConfiguration['default'];
138 if ( !isset( $conf['readOnlyReason'] ) ) {
139 $conf['readOnlyReason'] = $this->readOnlyMode->getReason();
140 }
141
142 $conf['stats'] = $this->statsdDataFactory;
143 $conf['wanCache'] = $this->wanCache;
144 $conf['idGenerator'] = $this->globalIdGenerator;
145
146 return JobQueue::factory( $conf );
147 }
148
159 public function push( $jobs ) {
160 if ( $this->invalidDomain ) {
161 // Do not enqueue job that cannot be run (T171371)
162 $e = new LogicException( "Domain '{$this->domain}' is not recognized." );
163 MWExceptionHandler::logException( $e );
164 return;
165 }
166
167 $jobs = is_array( $jobs ) ? $jobs : [ $jobs ];
168 if ( $jobs === [] ) {
169 return;
170 }
171
172 $this->assertValidJobs( $jobs );
173
174 $jobsByType = []; // (job type => list of jobs)
175 foreach ( $jobs as $job ) {
176 $type = $job->getType();
177 if ( isset( $this->jobTypeConfiguration[$type] ) ) {
178 $jobsByType[$type][] = $job;
179 } else {
180 if (
181 isset( $this->jobTypeConfiguration['default']['typeAgnostic'] ) &&
182 $this->jobTypeConfiguration['default']['typeAgnostic']
183 ) {
184 $jobsByType['default'][] = $job;
185 } else {
186 $jobsByType[$type][] = $job;
187 }
188 }
189 }
190
191 foreach ( $jobsByType as $type => $jobs ) {
192 $this->get( $type )->push( $jobs );
193 }
194
195 if ( $this->cache->hasField( 'queues-ready', 'list' ) ) {
196 $list = $this->cache->getField( 'queues-ready', 'list' );
197 if ( count( array_diff( array_keys( $jobsByType ), $list ) ) ) {
198 $this->cache->clear( 'queues-ready' );
199 }
200 }
201
202 $cache = ObjectCache::getLocalClusterInstance();
203 $cache->set(
204 $cache->makeGlobalKey( 'jobqueue', $this->domain, 'hasjobs', self::TYPE_ANY ),
205 'true',
206 15
207 );
208 if ( array_diff( array_keys( $jobsByType ), $this->jobTypesExcludedFromDefaultQueue ) ) {
209 $cache->set(
210 $cache->makeGlobalKey( 'jobqueue', $this->domain, 'hasjobs', self::TYPE_DEFAULT ),
211 'true',
212 15
213 );
214 }
215 }
216
224 public function lazyPush( $jobs ) {
225 if ( $this->invalidDomain ) {
226 // Do not enqueue job that cannot be run (T171371)
227 throw new LogicException( "Domain '{$this->domain}' is not recognized." );
228 }
229
230 if ( PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg' ) {
231 $this->push( $jobs );
232 return;
233 }
234
235 $jobs = is_array( $jobs ) ? $jobs : [ $jobs ];
236
237 // Throw errors now instead of on push(), when other jobs may be buffered
238 $this->assertValidJobs( $jobs );
239
240 DeferredUpdates::addUpdate( new JobQueueEnqueueUpdate( $this->domain, $jobs ) );
241 }
242
254 public function pop( $qtype = self::TYPE_DEFAULT, $flags = 0, array $ignored = [] ) {
255 $job = false;
256
257 if ( !WikiMap::isCurrentWikiDbDomain( $this->domain ) ) {
258 throw new JobQueueError(
259 "Cannot pop '{$qtype}' job off foreign '{$this->domain}' wiki queue." );
260 } elseif ( is_string( $qtype ) && !isset( $this->jobClasses[$qtype] ) ) {
261 // Do not pop jobs if there is no class for the queue type
262 throw new JobQueueError( "Unrecognized job type '$qtype'." );
263 }
264
265 if ( is_string( $qtype ) ) { // specific job type
266 if ( !in_array( $qtype, $ignored ) ) {
267 $job = $this->get( $qtype )->pop();
268 }
269 } else { // any job in the "default" jobs types
270 if ( $flags & self::USE_CACHE ) {
271 if ( !$this->cache->hasField( 'queues-ready', 'list', self::PROC_CACHE_TTL ) ) {
272 $this->cache->setField( 'queues-ready', 'list', $this->getQueuesWithJobs() );
273 }
274 $types = $this->cache->getField( 'queues-ready', 'list' );
275 } else {
276 $types = $this->getQueuesWithJobs();
277 }
278
279 if ( $qtype == self::TYPE_DEFAULT ) {
280 $types = array_intersect( $types, $this->getDefaultQueueTypes() );
281 }
282
283 $types = array_diff( $types, $ignored ); // avoid selected types
284 shuffle( $types ); // avoid starvation
285
286 foreach ( $types as $type ) { // for each queue...
287 $job = $this->get( $type )->pop();
288 if ( $job ) { // found
289 break;
290 } else { // not found
291 $this->cache->clear( 'queues-ready' );
292 }
293 }
294 }
295
296 return $job;
297 }
298
305 public function ack( RunnableJob $job ) {
306 $this->get( $job->getType() )->ack( $job );
307 }
308
317 return $this->get( $job->getType() )->deduplicateRootJob( $job );
318 }
319
327 public function waitForBackups() {
328 // Try to avoid doing this more than once per queue storage medium
329 foreach ( $this->jobTypeConfiguration as $type => $conf ) {
330 $this->get( $type )->waitForBackups();
331 }
332 }
333
339 public function getQueueTypes() {
340 return array_keys( $this->getCachedConfigVar( 'wgJobClasses' ) );
341 }
342
348 public function getDefaultQueueTypes() {
349 return array_diff( $this->getQueueTypes(), $this->jobTypesExcludedFromDefaultQueue );
350 }
351
359 public function queuesHaveJobs( $type = self::TYPE_ANY ) {
360 $cache = ObjectCache::getLocalClusterInstance();
361 $key = $cache->makeGlobalKey( 'jobqueue', $this->domain, 'hasjobs', $type );
362
363 $value = $cache->get( $key );
364 if ( $value === false ) {
365 $queues = $this->getQueuesWithJobs();
366 if ( $type == self::TYPE_DEFAULT ) {
367 $queues = array_intersect( $queues, $this->getDefaultQueueTypes() );
368 }
369 $value = count( $queues ) ? 'true' : 'false';
370 $cache->add( $key, $value, 15 );
371 }
372
373 return ( $value === 'true' );
374 }
375
381 public function getQueuesWithJobs() {
382 $types = [];
383 foreach ( $this->getCoalescedQueues() as $info ) {
385 $queue = $info['queue'];
386 $nonEmpty = $queue->getSiblingQueuesWithJobs( $this->getQueueTypes() );
387 if ( is_array( $nonEmpty ) ) { // batching features supported
388 $types = array_merge( $types, $nonEmpty );
389 } else { // we have to go through the queues in the bucket one-by-one
390 foreach ( $info['types'] as $type ) {
391 if ( !$this->get( $type )->isEmpty() ) {
392 $types[] = $type;
393 }
394 }
395 }
396 }
397
398 return $types;
399 }
400
406 public function getQueueSizes() {
407 $sizeMap = [];
408 foreach ( $this->getCoalescedQueues() as $info ) {
410 $queue = $info['queue'];
411 $sizes = $queue->getSiblingQueueSizes( $this->getQueueTypes() );
412 if ( is_array( $sizes ) ) { // batching features supported
413 $sizeMap += $sizes;
414 } else { // we have to go through the queues in the bucket one-by-one
415 foreach ( $info['types'] as $type ) {
416 $sizeMap[$type] = $this->get( $type )->getSize();
417 }
418 }
419 }
420
421 return $sizeMap;
422 }
423
428 protected function getCoalescedQueues() {
429 if ( $this->coalescedQueues === null ) {
430 $this->coalescedQueues = [];
431 foreach ( $this->jobTypeConfiguration as $type => $conf ) {
432 $conf['domain'] = $this->domain;
433 $conf['type'] = 'null';
434 $conf['stats'] = $this->statsdDataFactory;
435 $conf['wanCache'] = $this->wanCache;
436 $conf['idGenerator'] = $this->globalIdGenerator;
437
438 $queue = JobQueue::factory( $conf );
439 $loc = $queue->getCoalesceLocationInternal();
440 if ( !isset( $this->coalescedQueues[$loc] ) ) {
441 $this->coalescedQueues[$loc]['queue'] = $queue;
442 $this->coalescedQueues[$loc]['types'] = [];
443 }
444 if ( $type === 'default' ) {
445 $this->coalescedQueues[$loc]['types'] = array_merge(
446 $this->coalescedQueues[$loc]['types'],
447 array_diff( $this->getQueueTypes(), array_keys( $this->jobTypeConfiguration ) )
448 );
449 } else {
450 $this->coalescedQueues[$loc]['types'][] = $type;
451 }
452 }
453 }
454
455 return $this->coalescedQueues;
456 }
457
462 private function getCachedConfigVar( $name ) {
463 // @TODO: cleanup this whole method with a proper config system
464 if ( WikiMap::isCurrentWikiDbDomain( $this->domain ) ) {
465 return $GLOBALS[$name]; // common case
466 } else {
467 $wiki = WikiMap::getWikiIdFromDbDomain( $this->domain );
468 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
469 $value = $cache->getWithSetCallback(
470 $cache->makeGlobalKey( 'jobqueue', 'configvalue', $this->domain, $name ),
471 $cache::TTL_DAY + mt_rand( 0, $cache::TTL_DAY ),
472 static function () use ( $wiki, $name ) {
473 global $wgConf;
474 // @TODO: use the full domain ID here
475 return [ 'v' => $wgConf->getConfig( $wiki, $name ) ];
476 },
477 [ 'pcTTL' => WANObjectCache::TTL_PROC_LONG ]
478 );
479
480 return $value['v'];
481 }
482 }
483
488 private function assertValidJobs( array $jobs ) {
489 foreach ( $jobs as $job ) {
490 if ( !( $job instanceof IJobSpecification ) ) {
491 $type = is_object( $job ) ? get_class( $job ) : gettype( $job );
492 throw new InvalidArgumentException( "Expected IJobSpecification objects, got " . $type );
493 }
494 }
495 }
496}
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Logs a warning that a deprecated feature was used.
$wgConf
$wgConf hold the site configuration.
Definition Setup.php:139
A read-only mode service which does not depend on LoadBalancer.
Enqueue lazy-pushed jobs that have accumulated from JobQueueGroup.
Class to handle enqueueing of background jobs.
push( $jobs)
Insert jobs into the respective queues of which they belong.
string $domain
Wiki domain ID.
getQueueSizes()
Get the size of the queues for a list of job types.
__construct( $domain, ConfiguredReadOnlyMode $readOnlyMode, bool $invalidDomain, array $jobClasses, array $jobTypeConfiguration, array $jobTypesExcludedFromDefaultQueue, IBufferingStatsdDataFactory $statsdDataFactory, WANObjectCache $wanCache, GlobalIdGenerator $globalIdGenerator)
waitForBackups()
Wait for any replica DBs or backup queue servers to catch up.
array $coalescedQueues
Map of (bucket => (queue => JobQueue, types => list of types)
static singleton( $domain=false)
getDefaultQueueTypes()
Get the list of default queue types.
lazyPush( $jobs)
Buffer jobs for insertion via push() or call it now if in CLI mode.
pop( $qtype=self::TYPE_DEFAULT, $flags=0, array $ignored=[])
Pop a job off one of the job queues.
ack(RunnableJob $job)
Acknowledge that a job was completed.
static destroySingletons()
Destroy the singleton instances.
ConfiguredReadOnlyMode $readOnlyMode
Read only mode.
queuesHaveJobs( $type=self::TYPE_ANY)
Check if there are any queues with jobs (this is cached)
bool $invalidDomain
Whether the wiki is not recognized in configuration.
static JobQueueGroup[] $instances
MapCacheLRU $cache
getQueuesWithJobs()
Get the list of job types that have non-empty queues.
getQueueTypes()
Get the list of queue types.
deduplicateRootJob(RunnableJob $job)
Register the "root job" of a given job into the queue for de-duplication.
static factory(array $params)
Get a job queue object of the specified type.
Definition JobQueue.php:137
Handles a simple LRU key/value map with a maximum number of entries.
Service locator for MediaWiki core services.
Multi-datacenter aware caching interface.
static getWikiIdFromDbDomain( $domain)
Get the wiki ID of a database domain.
Definition WikiMap.php:269
Class for getting statistically unique IDs without a central coordinator.
MediaWiki adaptation of StatsdDataFactory that provides buffering functionality.
Interface for serializable objects that describe a job queue task.
Job that has a run() method and metadata accessors for JobQueue::pop() and JobQueue::ack()
$cache
Definition mcc.php:33
if(count( $args)< 1) $job