Merge "Add curly braces to while"
[mediawiki.git] / includes / jobqueue / JobQueueGroup.php
blob5bd1cc94a858b843af4a8c82b70de10014f380cd
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 = array();
34 /** @var ProcessCacheLRU */
35 protected $cache;
37 /** @var string Wiki ID */
38 protected $wiki;
40 /** @var array Map of (bucket => (queue => JobQueue, types => list of types) */
41 protected $coalescedQueues;
43 /** @var Job[] */
44 protected $bufferedJobs = array();
46 const TYPE_DEFAULT = 1; // integer; jobs popped by default
47 const TYPE_ANY = 2; // integer; any job
49 const USE_CACHE = 1; // integer; use process or persistent cache
51 const PROC_CACHE_TTL = 15; // integer; seconds
53 const CACHE_VERSION = 1; // integer; cache version
55 /**
56 * @param string $wiki Wiki ID
58 protected function __construct( $wiki ) {
59 $this->wiki = $wiki;
60 $this->cache = new ProcessCacheLRU( 10 );
63 /**
64 * @param bool|string $wiki Wiki ID
65 * @return JobQueueGroup
67 public static function singleton( $wiki = false ) {
68 $wiki = ( $wiki === false ) ? wfWikiID() : $wiki;
69 if ( !isset( self::$instances[$wiki] ) ) {
70 self::$instances[$wiki] = new self( $wiki );
73 return self::$instances[$wiki];
76 /**
77 * Destroy the singleton instances
79 * @return void
81 public static function destroySingletons() {
82 self::$instances = array();
85 /**
86 * Get the job queue object for a given queue type
88 * @param string $type
89 * @return JobQueue
91 public function get( $type ) {
92 global $wgJobTypeConf;
94 $conf = array( 'wiki' => $this->wiki, 'type' => $type );
95 if ( isset( $wgJobTypeConf[$type] ) ) {
96 $conf = $conf + $wgJobTypeConf[$type];
97 } else {
98 $conf = $conf + $wgJobTypeConf['default'];
100 $conf['aggregator'] = JobQueueAggregator::singleton();
102 return JobQueue::factory( $conf );
106 * Insert jobs into the respective queues of which they belong
108 * This inserts the jobs into the queue specified by $wgJobTypeConf
109 * and updates the aggregate job queue information cache as needed.
111 * @param IJobSpecification|IJobSpecification[] $jobs A single Job or a list of Jobs
112 * @throws InvalidArgumentException
113 * @return void
115 public function push( $jobs ) {
116 $jobs = is_array( $jobs ) ? $jobs : array( $jobs );
117 if ( !count( $jobs ) ) {
118 return;
121 $this->assertValidJobs( $jobs );
123 $jobsByType = array(); // (job type => list of jobs)
124 foreach ( $jobs as $job ) {
125 $jobsByType[$job->getType()][] = $job;
128 foreach ( $jobsByType as $type => $jobs ) {
129 $this->get( $type )->push( $jobs );
132 if ( $this->cache->has( 'queues-ready', 'list' ) ) {
133 $list = $this->cache->get( 'queues-ready', 'list' );
134 if ( count( array_diff( array_keys( $jobsByType ), $list ) ) ) {
135 $this->cache->clear( 'queues-ready' );
141 * Buffer jobs for insertion via push() or call it now if in CLI mode
143 * Note that MediaWiki::restInPeace() calls pushLazyJobs()
145 * @param IJobSpecification|IJobSpecification[] $jobs A single Job or a list of Jobs
146 * @return void
147 * @since 1.26
149 public function lazyPush( $jobs ) {
150 if ( PHP_SAPI === 'cli' ) {
151 $this->push( $jobs );
152 return;
155 $jobs = is_array( $jobs ) ? $jobs : array( $jobs );
157 // Throw errors now instead of on push(), when other jobs may be buffered
158 $this->assertValidJobs( $jobs );
160 $this->bufferedJobs = array_merge( $this->bufferedJobs, $jobs );
164 * Push all jobs buffered via lazyPush() into their respective queues
166 * @return void
167 * @since 1.26
169 public static function pushLazyJobs() {
170 foreach ( self::$instances as $group ) {
171 $group->push( $group->bufferedJobs );
172 $group->bufferedJobs = array();
177 * Pop a job off one of the job queues
179 * This pops a job off a queue as specified by $wgJobTypeConf and
180 * updates the aggregate job queue information cache as needed.
182 * @param int|string $qtype JobQueueGroup::TYPE_* constant or job type string
183 * @param int $flags Bitfield of JobQueueGroup::USE_* constants
184 * @param array $blacklist List of job types to ignore
185 * @return Job|bool Returns false on failure
187 public function pop( $qtype = self::TYPE_DEFAULT, $flags = 0, array $blacklist = array() ) {
188 $job = false;
190 if ( is_string( $qtype ) ) { // specific job type
191 if ( !in_array( $qtype, $blacklist ) ) {
192 $job = $this->get( $qtype )->pop();
194 } else { // any job in the "default" jobs types
195 if ( $flags & self::USE_CACHE ) {
196 if ( !$this->cache->has( 'queues-ready', 'list', self::PROC_CACHE_TTL ) ) {
197 $this->cache->set( 'queues-ready', 'list', $this->getQueuesWithJobs() );
199 $types = $this->cache->get( 'queues-ready', 'list' );
200 } else {
201 $types = $this->getQueuesWithJobs();
204 if ( $qtype == self::TYPE_DEFAULT ) {
205 $types = array_intersect( $types, $this->getDefaultQueueTypes() );
208 $types = array_diff( $types, $blacklist ); // avoid selected types
209 shuffle( $types ); // avoid starvation
211 foreach ( $types as $type ) { // for each queue...
212 $job = $this->get( $type )->pop();
213 if ( $job ) { // found
214 break;
215 } else { // not found
216 $this->cache->clear( 'queues-ready' );
221 return $job;
225 * Acknowledge that a job was completed
227 * @param Job $job
228 * @return void
230 public function ack( Job $job ) {
231 $this->get( $job->getType() )->ack( $job );
235 * Register the "root job" of a given job into the queue for de-duplication.
236 * This should only be called right *after* all the new jobs have been inserted.
238 * @param Job $job
239 * @return bool
241 public function deduplicateRootJob( Job $job ) {
242 return $this->get( $job->getType() )->deduplicateRootJob( $job );
246 * Wait for any slaves or backup queue servers to catch up.
248 * This does nothing for certain queue classes.
250 * @return void
252 public function waitForBackups() {
253 global $wgJobTypeConf;
255 // Try to avoid doing this more than once per queue storage medium
256 foreach ( $wgJobTypeConf as $type => $conf ) {
257 $this->get( $type )->waitForBackups();
262 * Get the list of queue types
264 * @return array List of strings
266 public function getQueueTypes() {
267 return array_keys( $this->getCachedConfigVar( 'wgJobClasses' ) );
271 * Get the list of default queue types
273 * @return array List of strings
275 public function getDefaultQueueTypes() {
276 global $wgJobTypesExcludedFromDefaultQueue;
278 return array_diff( $this->getQueueTypes(), $wgJobTypesExcludedFromDefaultQueue );
282 * Check if there are any queues with jobs (this is cached)
284 * @param int $type JobQueueGroup::TYPE_* constant
285 * @return bool
286 * @since 1.23
288 public function queuesHaveJobs( $type = self::TYPE_ANY ) {
289 global $wgMemc;
291 $key = wfMemcKey( 'jobqueue', 'queueshavejobs', $type );
293 $value = $wgMemc->get( $key );
294 if ( $value === false ) {
295 $queues = $this->getQueuesWithJobs();
296 if ( $type == self::TYPE_DEFAULT ) {
297 $queues = array_intersect( $queues, $this->getDefaultQueueTypes() );
299 $value = count( $queues ) ? 'true' : 'false';
300 $wgMemc->add( $key, $value, 15 );
303 return ( $value === 'true' );
307 * Get the list of job types that have non-empty queues
309 * @return array List of job types that have non-empty queues
311 public function getQueuesWithJobs() {
312 $types = array();
313 foreach ( $this->getCoalescedQueues() as $info ) {
314 $nonEmpty = $info['queue']->getSiblingQueuesWithJobs( $this->getQueueTypes() );
315 if ( is_array( $nonEmpty ) ) { // batching features supported
316 $types = array_merge( $types, $nonEmpty );
317 } else { // we have to go through the queues in the bucket one-by-one
318 foreach ( $info['types'] as $type ) {
319 if ( !$this->get( $type )->isEmpty() ) {
320 $types[] = $type;
326 return $types;
330 * Get the size of the queus for a list of job types
332 * @return array Map of (job type => size)
334 public function getQueueSizes() {
335 $sizeMap = array();
336 foreach ( $this->getCoalescedQueues() as $info ) {
337 $sizes = $info['queue']->getSiblingQueueSizes( $this->getQueueTypes() );
338 if ( is_array( $sizes ) ) { // batching features supported
339 $sizeMap = $sizeMap + $sizes;
340 } else { // we have to go through the queues in the bucket one-by-one
341 foreach ( $info['types'] as $type ) {
342 $sizeMap[$type] = $this->get( $type )->getSize();
347 return $sizeMap;
351 * @return array
353 protected function getCoalescedQueues() {
354 global $wgJobTypeConf;
356 if ( $this->coalescedQueues === null ) {
357 $this->coalescedQueues = array();
358 foreach ( $wgJobTypeConf as $type => $conf ) {
359 $queue = JobQueue::factory(
360 array( 'wiki' => $this->wiki, 'type' => 'null' ) + $conf );
361 $loc = $queue->getCoalesceLocationInternal();
362 if ( !isset( $this->coalescedQueues[$loc] ) ) {
363 $this->coalescedQueues[$loc]['queue'] = $queue;
364 $this->coalescedQueues[$loc]['types'] = array();
366 if ( $type === 'default' ) {
367 $this->coalescedQueues[$loc]['types'] = array_merge(
368 $this->coalescedQueues[$loc]['types'],
369 array_diff( $this->getQueueTypes(), array_keys( $wgJobTypeConf ) )
371 } else {
372 $this->coalescedQueues[$loc]['types'][] = $type;
377 return $this->coalescedQueues;
381 * @param string $name
382 * @return mixed
384 private function getCachedConfigVar( $name ) {
385 global $wgConf, $wgMemc;
387 if ( $this->wiki === wfWikiID() ) {
388 return $GLOBALS[$name]; // common case
389 } else {
390 list( $db, $prefix ) = wfSplitWikiID( $this->wiki );
391 $key = wfForeignMemcKey( $db, $prefix, 'configvalue', $name );
392 $value = $wgMemc->get( $key ); // ('v' => ...) or false
393 if ( is_array( $value ) ) {
394 return $value['v'];
395 } else {
396 $value = $wgConf->getConfig( $this->wiki, $name );
397 $wgMemc->set( $key, array( 'v' => $value ), 86400 + mt_rand( 0, 86400 ) );
399 return $value;
405 * @param array $jobs
406 * @throws InvalidArgumentException
408 private function assertValidJobs( array $jobs ) {
409 foreach ( $jobs as $job ) { // sanity checks
410 if ( !( $job instanceof IJobSpecification ) ) {
411 throw new InvalidArgumentException( "Expected IJobSpecification objects" );
416 function __destruct() {
417 $n = count( $this->bufferedJobs );
418 if ( $n > 0 ) {
419 $type = implode( ', ', array_unique( array_map( 'get_class', $this->bufferedJobs ) ) );
420 trigger_error( __METHOD__ . ": $n buffered job(s) of type(s) $type never inserted." );