Merge "Set visibility on class properties of OldLocalFile"
[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
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 $type string
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 $jobs Job|array 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
114 $jobsByType = array(); // (job type => list of jobs)
115 foreach ( $jobs as $job ) {
116 if ( $job instanceof Job ) {
117 $jobsByType[$job->getType()][] = $job;
118 } else {
119 throw new MWException( "Attempted to push a non-Job object into a queue." );
120 }
121 }
122
123 $ok = true;
124 foreach ( $jobsByType as $type => $jobs ) {
125 if ( $this->get( $type )->push( $jobs ) ) {
126 JobQueueAggregator::singleton()->notifyQueueNonEmpty( $this->wiki, $type );
127 } else {
128 $ok = false;
129 }
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 $ok;
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 $qtype integer|string JobQueueGroup::TYPE_DEFAULT or type string
149 * @param $flags integer Bitfield of JobQueueGroup::USE_* constants
150 * @return Job|bool Returns false on failure
151 */
152 public function pop( $qtype = self::TYPE_DEFAULT, $flags = 0 ) {
153 if ( is_string( $qtype ) ) { // specific job type
154 if ( ( $flags & self::USE_PRIORITY ) && $this->isQueueDeprioritized( $qtype ) ) {
155 return false; // back off
156 }
157 $job = $this->get( $qtype )->pop();
158 if ( !$job ) {
159 JobQueueAggregator::singleton()->notifyQueueEmpty( $this->wiki, $qtype );
160 }
161
162 return $job;
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 shuffle( $types ); // avoid starvation
177
178 foreach ( $types as $type ) { // for each queue...
179 if ( ( $flags & self::USE_PRIORITY ) && $this->isQueueDeprioritized( $type ) ) {
180 continue; // back off
181 }
182 $job = $this->get( $type )->pop();
183 if ( $job ) { // found
184 return $job;
185 } else { // not found
186 JobQueueAggregator::singleton()->notifyQueueEmpty( $this->wiki, $type );
187 $this->cache->clear( 'queues-ready' );
188 }
189 }
190
191 return false; // no jobs found
192 }
193 }
194
195 /**
196 * Acknowledge that a job was completed
197 *
198 * @param $job Job
199 * @return bool
200 */
201 public function ack( Job $job ) {
202 return $this->get( $job->getType() )->ack( $job );
203 }
204
205 /**
206 * Register the "root job" of a given job into the queue for de-duplication.
207 * This should only be called right *after* all the new jobs have been inserted.
208 *
209 * @param $job Job
210 * @return bool
211 */
212 public function deduplicateRootJob( Job $job ) {
213 return $this->get( $job->getType() )->deduplicateRootJob( $job );
214 }
215
216 /**
217 * Wait for any slaves or backup queue servers to catch up.
218 *
219 * This does nothing for certain queue classes.
220 *
221 * @return void
222 * @throws MWException
223 */
224 public function waitForBackups() {
225 global $wgJobTypeConf;
226
227 wfProfileIn( __METHOD__ );
228 // Try to avoid doing this more than once per queue storage medium
229 foreach ( $wgJobTypeConf as $type => $conf ) {
230 $this->get( $type )->waitForBackups();
231 }
232 wfProfileOut( __METHOD__ );
233 }
234
235 /**
236 * Get the list of queue types
237 *
238 * @return array List of strings
239 */
240 public function getQueueTypes() {
241 return array_keys( $this->getCachedConfigVar( 'wgJobClasses' ) );
242 }
243
244 /**
245 * Get the list of default queue types
246 *
247 * @return array List of strings
248 */
249 public function getDefaultQueueTypes() {
250 global $wgJobTypesExcludedFromDefaultQueue;
251
252 return array_diff( $this->getQueueTypes(), $wgJobTypesExcludedFromDefaultQueue );
253 }
254
255 /**
256 * Get the list of job types that have non-empty queues
257 *
258 * @return Array List of job types that have non-empty queues
259 */
260 public function getQueuesWithJobs() {
261 $types = array();
262 foreach ( $this->getCoalescedQueues() as $info ) {
263 $nonEmpty = $info['queue']->getSiblingQueuesWithJobs( $this->getQueueTypes() );
264 if ( is_array( $nonEmpty ) ) { // batching features supported
265 $types = array_merge( $types, $nonEmpty );
266 } else { // we have to go through the queues in the bucket one-by-one
267 foreach ( $info['types'] as $type ) {
268 if ( !$this->get( $type )->isEmpty() ) {
269 $types[] = $type;
270 }
271 }
272 }
273 }
274
275 return $types;
276 }
277
278 /**
279 * Get the size of the queus for a list of job types
280 *
281 * @return Array Map of (job type => size)
282 */
283 public function getQueueSizes() {
284 $sizeMap = array();
285 foreach ( $this->getCoalescedQueues() as $info ) {
286 $sizes = $info['queue']->getSiblingQueueSizes( $this->getQueueTypes() );
287 if ( is_array( $sizes ) ) { // batching features supported
288 $sizeMap = $sizeMap + $sizes;
289 } else { // we have to go through the queues in the bucket one-by-one
290 foreach ( $info['types'] as $type ) {
291 $sizeMap[$type] = $this->get( $type )->getSize();
292 }
293 }
294 }
295
296 return $sizeMap;
297 }
298
299 /**
300 * @return array
301 */
302 protected function getCoalescedQueues() {
303 global $wgJobTypeConf;
304
305 if ( $this->coalescedQueues === null ) {
306 $this->coalescedQueues = array();
307 foreach ( $wgJobTypeConf as $type => $conf ) {
308 $queue = JobQueue::factory(
309 array( 'wiki' => $this->wiki, 'type' => 'null' ) + $conf );
310 $loc = $queue->getCoalesceLocationInternal();
311 if ( !isset( $this->coalescedQueues[$loc] ) ) {
312 $this->coalescedQueues[$loc]['queue'] = $queue;
313 $this->coalescedQueues[$loc]['types'] = array();
314 }
315 if ( $type === 'default' ) {
316 $this->coalescedQueues[$loc]['types'] = array_merge(
317 $this->coalescedQueues[$loc]['types'],
318 array_diff( $this->getQueueTypes(), array_keys( $wgJobTypeConf ) )
319 );
320 } else {
321 $this->coalescedQueues[$loc]['types'][] = $type;
322 }
323 }
324 }
325
326 return $this->coalescedQueues;
327 }
328
329 /**
330 * Check if jobs should not be popped of a queue right now.
331 * This is only used for performance, such as to avoid spamming
332 * the queue with many sub-jobs before they actually get run.
333 *
334 * @param $type string
335 * @return bool
336 */
337 public function isQueueDeprioritized( $type ) {
338 if ( $this->cache->has( 'isDeprioritized', $type, 5 ) ) {
339 return $this->cache->get( 'isDeprioritized', $type );
340 }
341 if ( $type === 'refreshLinks2' ) {
342 // Don't keep converting refreshLinks2 => refreshLinks jobs if the
343 // later jobs have not been done yet. This helps throttle queue spam.
344 $deprioritized = !$this->get( 'refreshLinks' )->isEmpty();
345 $this->cache->set( 'isDeprioritized', $type, $deprioritized );
346
347 return $deprioritized;
348 }
349
350 return false;
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 integer 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 }
390
391 $wgMemc->merge( $key, function ( $cache, $key, $lastRuns ) use ( $tasksRun ) {
392 if ( is_array( $lastRuns ) ) {
393 foreach ( $tasksRun as $type => $tasks ) {
394 foreach ( $tasks as $task => $timestamp ) {
395 if ( !isset( $lastRuns[$type][$task] )
396 || $timestamp > $lastRuns[$type][$task]
397 ) {
398 $lastRuns[$type][$task] = $timestamp;
399 }
400 }
401 }
402 } else {
403 $lastRuns = $tasksRun;
404 }
405
406 return $lastRuns;
407 } );
408
409 return $count;
410 }
411
412 /**
413 * @param $name string
414 * @return mixed
415 */
416 private function getCachedConfigVar( $name ) {
417 global $wgConf, $wgMemc;
418
419 if ( $this->wiki === wfWikiID() ) {
420 return $GLOBALS[$name]; // common case
421 } else {
422 list( $db, $prefix ) = wfSplitWikiID( $this->wiki );
423 $key = wfForeignMemcKey( $db, $prefix, 'configvalue', $name );
424 $value = $wgMemc->get( $key ); // ('v' => ...) or false
425 if ( is_array( $value ) ) {
426 return $value['v'];
427 } else {
428 $value = $wgConf->getConfig( $this->wiki, $name );
429 $wgMemc->set( $key, array( 'v' => $value ), 86400 + mt_rand( 0, 86400 ) );
430
431 return $value;
432 }
433 }
434 }
435 }