Override momentjs's digit transform logic with MW's
[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
147 /**
148 * Buffer jobs for insertion via push() or call it now if in CLI mode
149 *
150 * Note that MediaWiki::restInPeace() calls pushLazyJobs()
151 *
152 * @param IJobSpecification|IJobSpecification[] $jobs A single Job or a list of Jobs
153 * @return void
154 * @since 1.26
155 */
156 public function lazyPush( $jobs ) {
157 if ( PHP_SAPI === 'cli' ) {
158 $this->push( $jobs );
159 return;
160 }
161
162 $jobs = is_array( $jobs ) ? $jobs : [ $jobs ];
163
164 // Throw errors now instead of on push(), when other jobs may be buffered
165 $this->assertValidJobs( $jobs );
166
167 $this->bufferedJobs = array_merge( $this->bufferedJobs, $jobs );
168 }
169
170 /**
171 * Push all jobs buffered via lazyPush() into their respective queues
172 *
173 * @return void
174 * @since 1.26
175 */
176 public static function pushLazyJobs() {
177 foreach ( self::$instances as $group ) {
178 $group->push( $group->bufferedJobs );
179 $group->bufferedJobs = [];
180 }
181 }
182
183 /**
184 * Pop a job off one of the job queues
185 *
186 * This pops a job off a queue as specified by $wgJobTypeConf and
187 * updates the aggregate job queue information cache as needed.
188 *
189 * @param int|string $qtype JobQueueGroup::TYPE_* constant or job type string
190 * @param int $flags Bitfield of JobQueueGroup::USE_* constants
191 * @param array $blacklist List of job types to ignore
192 * @return Job|bool Returns false on failure
193 */
194 public function pop( $qtype = self::TYPE_DEFAULT, $flags = 0, array $blacklist = [] ) {
195 $job = false;
196
197 if ( is_string( $qtype ) ) { // specific job type
198 if ( !in_array( $qtype, $blacklist ) ) {
199 $job = $this->get( $qtype )->pop();
200 }
201 } else { // any job in the "default" jobs types
202 if ( $flags & self::USE_CACHE ) {
203 if ( !$this->cache->has( 'queues-ready', 'list', self::PROC_CACHE_TTL ) ) {
204 $this->cache->set( 'queues-ready', 'list', $this->getQueuesWithJobs() );
205 }
206 $types = $this->cache->get( 'queues-ready', 'list' );
207 } else {
208 $types = $this->getQueuesWithJobs();
209 }
210
211 if ( $qtype == self::TYPE_DEFAULT ) {
212 $types = array_intersect( $types, $this->getDefaultQueueTypes() );
213 }
214
215 $types = array_diff( $types, $blacklist ); // avoid selected types
216 shuffle( $types ); // avoid starvation
217
218 foreach ( $types as $type ) { // for each queue...
219 $job = $this->get( $type )->pop();
220 if ( $job ) { // found
221 break;
222 } else { // not found
223 $this->cache->clear( 'queues-ready' );
224 }
225 }
226 }
227
228 return $job;
229 }
230
231 /**
232 * Acknowledge that a job was completed
233 *
234 * @param Job $job
235 * @return void
236 */
237 public function ack( Job $job ) {
238 $this->get( $job->getType() )->ack( $job );
239 }
240
241 /**
242 * Register the "root job" of a given job into the queue for de-duplication.
243 * This should only be called right *after* all the new jobs have been inserted.
244 *
245 * @param Job $job
246 * @return bool
247 */
248 public function deduplicateRootJob( Job $job ) {
249 return $this->get( $job->getType() )->deduplicateRootJob( $job );
250 }
251
252 /**
253 * Wait for any slaves or backup queue servers to catch up.
254 *
255 * This does nothing for certain queue classes.
256 *
257 * @return void
258 */
259 public function waitForBackups() {
260 global $wgJobTypeConf;
261
262 // Try to avoid doing this more than once per queue storage medium
263 foreach ( $wgJobTypeConf as $type => $conf ) {
264 $this->get( $type )->waitForBackups();
265 }
266 }
267
268 /**
269 * Get the list of queue types
270 *
271 * @return array List of strings
272 */
273 public function getQueueTypes() {
274 return array_keys( $this->getCachedConfigVar( 'wgJobClasses' ) );
275 }
276
277 /**
278 * Get the list of default queue types
279 *
280 * @return array List of strings
281 */
282 public function getDefaultQueueTypes() {
283 global $wgJobTypesExcludedFromDefaultQueue;
284
285 return array_diff( $this->getQueueTypes(), $wgJobTypesExcludedFromDefaultQueue );
286 }
287
288 /**
289 * Check if there are any queues with jobs (this is cached)
290 *
291 * @param int $type JobQueueGroup::TYPE_* constant
292 * @return bool
293 * @since 1.23
294 */
295 public function queuesHaveJobs( $type = self::TYPE_ANY ) {
296 $key = wfMemcKey( 'jobqueue', 'queueshavejobs', $type );
297 $cache = ObjectCache::getLocalClusterInstance();
298
299 $value = $cache->get( $key );
300 if ( $value === false ) {
301 $queues = $this->getQueuesWithJobs();
302 if ( $type == self::TYPE_DEFAULT ) {
303 $queues = array_intersect( $queues, $this->getDefaultQueueTypes() );
304 }
305 $value = count( $queues ) ? 'true' : 'false';
306 $cache->add( $key, $value, 15 );
307 }
308
309 return ( $value === 'true' );
310 }
311
312 /**
313 * Get the list of job types that have non-empty queues
314 *
315 * @return array List of job types that have non-empty queues
316 */
317 public function getQueuesWithJobs() {
318 $types = [];
319 foreach ( $this->getCoalescedQueues() as $info ) {
320 $nonEmpty = $info['queue']->getSiblingQueuesWithJobs( $this->getQueueTypes() );
321 if ( is_array( $nonEmpty ) ) { // batching features supported
322 $types = array_merge( $types, $nonEmpty );
323 } else { // we have to go through the queues in the bucket one-by-one
324 foreach ( $info['types'] as $type ) {
325 if ( !$this->get( $type )->isEmpty() ) {
326 $types[] = $type;
327 }
328 }
329 }
330 }
331
332 return $types;
333 }
334
335 /**
336 * Get the size of the queus for a list of job types
337 *
338 * @return array Map of (job type => size)
339 */
340 public function getQueueSizes() {
341 $sizeMap = [];
342 foreach ( $this->getCoalescedQueues() as $info ) {
343 $sizes = $info['queue']->getSiblingQueueSizes( $this->getQueueTypes() );
344 if ( is_array( $sizes ) ) { // batching features supported
345 $sizeMap = $sizeMap + $sizes;
346 } else { // we have to go through the queues in the bucket one-by-one
347 foreach ( $info['types'] as $type ) {
348 $sizeMap[$type] = $this->get( $type )->getSize();
349 }
350 }
351 }
352
353 return $sizeMap;
354 }
355
356 /**
357 * @return array
358 */
359 protected function getCoalescedQueues() {
360 global $wgJobTypeConf;
361
362 if ( $this->coalescedQueues === null ) {
363 $this->coalescedQueues = [];
364 foreach ( $wgJobTypeConf as $type => $conf ) {
365 $queue = JobQueue::factory(
366 [ 'wiki' => $this->wiki, 'type' => 'null' ] + $conf );
367 $loc = $queue->getCoalesceLocationInternal();
368 if ( !isset( $this->coalescedQueues[$loc] ) ) {
369 $this->coalescedQueues[$loc]['queue'] = $queue;
370 $this->coalescedQueues[$loc]['types'] = [];
371 }
372 if ( $type === 'default' ) {
373 $this->coalescedQueues[$loc]['types'] = array_merge(
374 $this->coalescedQueues[$loc]['types'],
375 array_diff( $this->getQueueTypes(), array_keys( $wgJobTypeConf ) )
376 );
377 } else {
378 $this->coalescedQueues[$loc]['types'][] = $type;
379 }
380 }
381 }
382
383 return $this->coalescedQueues;
384 }
385
386 /**
387 * @param string $name
388 * @return mixed
389 */
390 private function getCachedConfigVar( $name ) {
391 // @TODO: cleanup this whole method with a proper config system
392 if ( $this->wiki === wfWikiID() ) {
393 return $GLOBALS[$name]; // common case
394 } else {
395 $wiki = $this->wiki;
396 $cache = ObjectCache::getMainWANInstance();
397 $value = $cache->getWithSetCallback(
398 $cache->makeGlobalKey( 'jobqueue', 'configvalue', $wiki, $name ),
399 $cache::TTL_DAY + mt_rand( 0, $cache::TTL_DAY ),
400 function () use ( $wiki, $name ) {
401 global $wgConf;
402
403 return [ 'v' => $wgConf->getConfig( $wiki, $name ) ];
404 },
405 [ 'pcTTL' => 30 ]
406 );
407
408 return $value['v'];
409 }
410 }
411
412 /**
413 * @param array $jobs
414 * @throws InvalidArgumentException
415 */
416 private function assertValidJobs( array $jobs ) {
417 foreach ( $jobs as $job ) { // sanity checks
418 if ( !( $job instanceof IJobSpecification ) ) {
419 throw new InvalidArgumentException( "Expected IJobSpecification objects" );
420 }
421 }
422 }
423
424 function __destruct() {
425 $n = count( $this->bufferedJobs );
426 if ( $n > 0 ) {
427 $type = implode( ', ', array_unique( array_map( 'get_class', $this->bufferedJobs ) ) );
428 trigger_error( __METHOD__ . ": $n buffered job(s) of type(s) $type never inserted." );
429 }
430 }
431 }