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