MediaWiki REL1_40
JobQueueGroup.php
Go to the documentation of this file.
1<?php
24
33 protected $cache;
34
36 protected $domain;
38 protected $readOnlyMode;
40 protected $invalidDomain = false;
42 private $jobClasses;
44 private $jobTypeConfiguration;
46 private $jobTypesExcludedFromDefaultQueue;
48 private $statsdDataFactory;
50 private $wanCache;
52 private $globalIdGenerator;
53
56
57 public const TYPE_DEFAULT = 1; // integer; jobs popped by default
58 private const TYPE_ANY = 2; // integer; any job
59
60 public const USE_CACHE = 1; // integer; use process or persistent cache
61
62 private const PROC_CACHE_TTL = 15; // integer; seconds
63
64 private const CACHE_VERSION = 1; // integer; cache version
65
79 public function __construct(
80 $domain,
81 ConfiguredReadOnlyMode $readOnlyMode,
82 bool $invalidDomain,
83 array $jobClasses,
84 array $jobTypeConfiguration,
85 array $jobTypesExcludedFromDefaultQueue,
86 IBufferingStatsdDataFactory $statsdDataFactory,
87 WANObjectCache $wanCache,
88 GlobalIdGenerator $globalIdGenerator
89 ) {
90 $this->domain = $domain;
91 $this->readOnlyMode = $readOnlyMode;
92 $this->cache = new MapCacheLRU( 10 );
93 $this->invalidDomain = $invalidDomain;
94 $this->jobClasses = $jobClasses;
95 $this->jobTypeConfiguration = $jobTypeConfiguration;
96 $this->jobTypesExcludedFromDefaultQueue = $jobTypesExcludedFromDefaultQueue;
97 $this->statsdDataFactory = $statsdDataFactory;
98 $this->wanCache = $wanCache;
99 $this->globalIdGenerator = $globalIdGenerator;
100 }
101
108 public function get( $type ) {
109 $conf = [ 'domain' => $this->domain, 'type' => $type ];
110 $conf += $this->jobTypeConfiguration[$type] ?? $this->jobTypeConfiguration['default'];
111 if ( !isset( $conf['readOnlyReason'] ) ) {
112 $conf['readOnlyReason'] = $this->readOnlyMode->getReason();
113 }
114
115 $conf['stats'] = $this->statsdDataFactory;
116 $conf['wanCache'] = $this->wanCache;
117 $conf['idGenerator'] = $this->globalIdGenerator;
118
119 return JobQueue::factory( $conf );
120 }
121
132 public function push( $jobs ) {
133 if ( $this->invalidDomain ) {
134 // Do not enqueue job that cannot be run (T171371)
135 $e = new LogicException( "Domain '{$this->domain}' is not recognized." );
136 MWExceptionHandler::logException( $e );
137 return;
138 }
139
140 $jobs = is_array( $jobs ) ? $jobs : [ $jobs ];
141 if ( $jobs === [] ) {
142 return;
143 }
144
145 $this->assertValidJobs( $jobs );
146
147 $jobsByType = []; // (job type => list of jobs)
148 foreach ( $jobs as $job ) {
149 $type = $job->getType();
150 if ( isset( $this->jobTypeConfiguration[$type] ) ) {
151 $jobsByType[$type][] = $job;
152 } else {
153 if (
154 isset( $this->jobTypeConfiguration['default']['typeAgnostic'] ) &&
155 $this->jobTypeConfiguration['default']['typeAgnostic']
156 ) {
157 $jobsByType['default'][] = $job;
158 } else {
159 $jobsByType[$type][] = $job;
160 }
161 }
162 }
163
164 foreach ( $jobsByType as $type => $jobs ) {
165 $this->get( $type )->push( $jobs );
166 }
167
168 if ( $this->cache->hasField( 'queues-ready', 'list' ) ) {
169 $list = $this->cache->getField( 'queues-ready', 'list' );
170 if ( count( array_diff( array_keys( $jobsByType ), $list ) ) ) {
171 $this->cache->clear( 'queues-ready' );
172 }
173 }
174
175 $cache = ObjectCache::getLocalClusterInstance();
176 $cache->set(
177 $cache->makeGlobalKey( 'jobqueue', $this->domain, 'hasjobs', self::TYPE_ANY ),
178 'true',
179 15
180 );
181 if ( array_diff( array_keys( $jobsByType ), $this->jobTypesExcludedFromDefaultQueue ) ) {
182 $cache->set(
183 $cache->makeGlobalKey( 'jobqueue', $this->domain, 'hasjobs', self::TYPE_DEFAULT ),
184 'true',
185 15
186 );
187 }
188 }
189
197 public function lazyPush( $jobs ) {
198 if ( $this->invalidDomain ) {
199 // Do not enqueue job that cannot be run (T171371)
200 throw new LogicException( "Domain '{$this->domain}' is not recognized." );
201 }
202
203 if ( PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg' ) {
204 $this->push( $jobs );
205 return;
206 }
207
208 $jobs = is_array( $jobs ) ? $jobs : [ $jobs ];
209
210 // Throw errors now instead of on push(), when other jobs may be buffered
211 $this->assertValidJobs( $jobs );
212
213 DeferredUpdates::addUpdate( new JobQueueEnqueueUpdate( $this->domain, $jobs ) );
214 }
215
227 public function pop( $qtype = self::TYPE_DEFAULT, $flags = 0, array $ignored = [] ) {
228 $job = false;
229
230 if ( !WikiMap::isCurrentWikiDbDomain( $this->domain ) ) {
231 throw new JobQueueError(
232 "Cannot pop '{$qtype}' job off foreign '{$this->domain}' wiki queue." );
233 } elseif ( is_string( $qtype ) && !isset( $this->jobClasses[$qtype] ) ) {
234 // Do not pop jobs if there is no class for the queue type
235 throw new JobQueueError( "Unrecognized job type '$qtype'." );
236 }
237
238 if ( is_string( $qtype ) ) { // specific job type
239 if ( !in_array( $qtype, $ignored ) ) {
240 $job = $this->get( $qtype )->pop();
241 }
242 } else { // any job in the "default" jobs types
243 if ( $flags & self::USE_CACHE ) {
244 if ( !$this->cache->hasField( 'queues-ready', 'list', self::PROC_CACHE_TTL ) ) {
245 $this->cache->setField( 'queues-ready', 'list', $this->getQueuesWithJobs() );
246 }
247 $types = $this->cache->getField( 'queues-ready', 'list' );
248 } else {
249 $types = $this->getQueuesWithJobs();
250 }
251
252 if ( $qtype == self::TYPE_DEFAULT ) {
253 $types = array_intersect( $types, $this->getDefaultQueueTypes() );
254 }
255
256 $types = array_diff( $types, $ignored ); // avoid selected types
257 shuffle( $types ); // avoid starvation
258
259 foreach ( $types as $type ) { // for each queue...
260 $job = $this->get( $type )->pop();
261 if ( $job ) { // found
262 break;
263 } else { // not found
264 $this->cache->clear( 'queues-ready' );
265 }
266 }
267 }
268
269 return $job;
270 }
271
278 public function ack( RunnableJob $job ) {
279 $this->get( $job->getType() )->ack( $job );
280 }
281
291 wfDeprecated( __METHOD__, '1.40' );
292 return true;
293 }
294
302 public function waitForBackups() {
303 // Try to avoid doing this more than once per queue storage medium
304 foreach ( $this->jobTypeConfiguration as $type => $conf ) {
305 $this->get( $type )->waitForBackups();
306 }
307 }
308
314 public function getQueueTypes() {
315 return array_keys( $this->getCachedConfigVar( 'wgJobClasses' ) );
316 }
317
323 public function getDefaultQueueTypes() {
324 return array_diff( $this->getQueueTypes(), $this->jobTypesExcludedFromDefaultQueue );
325 }
326
334 public function queuesHaveJobs( $type = self::TYPE_ANY ) {
335 $cache = ObjectCache::getLocalClusterInstance();
336 $key = $cache->makeGlobalKey( 'jobqueue', $this->domain, 'hasjobs', $type );
337
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() );
343 }
344 $value = count( $queues ) ? 'true' : 'false';
345 $cache->add( $key, $value, 15 );
346 }
347
348 return ( $value === 'true' );
349 }
350
356 public function getQueuesWithJobs() {
357 $types = [];
358 foreach ( $this->getCoalescedQueues() as $info ) {
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() ) {
367 $types[] = $type;
368 }
369 }
370 }
371 }
372
373 return $types;
374 }
375
381 public function getQueueSizes() {
382 $sizeMap = [];
383 foreach ( $this->getCoalescedQueues() as $info ) {
385 $queue = $info['queue'];
386 $sizes = $queue->getSiblingQueueSizes( $this->getQueueTypes() );
387 if ( is_array( $sizes ) ) { // batching features supported
388 $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();
392 }
393 }
394 }
395
396 return $sizeMap;
397 }
398
403 protected function getCoalescedQueues() {
404 if ( $this->coalescedQueues === null ) {
405 $this->coalescedQueues = [];
406 foreach ( $this->jobTypeConfiguration as $type => $conf ) {
407 $conf['domain'] = $this->domain;
408 $conf['type'] = 'null';
409 $conf['stats'] = $this->statsdDataFactory;
410 $conf['wanCache'] = $this->wanCache;
411 $conf['idGenerator'] = $this->globalIdGenerator;
412
413 $queue = JobQueue::factory( $conf );
414 $loc = $queue->getCoalesceLocationInternal();
415 if ( !isset( $this->coalescedQueues[$loc] ) ) {
416 $this->coalescedQueues[$loc]['queue'] = $queue;
417 $this->coalescedQueues[$loc]['types'] = [];
418 }
419 if ( $type === 'default' ) {
420 $this->coalescedQueues[$loc]['types'] = array_merge(
421 $this->coalescedQueues[$loc]['types'],
422 array_diff( $this->getQueueTypes(), array_keys( $this->jobTypeConfiguration ) )
423 );
424 } else {
425 $this->coalescedQueues[$loc]['types'][] = $type;
426 }
427 }
428 }
429
430 return $this->coalescedQueues;
431 }
432
437 private function getCachedConfigVar( $name ) {
438 // @TODO: cleanup this whole method with a proper config system
439 if ( WikiMap::isCurrentWikiDbDomain( $this->domain ) ) {
440 return $GLOBALS[$name]; // common case
441 } else {
442 $wiki = WikiMap::getWikiIdFromDbDomain( $this->domain );
443 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
444 $value = $cache->getWithSetCallback(
445 $cache->makeGlobalKey( 'jobqueue', 'configvalue', $this->domain, $name ),
446 $cache::TTL_DAY + mt_rand( 0, $cache::TTL_DAY ),
447 static function () use ( $wiki, $name ) {
448 global $wgConf;
449 // @TODO: use the full domain ID here
450 return [ 'v' => $wgConf->getConfig( $wiki, $name ) ];
451 },
452 [ 'pcTTL' => WANObjectCache::TTL_PROC_LONG ]
453 );
454
455 return $value['v'];
456 }
457 }
458
463 private function assertValidJobs( array $jobs ) {
464 foreach ( $jobs as $job ) {
465 if ( !( $job instanceof IJobSpecification ) ) {
466 $type = is_object( $job ) ? get_class( $job ) : gettype( $job );
467 throw new InvalidArgumentException( "Expected IJobSpecification objects, got " . $type );
468 }
469 }
470 }
471}
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:141
A read-only mode service which does not depend on LoadBalancer.
Enqueue lazy-pushed jobs that have accumulated from JobQueueGroup.
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)
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.
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.
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:144
Handles a simple LRU key/value map with a maximum number of entries.
set( $key, $value, $rank=self::RANK_TOP)
Set a key/value pair.
get( $key, $maxAge=INF, $default=null)
Get the value for a key.
getWithSetCallback( $key, callable $callback, $rank=self::RANK_TOP, $maxAge=INF)
Get an item with the given key, producing and setting it if not found.
Service locator for MediaWiki core services.
Helper tools for dealing with other locally-hosted wikis.
Definition WikiMap.php:33
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()
if(count( $args)< 1) $job