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