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