Merge "Add anchor "mw-oldid" for beginning of page content in diff view"
[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 array */
32 protected static $instances = array();
33
34 /** @var ProcessCacheLRU */
35 protected $cache;
36
37 /** @var string Wiki ID */
38 protected $wiki;
39
40 /** @var array Map of (bucket => (queue => JobQueue, types => list of types) */
41 protected $coalescedQueues;
42
43 const TYPE_DEFAULT = 1; // integer; jobs popped by default
44 const TYPE_ANY = 2; // integer; any job
45
46 const USE_CACHE = 1; // integer; use process or persistent cache
47
48 const PROC_CACHE_TTL = 15; // integer; seconds
49
50 const CACHE_VERSION = 1; // integer; cache version
51
52 /**
53 * @param string $wiki Wiki ID
54 */
55 protected function __construct( $wiki ) {
56 $this->wiki = $wiki;
57 $this->cache = new ProcessCacheLRU( 10 );
58 }
59
60 /**
61 * @param bool|string $wiki Wiki ID
62 * @return JobQueueGroup
63 */
64 public static function singleton( $wiki = false ) {
65 $wiki = ( $wiki === false ) ? wfWikiID() : $wiki;
66 if ( !isset( self::$instances[$wiki] ) ) {
67 self::$instances[$wiki] = new self( $wiki );
68 }
69
70 return self::$instances[$wiki];
71 }
72
73 /**
74 * Destroy the singleton instances
75 *
76 * @return void
77 */
78 public static function destroySingletons() {
79 self::$instances = array();
80 }
81
82 /**
83 * Get the job queue object for a given queue type
84 *
85 * @param string $type
86 * @return JobQueue
87 */
88 public function get( $type ) {
89 global $wgJobTypeConf;
90
91 $conf = array( 'wiki' => $this->wiki, 'type' => $type );
92 if ( isset( $wgJobTypeConf[$type] ) ) {
93 $conf = $conf + $wgJobTypeConf[$type];
94 } else {
95 $conf = $conf + $wgJobTypeConf['default'];
96 }
97 $conf['aggregator'] = JobQueueAggregator::singleton();
98
99 return JobQueue::factory( $conf );
100 }
101
102 /**
103 * Insert jobs into the respective queues of with the belong.
104 *
105 * This inserts the jobs into the queue specified by $wgJobTypeConf
106 * and updates the aggregate job queue information cache as needed.
107 *
108 * @param Job|Job[] $jobs A single Job or a list of Jobs
109 * @throws MWException
110 * @return void
111 */
112 public function push( $jobs ) {
113 $jobs = is_array( $jobs ) ? $jobs : array( $jobs );
114 if ( !count( $jobs ) ) {
115 return;
116 }
117
118 $jobsByType = array(); // (job type => list of jobs)
119 foreach ( $jobs as $job ) {
120 if ( $job instanceof IJobSpecification ) {
121 $jobsByType[$job->getType()][] = $job;
122 } else {
123 throw new MWException( "Attempted to push a non-Job object into a queue." );
124 }
125 }
126
127 foreach ( $jobsByType as $type => $jobs ) {
128 $this->get( $type )->push( $jobs );
129 }
130
131 if ( $this->cache->has( 'queues-ready', 'list' ) ) {
132 $list = $this->cache->get( 'queues-ready', 'list' );
133 if ( count( array_diff( array_keys( $jobsByType ), $list ) ) ) {
134 $this->cache->clear( 'queues-ready' );
135 }
136 }
137 }
138
139 /**
140 * Pop a job off one of the job queues
141 *
142 * This pops a job off a queue as specified by $wgJobTypeConf and
143 * updates the aggregate job queue information cache as needed.
144 *
145 * @param int|string $qtype JobQueueGroup::TYPE_* constant or job type string
146 * @param int $flags Bitfield of JobQueueGroup::USE_* constants
147 * @param array $blacklist List of job types to ignore
148 * @return Job|bool Returns false on failure
149 */
150 public function pop( $qtype = self::TYPE_DEFAULT, $flags = 0, array $blacklist = array() ) {
151 $job = false;
152
153 if ( is_string( $qtype ) ) { // specific job type
154 if ( !in_array( $qtype, $blacklist ) ) {
155 $job = $this->get( $qtype )->pop();
156 }
157 } else { // any job in the "default" jobs types
158 if ( $flags & self::USE_CACHE ) {
159 if ( !$this->cache->has( 'queues-ready', 'list', self::PROC_CACHE_TTL ) ) {
160 $this->cache->set( 'queues-ready', 'list', $this->getQueuesWithJobs() );
161 }
162 $types = $this->cache->get( 'queues-ready', 'list' );
163 } else {
164 $types = $this->getQueuesWithJobs();
165 }
166
167 if ( $qtype == self::TYPE_DEFAULT ) {
168 $types = array_intersect( $types, $this->getDefaultQueueTypes() );
169 }
170
171 $types = array_diff( $types, $blacklist ); // avoid selected types
172 shuffle( $types ); // avoid starvation
173
174 foreach ( $types as $type ) { // for each queue...
175 $job = $this->get( $type )->pop();
176 if ( $job ) { // found
177 break;
178 } else { // not found
179 $this->cache->clear( 'queues-ready' );
180 }
181 }
182 }
183
184 return $job;
185 }
186
187 /**
188 * Acknowledge that a job was completed
189 *
190 * @param Job $job
191 * @return bool
192 */
193 public function ack( Job $job ) {
194 return $this->get( $job->getType() )->ack( $job );
195 }
196
197 /**
198 * Register the "root job" of a given job into the queue for de-duplication.
199 * This should only be called right *after* all the new jobs have been inserted.
200 *
201 * @param Job $job
202 * @return bool
203 */
204 public function deduplicateRootJob( Job $job ) {
205 return $this->get( $job->getType() )->deduplicateRootJob( $job );
206 }
207
208 /**
209 * Wait for any slaves or backup queue servers to catch up.
210 *
211 * This does nothing for certain queue classes.
212 *
213 * @return void
214 * @throws MWException
215 */
216 public function waitForBackups() {
217 global $wgJobTypeConf;
218
219 // Try to avoid doing this more than once per queue storage medium
220 foreach ( $wgJobTypeConf as $type => $conf ) {
221 $this->get( $type )->waitForBackups();
222 }
223 }
224
225 /**
226 * Get the list of queue types
227 *
228 * @return array List of strings
229 */
230 public function getQueueTypes() {
231 return array_keys( $this->getCachedConfigVar( 'wgJobClasses' ) );
232 }
233
234 /**
235 * Get the list of default queue types
236 *
237 * @return array List of strings
238 */
239 public function getDefaultQueueTypes() {
240 global $wgJobTypesExcludedFromDefaultQueue;
241
242 return array_diff( $this->getQueueTypes(), $wgJobTypesExcludedFromDefaultQueue );
243 }
244
245 /**
246 * Check if there are any queues with jobs (this is cached)
247 *
248 * @param int $type JobQueueGroup::TYPE_* constant
249 * @return bool
250 * @since 1.23
251 */
252 public function queuesHaveJobs( $type = self::TYPE_ANY ) {
253 global $wgMemc;
254
255 $key = wfMemcKey( 'jobqueue', 'queueshavejobs', $type );
256
257 $value = $wgMemc->get( $key );
258 if ( $value === false ) {
259 $queues = $this->getQueuesWithJobs();
260 if ( $type == self::TYPE_DEFAULT ) {
261 $queues = array_intersect( $queues, $this->getDefaultQueueTypes() );
262 }
263 $value = count( $queues ) ? 'true' : 'false';
264 $wgMemc->add( $key, $value, 15 );
265 }
266
267 return ( $value === 'true' );
268 }
269
270 /**
271 * Get the list of job types that have non-empty queues
272 *
273 * @return array List of job types that have non-empty queues
274 */
275 public function getQueuesWithJobs() {
276 $types = array();
277 foreach ( $this->getCoalescedQueues() as $info ) {
278 $nonEmpty = $info['queue']->getSiblingQueuesWithJobs( $this->getQueueTypes() );
279 if ( is_array( $nonEmpty ) ) { // batching features supported
280 $types = array_merge( $types, $nonEmpty );
281 } else { // we have to go through the queues in the bucket one-by-one
282 foreach ( $info['types'] as $type ) {
283 if ( !$this->get( $type )->isEmpty() ) {
284 $types[] = $type;
285 }
286 }
287 }
288 }
289
290 return $types;
291 }
292
293 /**
294 * Get the size of the queus for a list of job types
295 *
296 * @return array Map of (job type => size)
297 */
298 public function getQueueSizes() {
299 $sizeMap = array();
300 foreach ( $this->getCoalescedQueues() as $info ) {
301 $sizes = $info['queue']->getSiblingQueueSizes( $this->getQueueTypes() );
302 if ( is_array( $sizes ) ) { // batching features supported
303 $sizeMap = $sizeMap + $sizes;
304 } else { // we have to go through the queues in the bucket one-by-one
305 foreach ( $info['types'] as $type ) {
306 $sizeMap[$type] = $this->get( $type )->getSize();
307 }
308 }
309 }
310
311 return $sizeMap;
312 }
313
314 /**
315 * @return array
316 */
317 protected function getCoalescedQueues() {
318 global $wgJobTypeConf;
319
320 if ( $this->coalescedQueues === null ) {
321 $this->coalescedQueues = array();
322 foreach ( $wgJobTypeConf as $type => $conf ) {
323 $queue = JobQueue::factory(
324 array( 'wiki' => $this->wiki, 'type' => 'null' ) + $conf );
325 $loc = $queue->getCoalesceLocationInternal();
326 if ( !isset( $this->coalescedQueues[$loc] ) ) {
327 $this->coalescedQueues[$loc]['queue'] = $queue;
328 $this->coalescedQueues[$loc]['types'] = array();
329 }
330 if ( $type === 'default' ) {
331 $this->coalescedQueues[$loc]['types'] = array_merge(
332 $this->coalescedQueues[$loc]['types'],
333 array_diff( $this->getQueueTypes(), array_keys( $wgJobTypeConf ) )
334 );
335 } else {
336 $this->coalescedQueues[$loc]['types'][] = $type;
337 }
338 }
339 }
340
341 return $this->coalescedQueues;
342 }
343
344 /**
345 * Execute any due periodic queue maintenance tasks for all queues.
346 *
347 * A task is "due" if the time ellapsed since the last run is greater than
348 * the defined run period. Concurrent calls to this function will cause tasks
349 * to be attempted twice, so they may need their own methods of mutual exclusion.
350 *
351 * @return int Number of tasks run
352 */
353 public function executeReadyPeriodicTasks() {
354 global $wgMemc;
355
356 list( $db, $prefix ) = wfSplitWikiID( $this->wiki );
357 $key = wfForeignMemcKey( $db, $prefix, 'jobqueuegroup', 'taskruns', 'v1' );
358 $lastRuns = $wgMemc->get( $key ); // (queue => task => UNIX timestamp)
359
360 $count = 0;
361 $tasksRun = array(); // (queue => task => UNIX timestamp)
362 foreach ( $this->getQueueTypes() as $type ) {
363 $queue = $this->get( $type );
364 foreach ( $queue->getPeriodicTasks() as $task => $definition ) {
365 if ( $definition['period'] <= 0 ) {
366 continue; // disabled
367 } elseif ( !isset( $lastRuns[$type][$task] )
368 || $lastRuns[$type][$task] < ( time() - $definition['period'] )
369 ) {
370 try {
371 if ( call_user_func( $definition['callback'] ) !== null ) {
372 $tasksRun[$type][$task] = time();
373 ++$count;
374 }
375 } catch ( JobQueueError $e ) {
376 MWExceptionHandler::logException( $e );
377 }
378 }
379 }
380 }
381
382 if ( $count === 0 ) {
383 return $count; // nothing to update
384 }
385
386 $wgMemc->merge( $key, function ( $cache, $key, $lastRuns ) use ( $tasksRun ) {
387 if ( is_array( $lastRuns ) ) {
388 foreach ( $tasksRun as $type => $tasks ) {
389 foreach ( $tasks as $task => $timestamp ) {
390 if ( !isset( $lastRuns[$type][$task] )
391 || $timestamp > $lastRuns[$type][$task]
392 ) {
393 $lastRuns[$type][$task] = $timestamp;
394 }
395 }
396 }
397 } else {
398 $lastRuns = $tasksRun;
399 }
400
401 return $lastRuns;
402 } );
403
404 return $count;
405 }
406
407 /**
408 * @param string $name
409 * @return mixed
410 */
411 private function getCachedConfigVar( $name ) {
412 global $wgConf, $wgMemc;
413
414 if ( $this->wiki === wfWikiID() ) {
415 return $GLOBALS[$name]; // common case
416 } else {
417 list( $db, $prefix ) = wfSplitWikiID( $this->wiki );
418 $key = wfForeignMemcKey( $db, $prefix, 'configvalue', $name );
419 $value = $wgMemc->get( $key ); // ('v' => ...) or false
420 if ( is_array( $value ) ) {
421 return $value['v'];
422 } else {
423 $value = $wgConf->getConfig( $this->wiki, $name );
424 $wgMemc->set( $key, array( 'v' => $value ), 86400 + mt_rand( 0, 86400 ) );
425
426 return $value;
427 }
428 }
429 }
430 }