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