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