Merge "Removed isQueueDeprioritized()"
[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 /** @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 const USE_PRIORITY = 2; // integer; respect deprioritization
48
49 const PROC_CACHE_TTL = 15; // integer; seconds
50
51 const CACHE_VERSION = 1; // integer; cache version
52
53 /**
54 * @param string $wiki Wiki ID
55 */
56 protected function __construct( $wiki ) {
57 $this->wiki = $wiki;
58 $this->cache = new ProcessCacheLRU( 10 );
59 }
60
61 /**
62 * @param bool|string $wiki Wiki ID
63 * @return JobQueueGroup
64 */
65 public static function singleton( $wiki = false ) {
66 $wiki = ( $wiki === false ) ? wfWikiID() : $wiki;
67 if ( !isset( self::$instances[$wiki] ) ) {
68 self::$instances[$wiki] = new self( $wiki );
69 }
70
71 return self::$instances[$wiki];
72 }
73
74 /**
75 * Destroy the singleton instances
76 *
77 * @return void
78 */
79 public static function destroySingletons() {
80 self::$instances = array();
81 }
82
83 /**
84 * Get the job queue object for a given queue type
85 *
86 * @param string $type
87 * @return JobQueue
88 */
89 public function get( $type ) {
90 global $wgJobTypeConf;
91
92 $conf = array( 'wiki' => $this->wiki, 'type' => $type );
93 if ( isset( $wgJobTypeConf[$type] ) ) {
94 $conf = $conf + $wgJobTypeConf[$type];
95 } else {
96 $conf = $conf + $wgJobTypeConf['default'];
97 }
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|array $jobs A single Job or a list of Jobs
109 * @throws MWException
110 * @return bool
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 Job ) {
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 $ok = true;
128 foreach ( $jobsByType as $type => $jobs ) {
129 if ( $this->get( $type )->push( $jobs ) ) {
130 JobQueueAggregator::singleton()->notifyQueueNonEmpty( $this->wiki, $type );
131 } else {
132 $ok = false;
133 }
134 }
135
136 if ( $this->cache->has( 'queues-ready', 'list' ) ) {
137 $list = $this->cache->get( 'queues-ready', 'list' );
138 if ( count( array_diff( array_keys( $jobsByType ), $list ) ) ) {
139 $this->cache->clear( 'queues-ready' );
140 }
141 }
142
143 return $ok;
144 }
145
146 /**
147 * Pop a job off one of the job queues
148 *
149 * This pops a job off a queue as specified by $wgJobTypeConf and
150 * updates the aggregate job queue information cache as needed.
151 *
152 * @param int|string $qtype JobQueueGroup::TYPE_DEFAULT or type string
153 * @param int $flags Bitfield of JobQueueGroup::USE_* constants
154 * @return Job|bool Returns false on failure
155 */
156 public function pop( $qtype = self::TYPE_DEFAULT, $flags = 0 ) {
157 if ( is_string( $qtype ) ) { // specific job type
158 $job = $this->get( $qtype )->pop();
159 if ( !$job ) {
160 JobQueueAggregator::singleton()->notifyQueueEmpty( $this->wiki, $qtype );
161 }
162
163 return $job;
164 } else { // any job in the "default" jobs types
165 if ( $flags & self::USE_CACHE ) {
166 if ( !$this->cache->has( 'queues-ready', 'list', self::PROC_CACHE_TTL ) ) {
167 $this->cache->set( 'queues-ready', 'list', $this->getQueuesWithJobs() );
168 }
169 $types = $this->cache->get( 'queues-ready', 'list' );
170 } else {
171 $types = $this->getQueuesWithJobs();
172 }
173
174 if ( $qtype == self::TYPE_DEFAULT ) {
175 $types = array_intersect( $types, $this->getDefaultQueueTypes() );
176 }
177 shuffle( $types ); // avoid starvation
178
179 foreach ( $types as $type ) { // for each queue...
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
273 return $types;
274 }
275
276 /**
277 * Get the size of the queus for a list of job types
278 *
279 * @return array Map of (job type => size)
280 */
281 public function getQueueSizes() {
282 $sizeMap = array();
283 foreach ( $this->getCoalescedQueues() as $info ) {
284 $sizes = $info['queue']->getSiblingQueueSizes( $this->getQueueTypes() );
285 if ( is_array( $sizes ) ) { // batching features supported
286 $sizeMap = $sizeMap + $sizes;
287 } else { // we have to go through the queues in the bucket one-by-one
288 foreach ( $info['types'] as $type ) {
289 $sizeMap[$type] = $this->get( $type )->getSize();
290 }
291 }
292 }
293
294 return $sizeMap;
295 }
296
297 /**
298 * @return array
299 */
300 protected function getCoalescedQueues() {
301 global $wgJobTypeConf;
302
303 if ( $this->coalescedQueues === null ) {
304 $this->coalescedQueues = array();
305 foreach ( $wgJobTypeConf as $type => $conf ) {
306 $queue = JobQueue::factory(
307 array( 'wiki' => $this->wiki, 'type' => 'null' ) + $conf );
308 $loc = $queue->getCoalesceLocationInternal();
309 if ( !isset( $this->coalescedQueues[$loc] ) ) {
310 $this->coalescedQueues[$loc]['queue'] = $queue;
311 $this->coalescedQueues[$loc]['types'] = array();
312 }
313 if ( $type === 'default' ) {
314 $this->coalescedQueues[$loc]['types'] = array_merge(
315 $this->coalescedQueues[$loc]['types'],
316 array_diff( $this->getQueueTypes(), array_keys( $wgJobTypeConf ) )
317 );
318 } else {
319 $this->coalescedQueues[$loc]['types'][] = $type;
320 }
321 }
322 }
323
324 return $this->coalescedQueues;
325 }
326
327 /**
328 * Execute any due periodic queue maintenance tasks for all queues.
329 *
330 * A task is "due" if the time ellapsed since the last run is greater than
331 * the defined run period. Concurrent calls to this function will cause tasks
332 * to be attempted twice, so they may need their own methods of mutual exclusion.
333 *
334 * @return int Number of tasks run
335 */
336 public function executeReadyPeriodicTasks() {
337 global $wgMemc;
338
339 list( $db, $prefix ) = wfSplitWikiID( $this->wiki );
340 $key = wfForeignMemcKey( $db, $prefix, 'jobqueuegroup', 'taskruns', 'v1' );
341 $lastRuns = $wgMemc->get( $key ); // (queue => task => UNIX timestamp)
342
343 $count = 0;
344 $tasksRun = array(); // (queue => task => UNIX timestamp)
345 foreach ( $this->getQueueTypes() as $type ) {
346 $queue = $this->get( $type );
347 foreach ( $queue->getPeriodicTasks() as $task => $definition ) {
348 if ( $definition['period'] <= 0 ) {
349 continue; // disabled
350 } elseif ( !isset( $lastRuns[$type][$task] )
351 || $lastRuns[$type][$task] < ( time() - $definition['period'] )
352 ) {
353 try {
354 if ( call_user_func( $definition['callback'] ) !== null ) {
355 $tasksRun[$type][$task] = time();
356 ++$count;
357 }
358 } catch ( JobQueueError $e ) {
359 MWExceptionHandler::logException( $e );
360 }
361 }
362 }
363 // The tasks may have recycled jobs or release delayed jobs into the queue
364 if ( isset( $tasksRun[$type] ) && !$queue->isEmpty() ) {
365 JobQueueAggregator::singleton()->notifyQueueNonEmpty( $this->wiki, $type );
366 }
367 }
368
369 $wgMemc->merge( $key, function ( $cache, $key, $lastRuns ) use ( $tasksRun ) {
370 if ( is_array( $lastRuns ) ) {
371 foreach ( $tasksRun as $type => $tasks ) {
372 foreach ( $tasks as $task => $timestamp ) {
373 if ( !isset( $lastRuns[$type][$task] )
374 || $timestamp > $lastRuns[$type][$task]
375 ) {
376 $lastRuns[$type][$task] = $timestamp;
377 }
378 }
379 }
380 } else {
381 $lastRuns = $tasksRun;
382 }
383
384 return $lastRuns;
385 } );
386
387 return $count;
388 }
389
390 /**
391 * @param $name string
392 * @return mixed
393 */
394 private function getCachedConfigVar( $name ) {
395 global $wgConf, $wgMemc;
396
397 if ( $this->wiki === wfWikiID() ) {
398 return $GLOBALS[$name]; // common case
399 } else {
400 list( $db, $prefix ) = wfSplitWikiID( $this->wiki );
401 $key = wfForeignMemcKey( $db, $prefix, 'configvalue', $name );
402 $value = $wgMemc->get( $key ); // ('v' => ...) or false
403 if ( is_array( $value ) ) {
404 return $value['v'];
405 } else {
406 $value = $wgConf->getConfig( $this->wiki, $name );
407 $wgMemc->set( $key, array( 'v' => $value ), 86400 + mt_rand( 0, 86400 ) );
408
409 return $value;
410 }
411 }
412 }
413 }