Expose $wgMaxArticleSize in siteinfo query api
[mediawiki.git] / includes / jobqueue / JobQueueGroup.php
bloba4b32411cf436d47f2e2ada76220c55daf562ac3
1 <?php
2 /**
3 * Job queue base code.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
20 * @file
21 * @author Aaron Schulz
24 /**
25 * Class to handle enqueueing of background jobs
27 * @ingroup JobQueue
28 * @since 1.21
30 class JobQueueGroup {
31 /** @var JobQueueGroup[] */
32 protected static $instances = [];
34 /** @var ProcessCacheLRU */
35 protected $cache;
37 /** @var string Wiki ID */
38 protected $wiki;
39 /** @var string|bool Read only rationale (or false if r/w) */
40 protected $readOnlyReason;
42 /** @var array Map of (bucket => (queue => JobQueue, types => list of types) */
43 protected $coalescedQueues;
45 /** @var Job[] */
46 protected $bufferedJobs = [];
48 const TYPE_DEFAULT = 1; // integer; jobs popped by default
49 const TYPE_ANY = 2; // integer; any job
51 const USE_CACHE = 1; // integer; use process or persistent cache
53 const PROC_CACHE_TTL = 15; // integer; seconds
55 const CACHE_VERSION = 1; // integer; cache version
57 /**
58 * @param string $wiki Wiki ID
59 * @param string|bool $readOnlyReason Read-only reason or false
61 protected function __construct( $wiki, $readOnlyReason ) {
62 $this->wiki = $wiki;
63 $this->readOnlyReason = $readOnlyReason;
64 $this->cache = new ProcessCacheLRU( 10 );
67 /**
68 * @param bool|string $wiki Wiki ID
69 * @return JobQueueGroup
71 public static function singleton( $wiki = false ) {
72 $wiki = ( $wiki === false ) ? wfWikiID() : $wiki;
73 if ( !isset( self::$instances[$wiki] ) ) {
74 self::$instances[$wiki] = new self( $wiki, wfConfiguredReadOnlyReason() );
77 return self::$instances[$wiki];
80 /**
81 * Destroy the singleton instances
83 * @return void
85 public static function destroySingletons() {
86 self::$instances = [];
89 /**
90 * Get the job queue object for a given queue type
92 * @param string $type
93 * @return JobQueue
95 public function get( $type ) {
96 global $wgJobTypeConf;
98 $conf = [ 'wiki' => $this->wiki, 'type' => $type ];
99 if ( isset( $wgJobTypeConf[$type] ) ) {
100 $conf = $conf + $wgJobTypeConf[$type];
101 } else {
102 $conf = $conf + $wgJobTypeConf['default'];
104 $conf['aggregator'] = JobQueueAggregator::singleton();
105 if ( $this->readOnlyReason !== false ) {
106 $conf['readOnlyReason'] = $this->readOnlyReason;
109 return JobQueue::factory( $conf );
113 * Insert jobs into the respective queues of which they belong
115 * This inserts the jobs into the queue specified by $wgJobTypeConf
116 * and updates the aggregate job queue information cache as needed.
118 * @param IJobSpecification|IJobSpecification[] $jobs A single Job or a list of Jobs
119 * @throws InvalidArgumentException
120 * @return void
122 public function push( $jobs ) {
123 $jobs = is_array( $jobs ) ? $jobs : [ $jobs ];
124 if ( !count( $jobs ) ) {
125 return;
128 $this->assertValidJobs( $jobs );
130 $jobsByType = []; // (job type => list of jobs)
131 foreach ( $jobs as $job ) {
132 $jobsByType[$job->getType()][] = $job;
135 foreach ( $jobsByType as $type => $jobs ) {
136 $this->get( $type )->push( $jobs );
139 if ( $this->cache->has( 'queues-ready', 'list' ) ) {
140 $list = $this->cache->get( 'queues-ready', 'list' );
141 if ( count( array_diff( array_keys( $jobsByType ), $list ) ) ) {
142 $this->cache->clear( 'queues-ready' );
148 * Buffer jobs for insertion via push() or call it now if in CLI mode
150 * Note that MediaWiki::restInPeace() calls pushLazyJobs()
152 * @param IJobSpecification|IJobSpecification[] $jobs A single Job or a list of Jobs
153 * @return void
154 * @since 1.26
156 public function lazyPush( $jobs ) {
157 if ( PHP_SAPI === 'cli' ) {
158 $this->push( $jobs );
159 return;
162 $jobs = is_array( $jobs ) ? $jobs : [ $jobs ];
164 // Throw errors now instead of on push(), when other jobs may be buffered
165 $this->assertValidJobs( $jobs );
167 $this->bufferedJobs = array_merge( $this->bufferedJobs, $jobs );
171 * Push all jobs buffered via lazyPush() into their respective queues
173 * @return void
174 * @since 1.26
176 public static function pushLazyJobs() {
177 foreach ( self::$instances as $group ) {
178 try {
179 $group->push( $group->bufferedJobs );
180 $group->bufferedJobs = [];
181 } catch ( Exception $e ) {
182 // Get in as many jobs as possible and let other post-send updates happen
183 MWExceptionHandler::logException( $e );
189 * Pop a job off one of the job queues
191 * This pops a job off a queue as specified by $wgJobTypeConf and
192 * updates the aggregate job queue information cache as needed.
194 * @param int|string $qtype JobQueueGroup::TYPE_* constant or job type string
195 * @param int $flags Bitfield of JobQueueGroup::USE_* constants
196 * @param array $blacklist List of job types to ignore
197 * @return Job|bool Returns false on failure
199 public function pop( $qtype = self::TYPE_DEFAULT, $flags = 0, array $blacklist = [] ) {
200 $job = false;
202 if ( is_string( $qtype ) ) { // specific job type
203 if ( !in_array( $qtype, $blacklist ) ) {
204 $job = $this->get( $qtype )->pop();
206 } else { // any job in the "default" jobs types
207 if ( $flags & self::USE_CACHE ) {
208 if ( !$this->cache->has( 'queues-ready', 'list', self::PROC_CACHE_TTL ) ) {
209 $this->cache->set( 'queues-ready', 'list', $this->getQueuesWithJobs() );
211 $types = $this->cache->get( 'queues-ready', 'list' );
212 } else {
213 $types = $this->getQueuesWithJobs();
216 if ( $qtype == self::TYPE_DEFAULT ) {
217 $types = array_intersect( $types, $this->getDefaultQueueTypes() );
220 $types = array_diff( $types, $blacklist ); // avoid selected types
221 shuffle( $types ); // avoid starvation
223 foreach ( $types as $type ) { // for each queue...
224 $job = $this->get( $type )->pop();
225 if ( $job ) { // found
226 break;
227 } else { // not found
228 $this->cache->clear( 'queues-ready' );
233 return $job;
237 * Acknowledge that a job was completed
239 * @param Job $job
240 * @return void
242 public function ack( Job $job ) {
243 $this->get( $job->getType() )->ack( $job );
247 * Register the "root job" of a given job into the queue for de-duplication.
248 * This should only be called right *after* all the new jobs have been inserted.
250 * @param Job $job
251 * @return bool
253 public function deduplicateRootJob( Job $job ) {
254 return $this->get( $job->getType() )->deduplicateRootJob( $job );
258 * Wait for any slaves or backup queue servers to catch up.
260 * This does nothing for certain queue classes.
262 * @return void
264 public function waitForBackups() {
265 global $wgJobTypeConf;
267 // Try to avoid doing this more than once per queue storage medium
268 foreach ( $wgJobTypeConf as $type => $conf ) {
269 $this->get( $type )->waitForBackups();
274 * Get the list of queue types
276 * @return array List of strings
278 public function getQueueTypes() {
279 return array_keys( $this->getCachedConfigVar( 'wgJobClasses' ) );
283 * Get the list of default queue types
285 * @return array List of strings
287 public function getDefaultQueueTypes() {
288 global $wgJobTypesExcludedFromDefaultQueue;
290 return array_diff( $this->getQueueTypes(), $wgJobTypesExcludedFromDefaultQueue );
294 * Check if there are any queues with jobs (this is cached)
296 * @param int $type JobQueueGroup::TYPE_* constant
297 * @return bool
298 * @since 1.23
300 public function queuesHaveJobs( $type = self::TYPE_ANY ) {
301 $key = wfMemcKey( 'jobqueue', 'queueshavejobs', $type );
302 $cache = ObjectCache::getLocalClusterInstance();
304 $value = $cache->get( $key );
305 if ( $value === false ) {
306 $queues = $this->getQueuesWithJobs();
307 if ( $type == self::TYPE_DEFAULT ) {
308 $queues = array_intersect( $queues, $this->getDefaultQueueTypes() );
310 $value = count( $queues ) ? 'true' : 'false';
311 $cache->add( $key, $value, 15 );
314 return ( $value === 'true' );
318 * Get the list of job types that have non-empty queues
320 * @return array List of job types that have non-empty queues
322 public function getQueuesWithJobs() {
323 $types = [];
324 foreach ( $this->getCoalescedQueues() as $info ) {
325 $nonEmpty = $info['queue']->getSiblingQueuesWithJobs( $this->getQueueTypes() );
326 if ( is_array( $nonEmpty ) ) { // batching features supported
327 $types = array_merge( $types, $nonEmpty );
328 } else { // we have to go through the queues in the bucket one-by-one
329 foreach ( $info['types'] as $type ) {
330 if ( !$this->get( $type )->isEmpty() ) {
331 $types[] = $type;
337 return $types;
341 * Get the size of the queus for a list of job types
343 * @return array Map of (job type => size)
345 public function getQueueSizes() {
346 $sizeMap = [];
347 foreach ( $this->getCoalescedQueues() as $info ) {
348 $sizes = $info['queue']->getSiblingQueueSizes( $this->getQueueTypes() );
349 if ( is_array( $sizes ) ) { // batching features supported
350 $sizeMap = $sizeMap + $sizes;
351 } else { // we have to go through the queues in the bucket one-by-one
352 foreach ( $info['types'] as $type ) {
353 $sizeMap[$type] = $this->get( $type )->getSize();
358 return $sizeMap;
362 * @return array
364 protected function getCoalescedQueues() {
365 global $wgJobTypeConf;
367 if ( $this->coalescedQueues === null ) {
368 $this->coalescedQueues = [];
369 foreach ( $wgJobTypeConf as $type => $conf ) {
370 $queue = JobQueue::factory(
371 [ 'wiki' => $this->wiki, 'type' => 'null' ] + $conf );
372 $loc = $queue->getCoalesceLocationInternal();
373 if ( !isset( $this->coalescedQueues[$loc] ) ) {
374 $this->coalescedQueues[$loc]['queue'] = $queue;
375 $this->coalescedQueues[$loc]['types'] = [];
377 if ( $type === 'default' ) {
378 $this->coalescedQueues[$loc]['types'] = array_merge(
379 $this->coalescedQueues[$loc]['types'],
380 array_diff( $this->getQueueTypes(), array_keys( $wgJobTypeConf ) )
382 } else {
383 $this->coalescedQueues[$loc]['types'][] = $type;
388 return $this->coalescedQueues;
392 * @param string $name
393 * @return mixed
395 private function getCachedConfigVar( $name ) {
396 // @TODO: cleanup this whole method with a proper config system
397 if ( $this->wiki === wfWikiID() ) {
398 return $GLOBALS[$name]; // common case
399 } else {
400 $wiki = $this->wiki;
401 $cache = ObjectCache::getMainWANInstance();
402 $value = $cache->getWithSetCallback(
403 $cache->makeGlobalKey( 'jobqueue', 'configvalue', $wiki, $name ),
404 $cache::TTL_DAY + mt_rand( 0, $cache::TTL_DAY ),
405 function () use ( $wiki, $name ) {
406 global $wgConf;
408 return [ 'v' => $wgConf->getConfig( $wiki, $name ) ];
410 [ 'pcTTL' => WANObjectCache::TTL_PROC_LONG ]
413 return $value['v'];
418 * @param array $jobs
419 * @throws InvalidArgumentException
421 private function assertValidJobs( array $jobs ) {
422 foreach ( $jobs as $job ) { // sanity checks
423 if ( !( $job instanceof IJobSpecification ) ) {
424 throw new InvalidArgumentException( "Expected IJobSpecification objects" );
429 function __destruct() {
430 $n = count( $this->bufferedJobs );
431 if ( $n > 0 ) {
432 $type = implode( ', ', array_unique( array_map( 'get_class', $this->bufferedJobs ) ) );
433 trigger_error( __METHOD__ . ": $n buffered job(s) of type(s) $type never inserted." );