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