MediaWiki  master
JobQueueGroup.php
Go to the documentation of this file.
1 <?php
26 
35  protected $cache;
36 
38  protected $domain;
40  protected $readOnlyMode;
42  protected $invalidDomain = false;
44  private $jobClasses;
46  private $jobTypeConfiguration;
48  private $jobTypesExcludedFromDefaultQueue;
50  private $statsdDataFactory;
52  private $wanCache;
54  private $globalIdGenerator;
55 
57  protected $coalescedQueues;
58 
59  public const TYPE_DEFAULT = 1; // integer; jobs popped by default
60  private const TYPE_ANY = 2; // integer; any job
61 
62  public const USE_CACHE = 1; // integer; use process or persistent cache
63 
64  private const PROC_CACHE_TTL = 15; // integer; seconds
65 
66  private const CACHE_VERSION = 1; // integer; cache version
67 
81  public function __construct(
82  $domain,
84  bool $invalidDomain,
85  array $jobClasses,
86  array $jobTypeConfiguration,
87  array $jobTypesExcludedFromDefaultQueue,
88  IBufferingStatsdDataFactory $statsdDataFactory,
89  WANObjectCache $wanCache,
90  GlobalIdGenerator $globalIdGenerator
91  ) {
92  $this->domain = $domain;
93  $this->readOnlyMode = $readOnlyMode;
94  $this->cache = new MapCacheLRU( 10 );
95  $this->invalidDomain = $invalidDomain;
96  $this->jobClasses = $jobClasses;
97  $this->jobTypeConfiguration = $jobTypeConfiguration;
98  $this->jobTypesExcludedFromDefaultQueue = $jobTypesExcludedFromDefaultQueue;
99  $this->statsdDataFactory = $statsdDataFactory;
100  $this->wanCache = $wanCache;
101  $this->globalIdGenerator = $globalIdGenerator;
102  }
103 
110  public function get( $type ) {
111  $conf = [ 'domain' => $this->domain, 'type' => $type ];
112  $conf += $this->jobTypeConfiguration[$type] ?? $this->jobTypeConfiguration['default'];
113  if ( !isset( $conf['readOnlyReason'] ) ) {
114  $conf['readOnlyReason'] = $this->readOnlyMode->getReason();
115  }
116 
117  $conf['stats'] = $this->statsdDataFactory;
118  $conf['wanCache'] = $this->wanCache;
119  $conf['idGenerator'] = $this->globalIdGenerator;
120 
121  return JobQueue::factory( $conf );
122  }
123 
134  public function push( $jobs ) {
135  if ( $this->invalidDomain ) {
136  // Do not enqueue job that cannot be run (T171371)
137  $e = new LogicException( "Domain '{$this->domain}' is not recognized." );
139  return;
140  }
141 
142  $jobs = is_array( $jobs ) ? $jobs : [ $jobs ];
143  if ( $jobs === [] ) {
144  return;
145  }
146 
147  $this->assertValidJobs( $jobs );
148 
149  $jobsByType = []; // (job type => list of jobs)
150  foreach ( $jobs as $job ) {
151  $type = $job->getType();
152  if ( isset( $this->jobTypeConfiguration[$type] ) ) {
153  $jobsByType[$type][] = $job;
154  } else {
155  if (
156  isset( $this->jobTypeConfiguration['default']['typeAgnostic'] ) &&
157  $this->jobTypeConfiguration['default']['typeAgnostic']
158  ) {
159  $jobsByType['default'][] = $job;
160  } else {
161  $jobsByType[$type][] = $job;
162  }
163  }
164  }
165 
166  foreach ( $jobsByType as $type => $jobs ) {
167  $this->get( $type )->push( $jobs );
168  }
169 
170  if ( $this->cache->hasField( 'queues-ready', 'list' ) ) {
171  $list = $this->cache->getField( 'queues-ready', 'list' );
172  if ( count( array_diff( array_keys( $jobsByType ), $list ) ) ) {
173  $this->cache->clear( 'queues-ready' );
174  }
175  }
176 
178  $cache->set(
179  $cache->makeGlobalKey( 'jobqueue', $this->domain, 'hasjobs', self::TYPE_ANY ),
180  'true',
181  15
182  );
183  if ( array_diff( array_keys( $jobsByType ), $this->jobTypesExcludedFromDefaultQueue ) ) {
184  $cache->set(
185  $cache->makeGlobalKey( 'jobqueue', $this->domain, 'hasjobs', self::TYPE_DEFAULT ),
186  'true',
187  15
188  );
189  }
190  }
191 
199  public function lazyPush( $jobs ) {
200  if ( $this->invalidDomain ) {
201  // Do not enqueue job that cannot be run (T171371)
202  throw new LogicException( "Domain '{$this->domain}' is not recognized." );
203  }
204 
205  if ( PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg' ) {
206  $this->push( $jobs );
207  return;
208  }
209 
210  $jobs = is_array( $jobs ) ? $jobs : [ $jobs ];
211 
212  // Throw errors now instead of on push(), when other jobs may be buffered
213  $this->assertValidJobs( $jobs );
214 
215  DeferredUpdates::addUpdate( new JobQueueEnqueueUpdate( $this->domain, $jobs ) );
216  }
217 
229  public function pop( $qtype = self::TYPE_DEFAULT, $flags = 0, array $ignored = [] ) {
230  $job = false;
231 
232  if ( !WikiMap::isCurrentWikiDbDomain( $this->domain ) ) {
233  throw new JobQueueError(
234  "Cannot pop '{$qtype}' job off foreign '{$this->domain}' wiki queue." );
235  } elseif ( is_string( $qtype ) && !isset( $this->jobClasses[$qtype] ) ) {
236  // Do not pop jobs if there is no class for the queue type
237  throw new JobQueueError( "Unrecognized job type '$qtype'." );
238  }
239 
240  if ( is_string( $qtype ) ) { // specific job type
241  if ( !in_array( $qtype, $ignored ) ) {
242  $job = $this->get( $qtype )->pop();
243  }
244  } else { // any job in the "default" jobs types
245  if ( $flags & self::USE_CACHE ) {
246  if ( !$this->cache->hasField( 'queues-ready', 'list', self::PROC_CACHE_TTL ) ) {
247  $this->cache->setField( 'queues-ready', 'list', $this->getQueuesWithJobs() );
248  }
249  $types = $this->cache->getField( 'queues-ready', 'list' );
250  } else {
251  $types = $this->getQueuesWithJobs();
252  }
253 
254  if ( $qtype == self::TYPE_DEFAULT ) {
255  $types = array_intersect( $types, $this->getDefaultQueueTypes() );
256  }
257 
258  $types = array_diff( $types, $ignored ); // avoid selected types
259  shuffle( $types ); // avoid starvation
260 
261  foreach ( $types as $type ) { // for each queue...
262  $job = $this->get( $type )->pop();
263  if ( $job ) { // found
264  break;
265  } else { // not found
266  $this->cache->clear( 'queues-ready' );
267  }
268  }
269  }
270 
271  return $job;
272  }
273 
280  public function ack( RunnableJob $job ) {
281  $this->get( $job->getType() )->ack( $job );
282  }
283 
291  public function deduplicateRootJob( RunnableJob $job ) {
292  return $this->get( $job->getType() )->deduplicateRootJob( $job );
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 ) {
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 }
$wgConf
$wgConf hold the site configuration.
Definition: Setup.php:141
A read-only mode service which does not depend on LoadBalancer.
static addUpdate(DeferrableUpdate $update, $stage=self::POSTSEND)
Add an update to the pending update queue for execution at the appropriate time.
Enqueue lazy-pushed jobs that have accumulated from JobQueueGroup.
Class to 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
static logException(Throwable $e, $catcher=self::CAUGHT_BY_OTHER, $extraData=[])
Log a throwable to the exception log (if enabled).
Handles a simple LRU key/value map with a maximum number of entries.
Definition: MapCacheLRU.php:36
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
static getLocalClusterInstance()
Get the main cluster-local cache object.
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()
Definition: RunnableJob.php:37
if(count( $args)< 1) $job