MediaWiki  master
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 
45  protected $coalescedQueues;
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 ) {
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).
82  if (
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 = $conf + $wgJobTypeConf[$type];
114  } else {
115  $conf = $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." );
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 
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 
297  public function deduplicateRootJob( RunnableJob $job ) {
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 ) {
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 = $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 }
$wgConf
$wgConf
$wgConf hold the site configuration.
Definition: DefaultSettings.php:58
WikiMap\isCurrentWikiDbDomain
static isCurrentWikiDbDomain( $domain)
Definition: WikiMap.php:312
JobQueueGroup\pop
pop( $qtype=self::TYPE_DEFAULT, $flags=0, array $blacklist=[])
Pop a job off one of the job queues.
Definition: JobQueueGroup.php:233
JobQueueGroup\USE_CACHE
const USE_CACHE
Definition: JobQueueGroup.php:50
JobQueueGroup\waitForBackups
waitForBackups()
Wait for any replica DBs or backup queue servers to catch up.
Definition: JobQueueGroup.php:308
JobQueueGroup\deduplicateRootJob
deduplicateRootJob(RunnableJob $job)
Register the "root job" of a given job into the queue for de-duplication.
Definition: JobQueueGroup.php:297
$wgLocalDatabases
string[] $wgLocalDatabases
Other wikis on this site, can be administered from a single developer account.
Definition: DefaultSettings.php:2255
WikiMap\getCurrentWikiDbDomain
static getCurrentWikiDbDomain()
Definition: WikiMap.php:293
ObjectCache\getLocalClusterInstance
static getLocalClusterInstance()
Get the main cluster-local cache object.
Definition: ObjectCache.php:272
JobQueueGroup\PROC_CACHE_TTL
const PROC_CACHE_TTL
Definition: JobQueueGroup.php:52
JobQueueGroup\CACHE_VERSION
const CACHE_VERSION
Definition: JobQueueGroup.php:54
$wgJobTypeConf
$wgJobTypeConf
Map of job types to configuration arrays.
Definition: DefaultSettings.php:7951
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:146
JobQueueGroup\$coalescedQueues
array $coalescedQueues
Map of (bucket => (queue => JobQueue, types => list of types)
Definition: JobQueueGroup.php:45
JobQueueEnqueueUpdate
Enqueue lazy-pushed jobs that have accumulated from JobQueueGroup.
Definition: JobQueueEnqueueUpdate.php:31
JobQueueGroup\TYPE_DEFAULT
const TYPE_DEFAULT
Definition: JobQueueGroup.php:47
wfConfiguredReadOnlyReason
wfConfiguredReadOnlyReason()
Get the value of $wgReadOnly or the contents of $wgReadOnlyFile.
Definition: GlobalFunctions.php:1128
JobQueueGroup\getCoalescedQueues
getCoalescedQueues()
Definition: JobQueueGroup.php:413
DeferredUpdates\addUpdate
static addUpdate(DeferrableUpdate $update, $stage=self::POSTSEND)
Add an update to the deferred update queue for execution at the appropriate time.
Definition: DeferredUpdates.php:106
RunnableJob
Job that has a run() method and metadata accessors for JobQueue::pop() and JobQueue::ack()
Definition: RunnableJob.php:35
JobQueueGroup\$instances
static JobQueueGroup[] $instances
Definition: JobQueueGroup.php:32
JobQueueGroup\queuesHaveJobs
queuesHaveJobs( $type=self::TYPE_ANY)
Check if there are any queues with jobs (this is cached)
Definition: JobQueueGroup.php:344
JobQueueGroup\destroySingletons
static destroySingletons()
Destroy the singleton instances.
Definition: JobQueueGroup.php:98
MWExceptionHandler\logException
static logException(Throwable $e, $catcher=self::CAUGHT_BY_OTHER, $extraData=[])
Log a throwable to the exception log (if enabled).
Definition: MWExceptionHandler.php:645
IJobSpecification\getType
getType()
JobQueueGroup\$domain
string $domain
Wiki domain ID.
Definition: JobQueueGroup.php:38
JobQueueGroup\push
push( $jobs)
Insert jobs into the respective queues of which they belong.
Definition: JobQueueGroup.php:148
WikiMap\getWikiIdFromDbDomain
static getWikiIdFromDbDomain( $domain)
Get the wiki ID of a database domain.
Definition: WikiMap.php:269
$queue
$queue
Definition: mergeMessageFileList.php:157
MapCacheLRU
Handles a simple LRU key/value map with a maximum number of entries.
Definition: MapCacheLRU.php:38
JobQueueGroup\getCachedConfigVar
getCachedConfigVar( $name)
Definition: JobQueueGroup.php:444
JobQueueError
Definition: JobQueueError.php:28
MapCacheLRU\getWithSetCallback
getWithSetCallback( $key, callable $callback, $rank=self::RANK_TOP, $maxAge=INF)
Get an item with the given key, producing and setting it if not found.
Definition: MapCacheLRU.php:265
JobQueueGroup\ack
ack(RunnableJob $job)
Acknowledge that a job was completed.
Definition: JobQueueGroup.php:286
$wgJobTypesExcludedFromDefaultQueue
$wgJobTypesExcludedFromDefaultQueue
Jobs that must be explicitly requested, i.e.
Definition: DefaultSettings.php:7917
JobQueueGroup\getDefaultQueueTypes
getDefaultQueueTypes()
Get the list of default queue types.
Definition: JobQueueGroup.php:331
JobQueueGroup\$readOnlyReason
string bool $readOnlyReason
Read only rationale (or false if r/w)
Definition: JobQueueGroup.php:40
MapCacheLRU\set
set( $key, $value, $rank=self::RANK_TOP)
Set a key/value pair.
Definition: MapCacheLRU.php:111
JobQueue\factory
static factory(array $params)
Get a job queue object of the specified type.
Definition: JobQueue.php:121
$wgJobClasses
$wgJobClasses
Maps jobs to their handlers; extensions can add to this to provide custom jobs.
Definition: DefaultSettings.php:7880
JobQueueGroup\singleton
static singleton( $domain=false)
Definition: JobQueueGroup.php:70
JobQueueGroup\TYPE_ANY
const TYPE_ANY
Definition: JobQueueGroup.php:48
JobQueueGroup\assertValidJobs
assertValidJobs(array $jobs)
Definition: JobQueueGroup.php:470
$job
if(count( $args)< 1) $job
Definition: recompressTracked.php:50
JobQueueGroup\getQueueTypes
getQueueTypes()
Get the list of queue types.
Definition: JobQueueGroup.php:322
MapCacheLRU\get
get( $key, $maxAge=INF, $default=null)
Get the value for a key.
Definition: MapCacheLRU.php:169
JobQueueGroup\getQueuesWithJobs
getQueuesWithJobs()
Get the list of job types that have non-empty queues.
Definition: JobQueueGroup.php:366
JobQueueGroup\factoryJobQueue
factoryJobQueue(array $conf)
Definition: JobQueueGroup.php:129
JobQueueGroup\getQueueSizes
getQueueSizes()
Get the size of the queues for a list of job types.
Definition: JobQueueGroup.php:391
JobQueueGroup\$cache
MapCacheLRU $cache
Definition: JobQueueGroup.php:35
IJobSpecification
Interface for serializable objects that describe a job queue task.
Definition: IJobSpecification.php:35
$GLOBALS
$GLOBALS['IP']
Definition: ComposerHookHandler.php:6
JobQueueGroup\$invalidDomain
bool $invalidDomain
Whether the wiki is not recognized in configuration.
Definition: JobQueueGroup.php:42
JobQueueGroup\lazyPush
lazyPush( $jobs)
Buffer jobs for insertion via push() or call it now if in CLI mode.
Definition: JobQueueGroup.php:203
JobQueueGroup
Class to handle enqueueing of background jobs.
Definition: JobQueueGroup.php:30
JobQueueGroup\__construct
__construct( $domain, $readOnlyReason)
Definition: JobQueueGroup.php:60
$type
$type
Definition: testCompression.php:52