Merge "Support changing icon variants on hover"
[lhc/web/wiklou.git] / includes / jobqueue / JobQueueGroup.php
1 <?php
2 /**
3 * Job queue base code.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 * @author Aaron Schulz
22 */
23
24 /**
25 * Class to handle enqueueing of background jobs
26 *
27 * @ingroup JobQueue
28 * @since 1.21
29 */
30 class JobQueueGroup {
31 /** @var array */
32 protected static $instances = array();
33
34 /** @var ProcessCacheLRU */
35 protected $cache;
36
37 /** @var string Wiki ID */
38 protected $wiki;
39
40 /** @var array Map of (bucket => (queue => JobQueue, types => list of types) */
41 protected $coalescedQueues;
42
43 /** @var Job[] */
44 protected $bufferedJobs = array();
45
46 const TYPE_DEFAULT = 1; // integer; jobs popped by default
47 const TYPE_ANY = 2; // integer; any job
48
49 const USE_CACHE = 1; // integer; use process or persistent cache
50
51 const PROC_CACHE_TTL = 15; // integer; seconds
52
53 const CACHE_VERSION = 1; // integer; cache version
54
55 /**
56 * @param string $wiki Wiki ID
57 */
58 protected function __construct( $wiki ) {
59 $this->wiki = $wiki;
60 $this->cache = new ProcessCacheLRU( 10 );
61 }
62
63 /**
64 * @param bool|string $wiki Wiki ID
65 * @return JobQueueGroup
66 */
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 );
71 }
72
73 return self::$instances[$wiki];
74 }
75
76 /**
77 * Destroy the singleton instances
78 *
79 * @return void
80 */
81 public static function destroySingletons() {
82 self::$instances = array();
83 }
84
85 /**
86 * Get the job queue object for a given queue type
87 *
88 * @param string $type
89 * @return JobQueue
90 */
91 public function get( $type ) {
92 global $wgJobTypeConf;
93
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'];
99 }
100 $conf['aggregator'] = JobQueueAggregator::singleton();
101
102 return JobQueue::factory( $conf );
103 }
104
105 /**
106 * Insert jobs into the respective queues of which they belong
107 *
108 * This inserts the jobs into the queue specified by $wgJobTypeConf
109 * and updates the aggregate job queue information cache as needed.
110 *
111 * @param IJobSpecification|IJobSpecification[] $jobs A single Job or a list of Jobs
112 * @throws InvalidArgumentException
113 * @return void
114 */
115 public function push( $jobs ) {
116 $jobs = is_array( $jobs ) ? $jobs : array( $jobs );
117 if ( !count( $jobs ) ) {
118 return;
119 }
120
121 $this->assertValidJobs( $jobs );
122
123 $jobsByType = array(); // (job type => list of jobs)
124 foreach ( $jobs as $job ) {
125 $jobsByType[$job->getType()][] = $job;
126 }
127
128 foreach ( $jobsByType as $type => $jobs ) {
129 $this->get( $type )->push( $jobs );
130 }
131
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' );
136 }
137 }
138 }
139
140 /**
141 * Buffer jobs for insertion via push() or call it now if in CLI mode
142 *
143 * Note that MediaWiki::restInPeace() calls pushLazyJobs()
144 *
145 * @param IJobSpecification|IJobSpecification[] $jobs A single Job or a list of Jobs
146 * @return void
147 * @since 1.26
148 */
149 public function lazyPush( $jobs ) {
150 if ( PHP_SAPI === 'cli' ) {
151 $this->push( $jobs );
152 return;
153 }
154
155 $jobs = is_array( $jobs ) ? $jobs : array( $jobs );
156
157 // Throw errors now instead of on push(), when other jobs may be buffered
158 $this->assertValidJobs( $jobs );
159
160 $this->bufferedJobs = array_merge( $this->bufferedJobs, $jobs );
161 }
162
163 /**
164 * Push all jobs buffered via lazyPush() into their respective queues
165 *
166 * @return void
167 * @since 1.26
168 */
169 public function pushLazyJobs() {
170 $this->push( $this->bufferedJobs );
171
172 $this->bufferedJobs = array();
173 }
174
175 /**
176 * Pop a job off one of the job queues
177 *
178 * This pops a job off a queue as specified by $wgJobTypeConf and
179 * updates the aggregate job queue information cache as needed.
180 *
181 * @param int|string $qtype JobQueueGroup::TYPE_* constant or job type string
182 * @param int $flags Bitfield of JobQueueGroup::USE_* constants
183 * @param array $blacklist List of job types to ignore
184 * @return Job|bool Returns false on failure
185 */
186 public function pop( $qtype = self::TYPE_DEFAULT, $flags = 0, array $blacklist = array() ) {
187 $job = false;
188
189 if ( is_string( $qtype ) ) { // specific job type
190 if ( !in_array( $qtype, $blacklist ) ) {
191 $job = $this->get( $qtype )->pop();
192 }
193 } else { // any job in the "default" jobs types
194 if ( $flags & self::USE_CACHE ) {
195 if ( !$this->cache->has( 'queues-ready', 'list', self::PROC_CACHE_TTL ) ) {
196 $this->cache->set( 'queues-ready', 'list', $this->getQueuesWithJobs() );
197 }
198 $types = $this->cache->get( 'queues-ready', 'list' );
199 } else {
200 $types = $this->getQueuesWithJobs();
201 }
202
203 if ( $qtype == self::TYPE_DEFAULT ) {
204 $types = array_intersect( $types, $this->getDefaultQueueTypes() );
205 }
206
207 $types = array_diff( $types, $blacklist ); // avoid selected types
208 shuffle( $types ); // avoid starvation
209
210 foreach ( $types as $type ) { // for each queue...
211 $job = $this->get( $type )->pop();
212 if ( $job ) { // found
213 break;
214 } else { // not found
215 $this->cache->clear( 'queues-ready' );
216 }
217 }
218 }
219
220 return $job;
221 }
222
223 /**
224 * Acknowledge that a job was completed
225 *
226 * @param Job $job
227 * @return void
228 */
229 public function ack( Job $job ) {
230 $this->get( $job->getType() )->ack( $job );
231 }
232
233 /**
234 * Register the "root job" of a given job into the queue for de-duplication.
235 * This should only be called right *after* all the new jobs have been inserted.
236 *
237 * @param Job $job
238 * @return bool
239 */
240 public function deduplicateRootJob( Job $job ) {
241 return $this->get( $job->getType() )->deduplicateRootJob( $job );
242 }
243
244 /**
245 * Wait for any slaves or backup queue servers to catch up.
246 *
247 * This does nothing for certain queue classes.
248 *
249 * @return void
250 */
251 public function waitForBackups() {
252 global $wgJobTypeConf;
253
254 // Try to avoid doing this more than once per queue storage medium
255 foreach ( $wgJobTypeConf as $type => $conf ) {
256 $this->get( $type )->waitForBackups();
257 }
258 }
259
260 /**
261 * Get the list of queue types
262 *
263 * @return array List of strings
264 */
265 public function getQueueTypes() {
266 return array_keys( $this->getCachedConfigVar( 'wgJobClasses' ) );
267 }
268
269 /**
270 * Get the list of default queue types
271 *
272 * @return array List of strings
273 */
274 public function getDefaultQueueTypes() {
275 global $wgJobTypesExcludedFromDefaultQueue;
276
277 return array_diff( $this->getQueueTypes(), $wgJobTypesExcludedFromDefaultQueue );
278 }
279
280 /**
281 * Check if there are any queues with jobs (this is cached)
282 *
283 * @param int $type JobQueueGroup::TYPE_* constant
284 * @return bool
285 * @since 1.23
286 */
287 public function queuesHaveJobs( $type = self::TYPE_ANY ) {
288 global $wgMemc;
289
290 $key = wfMemcKey( 'jobqueue', 'queueshavejobs', $type );
291
292 $value = $wgMemc->get( $key );
293 if ( $value === false ) {
294 $queues = $this->getQueuesWithJobs();
295 if ( $type == self::TYPE_DEFAULT ) {
296 $queues = array_intersect( $queues, $this->getDefaultQueueTypes() );
297 }
298 $value = count( $queues ) ? 'true' : 'false';
299 $wgMemc->add( $key, $value, 15 );
300 }
301
302 return ( $value === 'true' );
303 }
304
305 /**
306 * Get the list of job types that have non-empty queues
307 *
308 * @return array List of job types that have non-empty queues
309 */
310 public function getQueuesWithJobs() {
311 $types = array();
312 foreach ( $this->getCoalescedQueues() as $info ) {
313 $nonEmpty = $info['queue']->getSiblingQueuesWithJobs( $this->getQueueTypes() );
314 if ( is_array( $nonEmpty ) ) { // batching features supported
315 $types = array_merge( $types, $nonEmpty );
316 } else { // we have to go through the queues in the bucket one-by-one
317 foreach ( $info['types'] as $type ) {
318 if ( !$this->get( $type )->isEmpty() ) {
319 $types[] = $type;
320 }
321 }
322 }
323 }
324
325 return $types;
326 }
327
328 /**
329 * Get the size of the queus for a list of job types
330 *
331 * @return array Map of (job type => size)
332 */
333 public function getQueueSizes() {
334 $sizeMap = array();
335 foreach ( $this->getCoalescedQueues() as $info ) {
336 $sizes = $info['queue']->getSiblingQueueSizes( $this->getQueueTypes() );
337 if ( is_array( $sizes ) ) { // batching features supported
338 $sizeMap = $sizeMap + $sizes;
339 } else { // we have to go through the queues in the bucket one-by-one
340 foreach ( $info['types'] as $type ) {
341 $sizeMap[$type] = $this->get( $type )->getSize();
342 }
343 }
344 }
345
346 return $sizeMap;
347 }
348
349 /**
350 * @return array
351 */
352 protected function getCoalescedQueues() {
353 global $wgJobTypeConf;
354
355 if ( $this->coalescedQueues === null ) {
356 $this->coalescedQueues = array();
357 foreach ( $wgJobTypeConf as $type => $conf ) {
358 $queue = JobQueue::factory(
359 array( 'wiki' => $this->wiki, 'type' => 'null' ) + $conf );
360 $loc = $queue->getCoalesceLocationInternal();
361 if ( !isset( $this->coalescedQueues[$loc] ) ) {
362 $this->coalescedQueues[$loc]['queue'] = $queue;
363 $this->coalescedQueues[$loc]['types'] = array();
364 }
365 if ( $type === 'default' ) {
366 $this->coalescedQueues[$loc]['types'] = array_merge(
367 $this->coalescedQueues[$loc]['types'],
368 array_diff( $this->getQueueTypes(), array_keys( $wgJobTypeConf ) )
369 );
370 } else {
371 $this->coalescedQueues[$loc]['types'][] = $type;
372 }
373 }
374 }
375
376 return $this->coalescedQueues;
377 }
378
379 /**
380 * @param string $name
381 * @return mixed
382 */
383 private function getCachedConfigVar( $name ) {
384 global $wgConf, $wgMemc;
385
386 if ( $this->wiki === wfWikiID() ) {
387 return $GLOBALS[$name]; // common case
388 } else {
389 list( $db, $prefix ) = wfSplitWikiID( $this->wiki );
390 $key = wfForeignMemcKey( $db, $prefix, 'configvalue', $name );
391 $value = $wgMemc->get( $key ); // ('v' => ...) or false
392 if ( is_array( $value ) ) {
393 return $value['v'];
394 } else {
395 $value = $wgConf->getConfig( $this->wiki, $name );
396 $wgMemc->set( $key, array( 'v' => $value ), 86400 + mt_rand( 0, 86400 ) );
397
398 return $value;
399 }
400 }
401 }
402
403 /**
404 * @param array $jobs
405 * @throws InvalidArgumentException
406 */
407 private function assertValidJobs( array $jobs ) {
408 foreach ( $jobs as $job ) { // sanity checks
409 if ( !( $job instanceof IJobSpecification ) ) {
410 throw new InvalidArgumentException( "Expected IJobSpecification objects" );
411 }
412 }
413 }
414
415 function __destruct() {
416 $n = count( $this->bufferedJobs );
417 if ( $n > 0 ) {
418 trigger_error( __METHOD__ . ": $n buffered job(s) never inserted." );
419 $this->pushLazyJobs(); // try to do it now
420 }
421 }
422 }