MediaWiki REL1_35
JobQueueGroup.php
Go to the documentation of this file.
1<?php
23
32 protected static $instances = [];
33
35 protected $cache;
36
38 protected $domain;
40 protected $readOnlyReason;
42 protected $invalidDomain = false;
43
46
47 public const TYPE_DEFAULT = 1; // integer; jobs popped by default
48 private const TYPE_ANY = 2; // integer; any job
49
50 public const USE_CACHE = 1; // integer; use process or persistent cache
51
52 private const PROC_CACHE_TTL = 15; // integer; seconds
53
54 private const CACHE_VERSION = 1; // integer; cache version
55
60 protected function __construct( $domain, $readOnlyReason ) {
61 $this->domain = $domain;
62 $this->readOnlyReason = $readOnlyReason;
63 $this->cache = new MapCacheLRU( 10 );
64 }
65
70 public static function singleton( $domain = false ) {
71 global $wgLocalDatabases;
72
73 if ( $domain === false ) {
74 $domain = WikiMap::getCurrentWikiDbDomain()->getId();
75 }
76
77 if ( !isset( self::$instances[$domain] ) ) {
78 self::$instances[$domain] = new self( $domain, 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 $wikiId = WikiMap::getWikiIdFromDbDomain( $domain );
82 if (
83 !WikiMap::isCurrentWikiDbDomain( $domain ) &&
84 !in_array( $wikiId, $wgLocalDatabases )
85 ) {
86 self::$instances[$domain]->invalidDomain = true;
87 }
88 }
89
90 return self::$instances[$domain];
91 }
92
98 public static function destroySingletons() {
99 self::$instances = [];
100 }
101
108 public function get( $type ) {
109 global $wgJobTypeConf;
110
111 $conf = [ 'domain' => $this->domain, 'type' => $type ];
112 if ( isset( $wgJobTypeConf[$type] ) ) {
113 $conf += $wgJobTypeConf[$type];
114 } else {
115 $conf += $wgJobTypeConf['default'];
116 }
117 if ( !isset( $conf['readOnlyReason'] ) ) {
118 $conf['readOnlyReason'] = $this->readOnlyReason;
119 }
120
121 return $this->factoryJobQueue( $conf );
122 }
123
129 private function factoryJobQueue( array $conf ) {
130 $services = MediaWikiServices::getInstance();
131 $conf['stats'] = $services->getStatsdDataFactory();
132 $conf['wanCache'] = $services->getMainWANObjectCache();
133 $conf['idGenerator'] = $services->getGlobalIdGenerator();
134
135 return JobQueue::factory( $conf );
136 }
137
148 public function push( $jobs ) {
150
151 if ( $this->invalidDomain ) {
152 // Do not enqueue job that cannot be run (T171371)
153 $e = new LogicException( "Domain '{$this->domain}' is not recognized." );
154 MWExceptionHandler::logException( $e );
155 return;
156 }
157
158 $jobs = is_array( $jobs ) ? $jobs : [ $jobs ];
159 if ( $jobs === [] ) {
160 return;
161 }
162
163 $this->assertValidJobs( $jobs );
164
165 $jobsByType = []; // (job type => list of jobs)
166 foreach ( $jobs as $job ) {
167 $jobsByType[$job->getType()][] = $job;
168 }
169
170 foreach ( $jobsByType as $type => $jobs ) {
171 $this->get( $type )->push( $jobs );
172 }
173
174 if ( $this->cache->hasField( 'queues-ready', 'list' ) ) {
175 $list = $this->cache->getField( 'queues-ready', 'list' );
176 if ( count( array_diff( array_keys( $jobsByType ), $list ) ) ) {
177 $this->cache->clear( 'queues-ready' );
178 }
179 }
180
181 $cache = ObjectCache::getLocalClusterInstance();
182 $cache->set(
183 $cache->makeGlobalKey( 'jobqueue', $this->domain, 'hasjobs', self::TYPE_ANY ),
184 'true',
185 15
186 );
187 if ( array_diff( array_keys( $jobsByType ), $wgJobTypesExcludedFromDefaultQueue ) ) {
188 $cache->set(
189 $cache->makeGlobalKey( 'jobqueue', $this->domain, 'hasjobs', self::TYPE_DEFAULT ),
190 'true',
191 15
192 );
193 }
194 }
195
203 public function lazyPush( $jobs ) {
204 if ( $this->invalidDomain ) {
205 // Do not enqueue job that cannot be run (T171371)
206 throw new LogicException( "Domain '{$this->domain}' is not recognized." );
207 }
208
209 if ( PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg' ) {
210 $this->push( $jobs );
211 return;
212 }
213
214 $jobs = is_array( $jobs ) ? $jobs : [ $jobs ];
215
216 // Throw errors now instead of on push(), when other jobs may be buffered
217 $this->assertValidJobs( $jobs );
218
219 DeferredUpdates::addUpdate( new JobQueueEnqueueUpdate( $this->domain, $jobs ) );
220 }
221
233 public function pop( $qtype = self::TYPE_DEFAULT, $flags = 0, array $blacklist = [] ) {
234 global $wgJobClasses;
235
236 $job = false;
237
238 if ( !WikiMap::isCurrentWikiDbDomain( $this->domain ) ) {
239 throw new JobQueueError(
240 "Cannot pop '{$qtype}' job off foreign '{$this->domain}' wiki queue." );
241 } elseif ( is_string( $qtype ) && !isset( $wgJobClasses[$qtype] ) ) {
242 // Do not pop jobs if there is no class for the queue type
243 throw new JobQueueError( "Unrecognized job type '$qtype'." );
244 }
245
246 if ( is_string( $qtype ) ) { // specific job type
247 if ( !in_array( $qtype, $blacklist ) ) {
248 $job = $this->get( $qtype )->pop();
249 }
250 } else { // any job in the "default" jobs types
251 if ( $flags & self::USE_CACHE ) {
252 if ( !$this->cache->hasField( 'queues-ready', 'list', self::PROC_CACHE_TTL ) ) {
253 $this->cache->setField( 'queues-ready', 'list', $this->getQueuesWithJobs() );
254 }
255 $types = $this->cache->getField( 'queues-ready', 'list' );
256 } else {
257 $types = $this->getQueuesWithJobs();
258 }
259
260 if ( $qtype == self::TYPE_DEFAULT ) {
261 $types = array_intersect( $types, $this->getDefaultQueueTypes() );
262 }
263
264 $types = array_diff( $types, $blacklist ); // avoid selected types
265 shuffle( $types ); // avoid starvation
266
267 foreach ( $types as $type ) { // for each queue...
268 $job = $this->get( $type )->pop();
269 if ( $job ) { // found
270 break;
271 } else { // not found
272 $this->cache->clear( 'queues-ready' );
273 }
274 }
275 }
276
277 return $job;
278 }
279
286 public function ack( RunnableJob $job ) {
287 $this->get( $job->getType() )->ack( $job );
288 }
289
298 return $this->get( $job->getType() )->deduplicateRootJob( $job );
299 }
300
308 public function waitForBackups() {
309 global $wgJobTypeConf;
310
311 // Try to avoid doing this more than once per queue storage medium
312 foreach ( $wgJobTypeConf as $type => $conf ) {
313 $this->get( $type )->waitForBackups();
314 }
315 }
316
322 public function getQueueTypes() {
323 return array_keys( $this->getCachedConfigVar( 'wgJobClasses' ) );
324 }
325
331 public function getDefaultQueueTypes() {
333
334 return array_diff( $this->getQueueTypes(), $wgJobTypesExcludedFromDefaultQueue );
335 }
336
344 public function queuesHaveJobs( $type = self::TYPE_ANY ) {
345 $cache = ObjectCache::getLocalClusterInstance();
346 $key = $cache->makeGlobalKey( 'jobqueue', $this->domain, 'hasjobs', $type );
347
348 $value = $cache->get( $key );
349 if ( $value === false ) {
350 $queues = $this->getQueuesWithJobs();
351 if ( $type == self::TYPE_DEFAULT ) {
352 $queues = array_intersect( $queues, $this->getDefaultQueueTypes() );
353 }
354 $value = count( $queues ) ? 'true' : 'false';
355 $cache->add( $key, $value, 15 );
356 }
357
358 return ( $value === 'true' );
359 }
360
366 public function getQueuesWithJobs() {
367 $types = [];
368 foreach ( $this->getCoalescedQueues() as $info ) {
370 $queue = $info['queue'];
371 $nonEmpty = $queue->getSiblingQueuesWithJobs( $this->getQueueTypes() );
372 if ( is_array( $nonEmpty ) ) { // batching features supported
373 $types = array_merge( $types, $nonEmpty );
374 } else { // we have to go through the queues in the bucket one-by-one
375 foreach ( $info['types'] as $type ) {
376 if ( !$this->get( $type )->isEmpty() ) {
377 $types[] = $type;
378 }
379 }
380 }
381 }
382
383 return $types;
384 }
385
391 public function getQueueSizes() {
392 $sizeMap = [];
393 foreach ( $this->getCoalescedQueues() as $info ) {
395 $queue = $info['queue'];
396 $sizes = $queue->getSiblingQueueSizes( $this->getQueueTypes() );
397 if ( is_array( $sizes ) ) { // batching features supported
398 $sizeMap += $sizes;
399 } else { // we have to go through the queues in the bucket one-by-one
400 foreach ( $info['types'] as $type ) {
401 $sizeMap[$type] = $this->get( $type )->getSize();
402 }
403 }
404 }
405
406 return $sizeMap;
407 }
408
413 protected function getCoalescedQueues() {
414 global $wgJobTypeConf;
415
416 if ( $this->coalescedQueues === null ) {
417 $this->coalescedQueues = [];
418 foreach ( $wgJobTypeConf as $type => $conf ) {
419 $queue = $this->factoryJobQueue(
420 [ 'domain' => $this->domain, 'type' => 'null' ] + $conf );
421 $loc = $queue->getCoalesceLocationInternal();
422 if ( !isset( $this->coalescedQueues[$loc] ) ) {
423 $this->coalescedQueues[$loc]['queue'] = $queue;
424 $this->coalescedQueues[$loc]['types'] = [];
425 }
426 if ( $type === 'default' ) {
427 $this->coalescedQueues[$loc]['types'] = array_merge(
428 $this->coalescedQueues[$loc]['types'],
429 array_diff( $this->getQueueTypes(), array_keys( $wgJobTypeConf ) )
430 );
431 } else {
432 $this->coalescedQueues[$loc]['types'][] = $type;
433 }
434 }
435 }
436
437 return $this->coalescedQueues;
438 }
439
444 private function getCachedConfigVar( $name ) {
445 // @TODO: cleanup this whole method with a proper config system
446 if ( WikiMap::isCurrentWikiDbDomain( $this->domain ) ) {
447 return $GLOBALS[$name]; // common case
448 } else {
449 $wiki = WikiMap::getWikiIdFromDbDomain( $this->domain );
450 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
451 $value = $cache->getWithSetCallback(
452 $cache->makeGlobalKey( 'jobqueue', 'configvalue', $this->domain, $name ),
453 $cache::TTL_DAY + mt_rand( 0, $cache::TTL_DAY ),
454 function () use ( $wiki, $name ) {
455 global $wgConf;
456 // @TODO: use the full domain ID here
457 return [ 'v' => $wgConf->getConfig( $wiki, $name ) ];
458 },
459 [ 'pcTTL' => WANObjectCache::TTL_PROC_LONG ]
460 );
461
462 return $value['v'];
463 }
464 }
465
470 private function assertValidJobs( array $jobs ) {
471 foreach ( $jobs as $job ) { // sanity checks
472 if ( !( $job instanceof IJobSpecification ) ) {
473 throw new InvalidArgumentException( "Expected IJobSpecification objects" );
474 }
475 }
476 }
477}
$GLOBALS['IP']
$wgJobTypeConf
Map of job types to configuration arrays.
$wgJobTypesExcludedFromDefaultQueue
Jobs that must be explicitly requested, i.e.
$wgConf
$wgConf hold the site configuration.
$wgJobClasses
Maps jobs to their handlers; extensions can add to this to provide custom jobs.
string[] $wgLocalDatabases
Other wikis on this site, can be administered from a single developer account.
wfConfiguredReadOnlyReason()
Get the value of $wgReadOnly or the contents of $wgReadOnlyFile.
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.
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)
string bool $readOnlyReason
Read only rationale (or false if r/w)
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 $blacklist=[])
Pop a job off one of the job queues.
ack(RunnableJob $job)
Acknowledge that a job was completed.
static destroySingletons()
Destroy the singleton instances.
factoryJobQueue(array $conf)
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.
__construct( $domain, $readOnlyReason)
static JobQueueGroup[] $instances
MapCacheLRU $cache
getQueuesWithJobs()
Get the list of job types that have non-empty queues.
assertValidJobs(array $jobs)
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: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.
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