Merge "phpunit: Call 'teardownTestDB' from shutdown instead of destruct."
[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 if ( !isset( $conf['readOnlyReason'] ) ) {
118 $conf['readOnlyReason'] = $this->readOnlyReason;
119 }
120
121 return JobQueue::factory( $conf );
122 }
123
124 /**
125 * Insert jobs into the respective queues of which they belong
126 *
127 * This inserts the jobs into the queue specified by $wgJobTypeConf
128 * and updates the aggregate job queue information cache as needed.
129 *
130 * @param IJobSpecification|IJobSpecification[] $jobs A single Job or a list of Jobs
131 * @throws InvalidArgumentException
132 * @return void
133 */
134 public function push( $jobs ) {
135 global $wgJobTypesExcludedFromDefaultQueue;
136
137 if ( $this->invalidDomain ) {
138 // Do not enqueue job that cannot be run (T171371)
139 $e = new LogicException( "Domain '{$this->domain}' is not recognized." );
140 MWExceptionHandler::logException( $e );
141 return;
142 }
143
144 $jobs = is_array( $jobs ) ? $jobs : [ $jobs ];
145 if ( $jobs === [] ) {
146 return;
147 }
148
149 $this->assertValidJobs( $jobs );
150
151 $jobsByType = []; // (job type => list of jobs)
152 foreach ( $jobs as $job ) {
153 $jobsByType[$job->getType()][] = $job;
154 }
155
156 foreach ( $jobsByType as $type => $jobs ) {
157 $this->get( $type )->push( $jobs );
158 }
159
160 if ( $this->cache->hasField( 'queues-ready', 'list' ) ) {
161 $list = $this->cache->getField( 'queues-ready', 'list' );
162 if ( count( array_diff( array_keys( $jobsByType ), $list ) ) ) {
163 $this->cache->clear( 'queues-ready' );
164 }
165 }
166
167 $cache = ObjectCache::getLocalClusterInstance();
168 $cache->set(
169 $cache->makeGlobalKey( 'jobqueue', $this->domain, 'hasjobs', self::TYPE_ANY ),
170 'true',
171 15
172 );
173 if ( array_diff( array_keys( $jobsByType ), $wgJobTypesExcludedFromDefaultQueue ) ) {
174 $cache->set(
175 $cache->makeGlobalKey( 'jobqueue', $this->domain, 'hasjobs', self::TYPE_DEFAULT ),
176 'true',
177 15
178 );
179 }
180 }
181
182 /**
183 * Buffer jobs for insertion via push() or call it now if in CLI mode
184 *
185 * Note that pushLazyJobs() is registered as a deferred update just before
186 * DeferredUpdates::doUpdates() in MediaWiki and JobRunner classes in order
187 * to be executed as the very last deferred update (T100085, T154425).
188 *
189 * @param IJobSpecification|IJobSpecification[] $jobs A single Job or a list of Jobs
190 * @return void
191 * @since 1.26
192 */
193 public function lazyPush( $jobs ) {
194 if ( $this->invalidDomain ) {
195 // Do not enqueue job that cannot be run (T171371)
196 throw new LogicException( "Domain '{$this->domain}' is not recognized." );
197 }
198
199 if ( PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg' ) {
200 $this->push( $jobs );
201 return;
202 }
203
204 $jobs = is_array( $jobs ) ? $jobs : [ $jobs ];
205
206 // Throw errors now instead of on push(), when other jobs may be buffered
207 $this->assertValidJobs( $jobs );
208
209 DeferredUpdates::addUpdate( new JobQueueEnqueueUpdate( $this->domain, $jobs ) );
210 }
211
212 /**
213 * Push all jobs buffered via lazyPush() into their respective queues
214 *
215 * @return void
216 * @since 1.26
217 * @deprecated Since 1.33 Not needed anymore
218 */
219 public static function pushLazyJobs() {
220 wfDeprecated( __METHOD__, '1.33' );
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->domain, '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 string[] List of job types that have non-empty queues
356 */
357 public function getQueuesWithJobs() {
358 $types = [];
359 foreach ( $this->getCoalescedQueues() as $info ) {
360 /** @var JobQueue $queue */
361 $queue = $info['queue'];
362 $nonEmpty = $queue->getSiblingQueuesWithJobs( $this->getQueueTypes() );
363 if ( is_array( $nonEmpty ) ) { // batching features supported
364 $types = array_merge( $types, $nonEmpty );
365 } else { // we have to go through the queues in the bucket one-by-one
366 foreach ( $info['types'] as $type ) {
367 if ( !$this->get( $type )->isEmpty() ) {
368 $types[] = $type;
369 }
370 }
371 }
372 }
373
374 return $types;
375 }
376
377 /**
378 * Get the size of the queus for a list of job types
379 *
380 * @return int[] Map of (job type => size)
381 */
382 public function getQueueSizes() {
383 $sizeMap = [];
384 foreach ( $this->getCoalescedQueues() as $info ) {
385 /** @var JobQueue $queue */
386 $queue = $info['queue'];
387 $sizes = $queue->getSiblingQueueSizes( $this->getQueueTypes() );
388 if ( is_array( $sizes ) ) { // batching features supported
389 $sizeMap = $sizeMap + $sizes;
390 } else { // we have to go through the queues in the bucket one-by-one
391 foreach ( $info['types'] as $type ) {
392 $sizeMap[$type] = $this->get( $type )->getSize();
393 }
394 }
395 }
396
397 return $sizeMap;
398 }
399
400 /**
401 * @return JobQueue[]
402 */
403 protected function getCoalescedQueues() {
404 global $wgJobTypeConf;
405
406 if ( $this->coalescedQueues === null ) {
407 $this->coalescedQueues = [];
408 foreach ( $wgJobTypeConf as $type => $conf ) {
409 $queue = JobQueue::factory(
410 [ 'domain' => $this->domain, 'type' => 'null' ] + $conf );
411 $loc = $queue->getCoalesceLocationInternal();
412 if ( !isset( $this->coalescedQueues[$loc] ) ) {
413 $this->coalescedQueues[$loc]['queue'] = $queue;
414 $this->coalescedQueues[$loc]['types'] = [];
415 }
416 if ( $type === 'default' ) {
417 $this->coalescedQueues[$loc]['types'] = array_merge(
418 $this->coalescedQueues[$loc]['types'],
419 array_diff( $this->getQueueTypes(), array_keys( $wgJobTypeConf ) )
420 );
421 } else {
422 $this->coalescedQueues[$loc]['types'][] = $type;
423 }
424 }
425 }
426
427 return $this->coalescedQueues;
428 }
429
430 /**
431 * @param string $name
432 * @return mixed
433 */
434 private function getCachedConfigVar( $name ) {
435 // @TODO: cleanup this whole method with a proper config system
436 if ( WikiMap::isCurrentWikiDbDomain( $this->domain ) ) {
437 return $GLOBALS[$name]; // common case
438 } else {
439 $wiki = WikiMap::getWikiIdFromDbDomain( $this->domain );
440 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
441 $value = $cache->getWithSetCallback(
442 $cache->makeGlobalKey( 'jobqueue', 'configvalue', $this->domain, $name ),
443 $cache::TTL_DAY + mt_rand( 0, $cache::TTL_DAY ),
444 function () use ( $wiki, $name ) {
445 global $wgConf;
446 // @TODO: use the full domain ID here
447 return [ 'v' => $wgConf->getConfig( $wiki, $name ) ];
448 },
449 [ 'pcTTL' => WANObjectCache::TTL_PROC_LONG ]
450 );
451
452 return $value['v'];
453 }
454 }
455
456 /**
457 * @param array $jobs
458 * @throws InvalidArgumentException
459 */
460 private function assertValidJobs( array $jobs ) {
461 foreach ( $jobs as $job ) { // sanity checks
462 if ( !( $job instanceof IJobSpecification ) ) {
463 throw new InvalidArgumentException( "Expected IJobSpecification objects" );
464 }
465 }
466 }
467 }