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