Merge "Http::getProxy() method to get proxy configuration"
[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 JobQueueGroup[] */
32 protected static $instances = [];
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 = [];
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 = [];
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 = [ '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 : [ $jobs ];
117 if ( !count( $jobs ) ) {
118 return;
119 }
120
121 $this->assertValidJobs( $jobs );
122
123 $jobsByType = []; // (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 : [ $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 static function pushLazyJobs() {
170 foreach ( self::$instances as $group ) {
171 $group->push( $group->bufferedJobs );
172 $group->bufferedJobs = [];
173 }
174 }
175
176 /**
177 * Pop a job off one of the job queues
178 *
179 * This pops a job off a queue as specified by $wgJobTypeConf and
180 * updates the aggregate job queue information cache as needed.
181 *
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
186 */
187 public function pop( $qtype = self::TYPE_DEFAULT, $flags = 0, array $blacklist = [] ) {
188 $job = false;
189
190 if ( is_string( $qtype ) ) { // specific job type
191 if ( !in_array( $qtype, $blacklist ) ) {
192 $job = $this->get( $qtype )->pop();
193 }
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() );
198 }
199 $types = $this->cache->get( 'queues-ready', 'list' );
200 } else {
201 $types = $this->getQueuesWithJobs();
202 }
203
204 if ( $qtype == self::TYPE_DEFAULT ) {
205 $types = array_intersect( $types, $this->getDefaultQueueTypes() );
206 }
207
208 $types = array_diff( $types, $blacklist ); // avoid selected types
209 shuffle( $types ); // avoid starvation
210
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' );
217 }
218 }
219 }
220
221 return $job;
222 }
223
224 /**
225 * Acknowledge that a job was completed
226 *
227 * @param Job $job
228 * @return void
229 */
230 public function ack( Job $job ) {
231 $this->get( $job->getType() )->ack( $job );
232 }
233
234 /**
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.
237 *
238 * @param Job $job
239 * @return bool
240 */
241 public function deduplicateRootJob( Job $job ) {
242 return $this->get( $job->getType() )->deduplicateRootJob( $job );
243 }
244
245 /**
246 * Wait for any slaves or backup queue servers to catch up.
247 *
248 * This does nothing for certain queue classes.
249 *
250 * @return void
251 */
252 public function waitForBackups() {
253 global $wgJobTypeConf;
254
255 // Try to avoid doing this more than once per queue storage medium
256 foreach ( $wgJobTypeConf as $type => $conf ) {
257 $this->get( $type )->waitForBackups();
258 }
259 }
260
261 /**
262 * Get the list of queue types
263 *
264 * @return array List of strings
265 */
266 public function getQueueTypes() {
267 return array_keys( $this->getCachedConfigVar( 'wgJobClasses' ) );
268 }
269
270 /**
271 * Get the list of default queue types
272 *
273 * @return array List of strings
274 */
275 public function getDefaultQueueTypes() {
276 global $wgJobTypesExcludedFromDefaultQueue;
277
278 return array_diff( $this->getQueueTypes(), $wgJobTypesExcludedFromDefaultQueue );
279 }
280
281 /**
282 * Check if there are any queues with jobs (this is cached)
283 *
284 * @param int $type JobQueueGroup::TYPE_* constant
285 * @return bool
286 * @since 1.23
287 */
288 public function queuesHaveJobs( $type = self::TYPE_ANY ) {
289 $key = wfMemcKey( 'jobqueue', 'queueshavejobs', $type );
290 $cache = ObjectCache::getLocalClusterInstance();
291
292 $value = $cache->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 $cache->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 = [];
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 = [];
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 = [];
357 foreach ( $wgJobTypeConf as $type => $conf ) {
358 $queue = JobQueue::factory(
359 [ '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'] = [];
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 // @TODO: cleanup this whole method with a proper config system
385 if ( $this->wiki === wfWikiID() ) {
386 return $GLOBALS[$name]; // common case
387 } else {
388 $wiki = $this->wiki;
389 $cache = ObjectCache::getMainWANInstance();
390 $value = $cache->getWithSetCallback(
391 $cache->makeGlobalKey( 'jobqueue', 'configvalue', $wiki, $name ),
392 $cache::TTL_DAY + mt_rand( 0, $cache::TTL_DAY ),
393 function () use ( $wiki, $name ) {
394 global $wgConf;
395
396 return [ 'v' => $wgConf->getConfig( $wiki, $name ) ];
397 },
398 [ 'pcTTL' => 30 ]
399 );
400
401 return $value['v'];
402 }
403 }
404
405 /**
406 * @param array $jobs
407 * @throws InvalidArgumentException
408 */
409 private function assertValidJobs( array $jobs ) {
410 foreach ( $jobs as $job ) { // sanity checks
411 if ( !( $job instanceof IJobSpecification ) ) {
412 throw new InvalidArgumentException( "Expected IJobSpecification objects" );
413 }
414 }
415 }
416
417 function __destruct() {
418 $n = count( $this->bufferedJobs );
419 if ( $n > 0 ) {
420 $type = implode( ', ', array_unique( array_map( 'get_class', $this->bufferedJobs ) ) );
421 trigger_error( __METHOD__ . ": $n buffered job(s) of type(s) $type never inserted." );
422 }
423 }
424 }