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
21 * @author Aaron Schulz
25 * Class to handle enqueueing of background jobs
31 /** @var JobQueueGroup[] */
32 protected static $instances = [];
34 /** @var ProcessCacheLRU */
37 /** @var string Wiki ID */
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;
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
58 * @param string $wiki Wiki ID
59 * @param string|bool $readOnlyReason Read-only reason or false
61 protected function __construct( $wiki, $readOnlyReason ) {
63 $this->readOnlyReason
= $readOnlyReason;
64 $this->cache
= new ProcessCacheLRU( 10 );
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];
81 * Destroy the singleton instances
85 public static function destroySingletons() {
86 self
::$instances = [];
90 * Get the job queue object for a given queue type
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];
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
122 public function push( $jobs ) {
123 global $wgJobTypesExcludedFromDefaultQueue;
125 $jobs = is_array( $jobs ) ?
$jobs : [ $jobs ];
126 if ( !count( $jobs ) ) {
130 $this->assertValidJobs( $jobs );
132 $jobsByType = []; // (job type => list of jobs)
133 foreach ( $jobs as $job ) {
134 $jobsByType[$job->getType()][] = $job;
137 foreach ( $jobsByType as $type => $jobs ) {
138 $this->get( $type )->push( $jobs );
141 if ( $this->cache
->has( 'queues-ready', 'list' ) ) {
142 $list = $this->cache
->get( 'queues-ready', 'list' );
143 if ( count( array_diff( array_keys( $jobsByType ), $list ) ) ) {
144 $this->cache
->clear( 'queues-ready' );
148 $cache = ObjectCache
::getLocalClusterInstance();
150 $cache->makeGlobalKey( 'jobqueue', $this->wiki
, 'hasjobs', self
::TYPE_ANY
),
154 if ( array_diff( array_keys( $jobsByType ), $wgJobTypesExcludedFromDefaultQueue ) ) {
156 $cache->makeGlobalKey( 'jobqueue', $this->wiki
, 'hasjobs', self
::TYPE_DEFAULT
),
164 * Buffer jobs for insertion via push() or call it now if in CLI mode
166 * Note that pushLazyJobs() is registered as a deferred update just before
167 * DeferredUpdates::doUpdates() in MediaWiki and JobRunner classes in order
168 * to be executed as the very last deferred update (T100085, T154425).
170 * @param IJobSpecification|IJobSpecification[] $jobs A single Job or a list of Jobs
174 public function lazyPush( $jobs ) {
175 if ( PHP_SAPI
=== 'cli' || PHP_SAPI
=== 'phpdbg' ) {
176 $this->push( $jobs );
180 $jobs = is_array( $jobs ) ?
$jobs : [ $jobs ];
182 // Throw errors now instead of on push(), when other jobs may be buffered
183 $this->assertValidJobs( $jobs );
185 $this->bufferedJobs
= array_merge( $this->bufferedJobs
, $jobs );
189 * Push all jobs buffered via lazyPush() into their respective queues
194 public static function pushLazyJobs() {
195 foreach ( self
::$instances as $group ) {
197 $group->push( $group->bufferedJobs
);
198 $group->bufferedJobs
= [];
199 } catch ( Exception
$e ) {
200 // Get in as many jobs as possible and let other post-send updates happen
201 MWExceptionHandler
::logException( $e );
207 * Pop a job off one of the job queues
209 * This pops a job off a queue as specified by $wgJobTypeConf and
210 * updates the aggregate job queue information cache as needed.
212 * @param int|string $qtype JobQueueGroup::TYPE_* constant or job type string
213 * @param int $flags Bitfield of JobQueueGroup::USE_* constants
214 * @param array $blacklist List of job types to ignore
215 * @return Job|bool Returns false on failure
217 public function pop( $qtype = self
::TYPE_DEFAULT
, $flags = 0, array $blacklist = [] ) {
220 if ( is_string( $qtype ) ) { // specific job type
221 if ( !in_array( $qtype, $blacklist ) ) {
222 $job = $this->get( $qtype )->pop();
224 } else { // any job in the "default" jobs types
225 if ( $flags & self
::USE_CACHE
) {
226 if ( !$this->cache
->has( 'queues-ready', 'list', self
::PROC_CACHE_TTL
) ) {
227 $this->cache
->set( 'queues-ready', 'list', $this->getQueuesWithJobs() );
229 $types = $this->cache
->get( 'queues-ready', 'list' );
231 $types = $this->getQueuesWithJobs();
234 if ( $qtype == self
::TYPE_DEFAULT
) {
235 $types = array_intersect( $types, $this->getDefaultQueueTypes() );
238 $types = array_diff( $types, $blacklist ); // avoid selected types
239 shuffle( $types ); // avoid starvation
241 foreach ( $types as $type ) { // for each queue...
242 $job = $this->get( $type )->pop();
243 if ( $job ) { // found
245 } else { // not found
246 $this->cache
->clear( 'queues-ready' );
255 * Acknowledge that a job was completed
260 public function ack( Job
$job ) {
261 $this->get( $job->getType() )->ack( $job );
265 * Register the "root job" of a given job into the queue for de-duplication.
266 * This should only be called right *after* all the new jobs have been inserted.
271 public function deduplicateRootJob( Job
$job ) {
272 return $this->get( $job->getType() )->deduplicateRootJob( $job );
276 * Wait for any replica DBs or backup queue servers to catch up.
278 * This does nothing for certain queue classes.
282 public function waitForBackups() {
283 global $wgJobTypeConf;
285 // Try to avoid doing this more than once per queue storage medium
286 foreach ( $wgJobTypeConf as $type => $conf ) {
287 $this->get( $type )->waitForBackups();
292 * Get the list of queue types
294 * @return array List of strings
296 public function getQueueTypes() {
297 return array_keys( $this->getCachedConfigVar( 'wgJobClasses' ) );
301 * Get the list of default queue types
303 * @return array List of strings
305 public function getDefaultQueueTypes() {
306 global $wgJobTypesExcludedFromDefaultQueue;
308 return array_diff( $this->getQueueTypes(), $wgJobTypesExcludedFromDefaultQueue );
312 * Check if there are any queues with jobs (this is cached)
314 * @param int $type JobQueueGroup::TYPE_* constant
318 public function queuesHaveJobs( $type = self
::TYPE_ANY
) {
319 $cache = ObjectCache
::getLocalClusterInstance();
320 $key = $cache->makeGlobalKey( 'jobqueue', $this->wiki
, 'hasjobs', $type );
322 $value = $cache->get( $key );
323 if ( $value === false ) {
324 $queues = $this->getQueuesWithJobs();
325 if ( $type == self
::TYPE_DEFAULT
) {
326 $queues = array_intersect( $queues, $this->getDefaultQueueTypes() );
328 $value = count( $queues ) ?
'true' : 'false';
329 $cache->add( $key, $value, 15 );
332 return ( $value === 'true' );
336 * Get the list of job types that have non-empty queues
338 * @return array List of job types that have non-empty queues
340 public function getQueuesWithJobs() {
342 foreach ( $this->getCoalescedQueues() as $info ) {
343 $nonEmpty = $info['queue']->getSiblingQueuesWithJobs( $this->getQueueTypes() );
344 if ( is_array( $nonEmpty ) ) { // batching features supported
345 $types = array_merge( $types, $nonEmpty );
346 } else { // we have to go through the queues in the bucket one-by-one
347 foreach ( $info['types'] as $type ) {
348 if ( !$this->get( $type )->isEmpty() ) {
359 * Get the size of the queus for a list of job types
361 * @return array Map of (job type => size)
363 public function getQueueSizes() {
365 foreach ( $this->getCoalescedQueues() as $info ) {
366 $sizes = $info['queue']->getSiblingQueueSizes( $this->getQueueTypes() );
367 if ( is_array( $sizes ) ) { // batching features supported
368 $sizeMap = $sizeMap +
$sizes;
369 } else { // we have to go through the queues in the bucket one-by-one
370 foreach ( $info['types'] as $type ) {
371 $sizeMap[$type] = $this->get( $type )->getSize();
382 protected function getCoalescedQueues() {
383 global $wgJobTypeConf;
385 if ( $this->coalescedQueues
=== null ) {
386 $this->coalescedQueues
= [];
387 foreach ( $wgJobTypeConf as $type => $conf ) {
388 $queue = JobQueue
::factory(
389 [ 'wiki' => $this->wiki
, 'type' => 'null' ] +
$conf );
390 $loc = $queue->getCoalesceLocationInternal();
391 if ( !isset( $this->coalescedQueues
[$loc] ) ) {
392 $this->coalescedQueues
[$loc]['queue'] = $queue;
393 $this->coalescedQueues
[$loc]['types'] = [];
395 if ( $type === 'default' ) {
396 $this->coalescedQueues
[$loc]['types'] = array_merge(
397 $this->coalescedQueues
[$loc]['types'],
398 array_diff( $this->getQueueTypes(), array_keys( $wgJobTypeConf ) )
401 $this->coalescedQueues
[$loc]['types'][] = $type;
406 return $this->coalescedQueues
;
410 * @param string $name
413 private function getCachedConfigVar( $name ) {
414 // @TODO: cleanup this whole method with a proper config system
415 if ( $this->wiki
=== wfWikiID() ) {
416 return $GLOBALS[$name]; // common case
419 $cache = ObjectCache
::getMainWANInstance();
420 $value = $cache->getWithSetCallback(
421 $cache->makeGlobalKey( 'jobqueue', 'configvalue', $wiki, $name ),
422 $cache::TTL_DAY +
mt_rand( 0, $cache::TTL_DAY
),
423 function () use ( $wiki, $name ) {
426 return [ 'v' => $wgConf->getConfig( $wiki, $name ) ];
428 [ 'pcTTL' => WANObjectCache
::TTL_PROC_LONG
]
437 * @throws InvalidArgumentException
439 private function assertValidJobs( array $jobs ) {
440 foreach ( $jobs as $job ) { // sanity checks
441 if ( !( $job instanceof IJobSpecification
) ) {
442 throw new InvalidArgumentException( "Expected IJobSpecification objects" );
447 function __destruct() {
448 $n = count( $this->bufferedJobs
);
450 $type = implode( ', ', array_unique( array_map( 'get_class', $this->bufferedJobs
) ) );
451 trigger_error( __METHOD__
. ": $n buffered job(s) of type(s) $type never inserted." );