MediaWiki  master
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 
62  protected $coalescedQueues;
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,
89  bool $invalidDomain,
90  array $jobClasses,
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." );
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 
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 
306  public function deduplicateRootJob( RunnableJob $job ) {
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 ) {
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
$wgConf hold the site configuration.
Definition: DefaultSettings.php:60
WikiMap\isCurrentWikiDbDomain
static isCurrentWikiDbDomain( $domain)
Definition: WikiMap.php:312
JobQueueGroup\USE_CACHE
const USE_CACHE
Definition: JobQueueGroup.php:67
JobQueueGroup\waitForBackups
waitForBackups()
Wait for any replica DBs or backup queue servers to catch up.
Definition: JobQueueGroup.php:317
JobQueueGroup\deduplicateRootJob
deduplicateRootJob(RunnableJob $job)
Register the "root job" of a given job into the queue for de-duplication.
Definition: JobQueueGroup.php:306
Wikimedia\UUID\GlobalIdGenerator
Class for getting statistically unique IDs without a central coordinator.
Definition: GlobalIdGenerator.php:34
ObjectCache\getLocalClusterInstance
static getLocalClusterInstance()
Get the main cluster-local cache object.
Definition: ObjectCache.php:273
JobQueueGroup\PROC_CACHE_TTL
const PROC_CACHE_TTL
Definition: JobQueueGroup.php:69
JobQueueGroup\CACHE_VERSION
const CACHE_VERSION
Definition: JobQueueGroup.php:71
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:193
JobQueueGroup\$jobTypeConfiguration
array $jobTypeConfiguration
Definition: JobQueueGroup.php:51
JobQueueGroup\$coalescedQueues
array $coalescedQueues
Map of (bucket => (queue => JobQueue, types => list of types)
Definition: JobQueueGroup.php:62
JobQueueEnqueueUpdate
Enqueue lazy-pushed jobs that have accumulated from JobQueueGroup.
Definition: JobQueueEnqueueUpdate.php:31
JobQueueGroup\TYPE_DEFAULT
const TYPE_DEFAULT
Definition: JobQueueGroup.php:64
JobQueueGroup\getCoalescedQueues
getCoalescedQueues()
Definition: JobQueueGroup.php:418
DeferredUpdates\addUpdate
static addUpdate(DeferrableUpdate $update, $stage=self::POSTSEND)
Add an update to the pending update queue for execution at the appropriate time.
Definition: DeferredUpdates.php:119
ConfiguredReadOnlyMode
A read-only mode service which does not depend on LoadBalancer.
Definition: ConfiguredReadOnlyMode.php:9
RunnableJob
Job that has a run() method and metadata accessors for JobQueue::pop() and JobQueue::ack()
Definition: RunnableJob.php:37
JobQueueGroup\$instances
static JobQueueGroup[] $instances
Definition: JobQueueGroup.php:37
JobQueueGroup\queuesHaveJobs
queuesHaveJobs( $type=self::TYPE_ANY)
Check if there are any queues with jobs (this is cached)
Definition: JobQueueGroup.php:349
JobQueueGroup\destroySingletons
static destroySingletons()
Destroy the singleton instances.
Definition: JobQueueGroup.php:124
JobQueueGroup\__construct
__construct( $domain, ConfiguredReadOnlyMode $readOnlyMode, bool $invalidDomain, array $jobClasses, array $jobTypeConfiguration, array $jobTypesExcludedFromDefaultQueue, IBufferingStatsdDataFactory $statsdDataFactory, WANObjectCache $wanCache, GlobalIdGenerator $globalIdGenerator)
Definition: JobQueueGroup.php:86
JobQueueGroup\$statsdDataFactory
IBufferingStatsdDataFactory $statsdDataFactory
Definition: JobQueueGroup.php:55
MWExceptionHandler\logException
static logException(Throwable $e, $catcher=self::CAUGHT_BY_OTHER, $extraData=[])
Log a throwable to the exception log (if enabled).
Definition: MWExceptionHandler.php:700
IJobSpecification\getType
getType()
JobQueueGroup\$wanCache
WANObjectCache $wanCache
Definition: JobQueueGroup.php:57
JobQueueGroup\$domain
string $domain
Wiki domain ID.
Definition: JobQueueGroup.php:43
JobQueueGroup\push
push( $jobs)
Insert jobs into the respective queues of which they belong.
Definition: JobQueueGroup.php:161
WikiMap\getWikiIdFromDbDomain
static getWikiIdFromDbDomain( $domain)
Get the wiki ID of a database domain.
Definition: WikiMap.php:269
JobQueueGroup\$jobTypesExcludedFromDefaultQueue
array $jobTypesExcludedFromDefaultQueue
Definition: JobQueueGroup.php:53
JobQueueGroup\$globalIdGenerator
GlobalIdGenerator $globalIdGenerator
Definition: JobQueueGroup.php:59
$queue
$queue
Definition: mergeMessageFileList.php:176
MapCacheLRU
Handles a simple LRU key/value map with a maximum number of entries.
Definition: MapCacheLRU.php:36
JobQueueGroup\getCachedConfigVar
getCachedConfigVar( $name)
Definition: JobQueueGroup.php:452
JobQueueGroup\$jobClasses
array $jobClasses
Definition: JobQueueGroup.php:49
JobQueueError
@newable
Definition: JobQueueError.php:29
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:262
JobQueueGroup\ack
ack(RunnableJob $job)
Acknowledge that a job was completed.
Definition: JobQueueGroup.php:295
JobQueueGroup\getDefaultQueueTypes
getDefaultQueueTypes()
Get the list of default queue types.
Definition: JobQueueGroup.php:338
WANObjectCache
Multi-datacenter aware caching interface.
Definition: WANObjectCache.php:128
MapCacheLRU\set
set( $key, $value, $rank=self::RANK_TOP)
Set a key/value pair.
Definition: MapCacheLRU.php:109
JobQueue\factory
static factory(array $params)
Get a job queue object of the specified type.
Definition: JobQueue.php:125
JobQueueGroup\pop
pop( $qtype=self::TYPE_DEFAULT, $flags=0, array $ignored=[])
Pop a job off one of the job queues.
Definition: JobQueueGroup.php:244
IBufferingStatsdDataFactory
MediaWiki adaptation of StatsdDataFactory that provides buffering functionality.
Definition: IBufferingStatsdDataFactory.php:13
JobQueueGroup\singleton
static singleton( $domain=false)
Definition: JobQueueGroup.php:114
JobQueueGroup\TYPE_ANY
const TYPE_ANY
Definition: JobQueueGroup.php:65
JobQueueGroup\assertValidJobs
assertValidJobs(array $jobs)
Definition: JobQueueGroup.php:478
$job
if(count( $args)< 1) $job
Definition: recompressTracked.php:49
JobQueueGroup\getQueueTypes
getQueueTypes()
Get the list of queue types.
Definition: JobQueueGroup.php:329
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:371
JobQueueGroup\$readOnlyMode
ConfiguredReadOnlyMode $readOnlyMode
Read only mode.
Definition: JobQueueGroup.php:45
JobQueueGroup\getQueueSizes
getQueueSizes()
Get the size of the queues for a list of job types.
Definition: JobQueueGroup.php:396
JobQueueGroup\$cache
MapCacheLRU $cache
Definition: JobQueueGroup.php:40
IJobSpecification
Interface for serializable objects that describe a job queue task.
Definition: IJobSpecification.php:42
JobQueueGroup\$invalidDomain
bool $invalidDomain
Whether the wiki is not recognized in configuration.
Definition: JobQueueGroup.php:47
JobQueueGroup\lazyPush
lazyPush( $jobs)
Buffer jobs for insertion via push() or call it now if in CLI mode.
Definition: JobQueueGroup.php:214
JobQueueGroup
Class to handle enqueueing of background jobs.
Definition: JobQueueGroup.php:32
$type
$type
Definition: testCompression.php:52