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