MediaWiki REL1_37
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;
57 private $wanCache;
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 return MediaWikiServices::getInstance()->getJobQueueGroupFactory()->makeJobQueueGroup( $domain );
116 }
117
124 public static function destroySingletons() {
125 }
126
133 public function get( $type ) {
134 $conf = [ 'domain' => $this->domain, 'type' => $type ];
135 if ( isset( $this->jobTypeConfiguration[$type] ) ) {
136 $conf += $this->jobTypeConfiguration[$type];
137 } else {
138 $conf += $this->jobTypeConfiguration['default'];
139 }
140 if ( !isset( $conf['readOnlyReason'] ) ) {
141 $conf['readOnlyReason'] = $this->readOnlyMode->getReason();
142 }
143
144 $conf['stats'] = $this->statsdDataFactory;
145 $conf['wanCache'] = $this->wanCache;
146 $conf['idGenerator'] = $this->globalIdGenerator;
147
148 return JobQueue::factory( $conf );
149 }
150
161 public function push( $jobs ) {
162 if ( $this->invalidDomain ) {
163 // Do not enqueue job that cannot be run (T171371)
164 $e = new LogicException( "Domain '{$this->domain}' is not recognized." );
165 MWExceptionHandler::logException( $e );
166 return;
167 }
168
169 $jobs = is_array( $jobs ) ? $jobs : [ $jobs ];
170 if ( $jobs === [] ) {
171 return;
172 }
173
174 $this->assertValidJobs( $jobs );
175
176 $jobsByType = []; // (job type => list of jobs)
177 foreach ( $jobs as $job ) {
178 $jobsByType[$job->getType()][] = $job;
179 }
180
181 foreach ( $jobsByType as $type => $jobs ) {
182 $this->get( $type )->push( $jobs );
183 }
184
185 if ( $this->cache->hasField( 'queues-ready', 'list' ) ) {
186 $list = $this->cache->getField( 'queues-ready', 'list' );
187 if ( count( array_diff( array_keys( $jobsByType ), $list ) ) ) {
188 $this->cache->clear( 'queues-ready' );
189 }
190 }
191
192 $cache = ObjectCache::getLocalClusterInstance();
193 $cache->set(
194 $cache->makeGlobalKey( 'jobqueue', $this->domain, 'hasjobs', self::TYPE_ANY ),
195 'true',
196 15
197 );
198 if ( array_diff( array_keys( $jobsByType ), $this->jobTypesExcludedFromDefaultQueue ) ) {
199 $cache->set(
200 $cache->makeGlobalKey( 'jobqueue', $this->domain, 'hasjobs', self::TYPE_DEFAULT ),
201 'true',
202 15
203 );
204 }
205 }
206
214 public function lazyPush( $jobs ) {
215 if ( $this->invalidDomain ) {
216 // Do not enqueue job that cannot be run (T171371)
217 throw new LogicException( "Domain '{$this->domain}' is not recognized." );
218 }
219
220 if ( PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg' ) {
221 $this->push( $jobs );
222 return;
223 }
224
225 $jobs = is_array( $jobs ) ? $jobs : [ $jobs ];
226
227 // Throw errors now instead of on push(), when other jobs may be buffered
228 $this->assertValidJobs( $jobs );
229
230 DeferredUpdates::addUpdate( new JobQueueEnqueueUpdate( $this->domain, $jobs ) );
231 }
232
244 public function pop( $qtype = self::TYPE_DEFAULT, $flags = 0, array $ignored = [] ) {
245 $job = false;
246
247 if ( !WikiMap::isCurrentWikiDbDomain( $this->domain ) ) {
248 throw new JobQueueError(
249 "Cannot pop '{$qtype}' job off foreign '{$this->domain}' wiki queue." );
250 } elseif ( is_string( $qtype ) && !isset( $this->jobClasses[$qtype] ) ) {
251 // Do not pop jobs if there is no class for the queue type
252 throw new JobQueueError( "Unrecognized job type '$qtype'." );
253 }
254
255 if ( is_string( $qtype ) ) { // specific job type
256 if ( !in_array( $qtype, $ignored ) ) {
257 $job = $this->get( $qtype )->pop();
258 }
259 } else { // any job in the "default" jobs types
260 if ( $flags & self::USE_CACHE ) {
261 if ( !$this->cache->hasField( 'queues-ready', 'list', self::PROC_CACHE_TTL ) ) {
262 $this->cache->setField( 'queues-ready', 'list', $this->getQueuesWithJobs() );
263 }
264 $types = $this->cache->getField( 'queues-ready', 'list' );
265 } else {
266 $types = $this->getQueuesWithJobs();
267 }
268
269 if ( $qtype == self::TYPE_DEFAULT ) {
270 $types = array_intersect( $types, $this->getDefaultQueueTypes() );
271 }
272
273 $types = array_diff( $types, $ignored ); // avoid selected types
274 shuffle( $types ); // avoid starvation
275
276 foreach ( $types as $type ) { // for each queue...
277 $job = $this->get( $type )->pop();
278 if ( $job ) { // found
279 break;
280 } else { // not found
281 $this->cache->clear( 'queues-ready' );
282 }
283 }
284 }
285
286 return $job;
287 }
288
295 public function ack( RunnableJob $job ) {
296 $this->get( $job->getType() )->ack( $job );
297 }
298
307 return $this->get( $job->getType() )->deduplicateRootJob( $job );
308 }
309
317 public function waitForBackups() {
318 // Try to avoid doing this more than once per queue storage medium
319 foreach ( $this->jobTypeConfiguration as $type => $conf ) {
320 $this->get( $type )->waitForBackups();
321 }
322 }
323
329 public function getQueueTypes() {
330 return array_keys( $this->getCachedConfigVar( 'wgJobClasses' ) );
331 }
332
338 public function getDefaultQueueTypes() {
339 return array_diff( $this->getQueueTypes(), $this->jobTypesExcludedFromDefaultQueue );
340 }
341
349 public function queuesHaveJobs( $type = self::TYPE_ANY ) {
350 $cache = ObjectCache::getLocalClusterInstance();
351 $key = $cache->makeGlobalKey( 'jobqueue', $this->domain, 'hasjobs', $type );
352
353 $value = $cache->get( $key );
354 if ( $value === false ) {
355 $queues = $this->getQueuesWithJobs();
356 if ( $type == self::TYPE_DEFAULT ) {
357 $queues = array_intersect( $queues, $this->getDefaultQueueTypes() );
358 }
359 $value = count( $queues ) ? 'true' : 'false';
360 $cache->add( $key, $value, 15 );
361 }
362
363 return ( $value === 'true' );
364 }
365
371 public function getQueuesWithJobs() {
372 $types = [];
373 foreach ( $this->getCoalescedQueues() as $info ) {
375 $queue = $info['queue'];
376 $nonEmpty = $queue->getSiblingQueuesWithJobs( $this->getQueueTypes() );
377 if ( is_array( $nonEmpty ) ) { // batching features supported
378 $types = array_merge( $types, $nonEmpty );
379 } else { // we have to go through the queues in the bucket one-by-one
380 foreach ( $info['types'] as $type ) {
381 if ( !$this->get( $type )->isEmpty() ) {
382 $types[] = $type;
383 }
384 }
385 }
386 }
387
388 return $types;
389 }
390
396 public function getQueueSizes() {
397 $sizeMap = [];
398 foreach ( $this->getCoalescedQueues() as $info ) {
400 $queue = $info['queue'];
401 $sizes = $queue->getSiblingQueueSizes( $this->getQueueTypes() );
402 if ( is_array( $sizes ) ) { // batching features supported
403 $sizeMap += $sizes;
404 } else { // we have to go through the queues in the bucket one-by-one
405 foreach ( $info['types'] as $type ) {
406 $sizeMap[$type] = $this->get( $type )->getSize();
407 }
408 }
409 }
410
411 return $sizeMap;
412 }
413
418 protected function getCoalescedQueues() {
419 if ( $this->coalescedQueues === null ) {
420 $this->coalescedQueues = [];
421 foreach ( $this->jobTypeConfiguration as $type => $conf ) {
422 $conf['domain'] = $this->domain;
423 $conf['type'] = 'null';
424 $conf['stats'] = $this->statsdDataFactory;
425 $conf['wanCache'] = $this->wanCache;
426 $conf['idGenerator'] = $this->globalIdGenerator;
427
428 $queue = JobQueue::factory( $conf );
429 $loc = $queue->getCoalesceLocationInternal();
430 if ( !isset( $this->coalescedQueues[$loc] ) ) {
431 $this->coalescedQueues[$loc]['queue'] = $queue;
432 $this->coalescedQueues[$loc]['types'] = [];
433 }
434 if ( $type === 'default' ) {
435 $this->coalescedQueues[$loc]['types'] = array_merge(
436 $this->coalescedQueues[$loc]['types'],
437 array_diff( $this->getQueueTypes(), array_keys( $this->jobTypeConfiguration ) )
438 );
439 } else {
440 $this->coalescedQueues[$loc]['types'][] = $type;
441 }
442 }
443 }
444
445 return $this->coalescedQueues;
446 }
447
452 private function getCachedConfigVar( $name ) {
453 // @TODO: cleanup this whole method with a proper config system
454 if ( WikiMap::isCurrentWikiDbDomain( $this->domain ) ) {
455 return $GLOBALS[$name]; // common case
456 } else {
457 $wiki = WikiMap::getWikiIdFromDbDomain( $this->domain );
458 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
459 $value = $cache->getWithSetCallback(
460 $cache->makeGlobalKey( 'jobqueue', 'configvalue', $this->domain, $name ),
461 $cache::TTL_DAY + mt_rand( 0, $cache::TTL_DAY ),
462 static function () use ( $wiki, $name ) {
463 global $wgConf;
464 // @TODO: use the full domain ID here
465 return [ 'v' => $wgConf->getConfig( $wiki, $name ) ];
466 },
467 [ 'pcTTL' => WANObjectCache::TTL_PROC_LONG ]
468 );
469
470 return $value['v'];
471 }
472 }
473
478 private function assertValidJobs( array $jobs ) {
479 foreach ( $jobs as $job ) { // sanity checks
480 if ( !( $job instanceof IJobSpecification ) ) {
481 $type = is_object( $job ) ? get_class( $job ) : gettype( $job );
482 throw new InvalidArgumentException( "Expected IJobSpecification objects, got " . $type );
483 }
484 }
485 }
486}
$wgConf
$wgConf hold the site configuration.
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.
getCachedConfigVar( $name)
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.
WANObjectCache $wanCache
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.
GlobalIdGenerator $globalIdGenerator
static JobQueueGroup[] $instances
array $jobTypesExcludedFromDefaultQueue
MapCacheLRU $cache
getQueuesWithJobs()
Get the list of job types that have non-empty queues.
assertValidJobs(array $jobs)
getQueueTypes()
Get the list of queue types.
IBufferingStatsdDataFactory $statsdDataFactory
deduplicateRootJob(RunnableJob $job)
Register the "root job" of a given job into the queue for de-duplication.
array $jobTypeConfiguration
static factory(array $params)
Get a job queue object of the specified type.
Definition JobQueue.php:125
Handles a simple LRU key/value map with a maximum number of entries.
MediaWikiServices is the service locator for the application scope of MediaWiki.
Multi-datacenter aware caching interface.
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