Merge "Apply IP blocks to X-Forwarded-For header"
[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 const TYPE_DEFAULT = 1; // integer; jobs popped by default
40 const TYPE_ANY = 2; // integer; any job
41
42 const USE_CACHE = 1; // integer; use process or persistent cache
43 const USE_PRIORITY = 2; // integer; respect deprioritization
44
45 const PROC_CACHE_TTL = 15; // integer; seconds
46
47 const CACHE_VERSION = 1; // integer; cache version
48
49 /**
50 * @param string $wiki Wiki ID
51 */
52 protected function __construct( $wiki ) {
53 $this->wiki = $wiki;
54 $this->cache = new ProcessCacheLRU( 10 );
55 }
56
57 /**
58 * @param string $wiki Wiki ID
59 * @return JobQueueGroup
60 */
61 public static function singleton( $wiki = false ) {
62 $wiki = ( $wiki === false ) ? wfWikiID() : $wiki;
63 if ( !isset( self::$instances[$wiki] ) ) {
64 self::$instances[$wiki] = new self( $wiki );
65 }
66 return self::$instances[$wiki];
67 }
68
69 /**
70 * Destroy the singleton instances
71 *
72 * @return void
73 */
74 public static function destroySingletons() {
75 self::$instances = array();
76 }
77
78 /**
79 * Get the job queue object for a given queue type
80 *
81 * @param $type string
82 * @return JobQueue
83 */
84 public function get( $type ) {
85 global $wgJobTypeConf;
86
87 $conf = array( 'wiki' => $this->wiki, 'type' => $type );
88 if ( isset( $wgJobTypeConf[$type] ) ) {
89 $conf = $conf + $wgJobTypeConf[$type];
90 } else {
91 $conf = $conf + $wgJobTypeConf['default'];
92 }
93
94 return JobQueue::factory( $conf );
95 }
96
97 /**
98 * Insert jobs into the respective queues of with the belong.
99 *
100 * This inserts the jobs into the queue specified by $wgJobTypeConf
101 * and updates the aggregate job queue information cache as needed.
102 *
103 * @param $jobs Job|array A single Job or a list of Jobs
104 * @throws MWException
105 * @return bool
106 */
107 public function push( $jobs ) {
108 $jobs = is_array( $jobs ) ? $jobs : array( $jobs );
109
110 $jobsByType = array(); // (job type => list of jobs)
111 foreach ( $jobs as $job ) {
112 if ( $job instanceof Job ) {
113 $jobsByType[$job->getType()][] = $job;
114 } else {
115 throw new MWException( "Attempted to push a non-Job object into a queue." );
116 }
117 }
118
119 $ok = true;
120 foreach ( $jobsByType as $type => $jobs ) {
121 if ( $this->get( $type )->push( $jobs ) ) {
122 JobQueueAggregator::singleton()->notifyQueueNonEmpty( $this->wiki, $type );
123 } else {
124 $ok = false;
125 }
126 }
127
128 if ( $this->cache->has( 'queues-ready', 'list' ) ) {
129 $list = $this->cache->get( 'queues-ready', 'list' );
130 if ( count( array_diff( array_keys( $jobsByType ), $list ) ) ) {
131 $this->cache->clear( 'queues-ready' );
132 }
133 }
134
135 return $ok;
136 }
137
138 /**
139 * Pop a job off one of the job queues
140 *
141 * This pops a job off a queue as specified by $wgJobTypeConf and
142 * updates the aggregate job queue information cache as needed.
143 *
144 * @param $qtype integer|string JobQueueGroup::TYPE_DEFAULT or type string
145 * @param $flags integer Bitfield of JobQueueGroup::USE_* constants
146 * @return Job|bool Returns false on failure
147 */
148 public function pop( $qtype = self::TYPE_DEFAULT, $flags = 0 ) {
149 if ( is_string( $qtype ) ) { // specific job type
150 if ( ( $flags & self::USE_PRIORITY ) && $this->isQueueDeprioritized( $qtype ) ) {
151 return false; // back off
152 }
153 $job = $this->get( $qtype )->pop();
154 if ( !$job ) {
155 JobQueueAggregator::singleton()->notifyQueueEmpty( $this->wiki, $qtype );
156 }
157 return $job;
158 } else { // any job in the "default" jobs types
159 if ( $flags & self::USE_CACHE ) {
160 if ( !$this->cache->has( 'queues-ready', 'list', self::PROC_CACHE_TTL ) ) {
161 $this->cache->set( 'queues-ready', 'list', $this->getQueuesWithJobs() );
162 }
163 $types = $this->cache->get( 'queues-ready', 'list' );
164 } else {
165 $types = $this->getQueuesWithJobs();
166 }
167
168 if ( $qtype == self::TYPE_DEFAULT ) {
169 $types = array_intersect( $types, $this->getDefaultQueueTypes() );
170 }
171 shuffle( $types ); // avoid starvation
172
173 foreach ( $types as $type ) { // for each queue...
174 if ( ( $flags & self::USE_PRIORITY ) && $this->isQueueDeprioritized( $type ) ) {
175 continue; // back off
176 }
177 $job = $this->get( $type )->pop();
178 if ( $job ) { // found
179 return $job;
180 } else { // not found
181 JobQueueAggregator::singleton()->notifyQueueEmpty( $this->wiki, $type );
182 $this->cache->clear( 'queues-ready' );
183 }
184 }
185
186 return false; // no jobs found
187 }
188 }
189
190 /**
191 * Acknowledge that a job was completed
192 *
193 * @param $job Job
194 * @return bool
195 */
196 public function ack( Job $job ) {
197 return $this->get( $job->getType() )->ack( $job );
198 }
199
200 /**
201 * Register the "root job" of a given job into the queue for de-duplication.
202 * This should only be called right *after* all the new jobs have been inserted.
203 *
204 * @param $job Job
205 * @return bool
206 */
207 public function deduplicateRootJob( Job $job ) {
208 return $this->get( $job->getType() )->deduplicateRootJob( $job );
209 }
210
211 /**
212 * Wait for any slaves or backup queue servers to catch up.
213 *
214 * This does nothing for certain queue classes.
215 *
216 * @return void
217 * @throws MWException
218 */
219 public function waitForBackups() {
220 global $wgJobTypeConf;
221
222 wfProfileIn( __METHOD__ );
223 // Try to avoid doing this more than once per queue storage medium
224 foreach ( $wgJobTypeConf as $type => $conf ) {
225 $this->get( $type )->waitForBackups();
226 }
227 wfProfileOut( __METHOD__ );
228 }
229
230 /**
231 * Get the list of queue types
232 *
233 * @return array List of strings
234 */
235 public function getQueueTypes() {
236 return array_keys( $this->getCachedConfigVar( 'wgJobClasses' ) );
237 }
238
239 /**
240 * Get the list of default queue types
241 *
242 * @return array List of strings
243 */
244 public function getDefaultQueueTypes() {
245 global $wgJobTypesExcludedFromDefaultQueue;
246
247 return array_diff( $this->getQueueTypes(), $wgJobTypesExcludedFromDefaultQueue );
248 }
249
250 /**
251 * Get the list of job types that have non-empty queues
252 *
253 * @return Array List of job types that have non-empty queues
254 */
255 public function getQueuesWithJobs() {
256 $types = array();
257 foreach ( $this->getQueueTypes() as $type ) {
258 if ( !$this->get( $type )->isEmpty() ) {
259 $types[] = $type;
260 }
261 }
262 return $types;
263 }
264
265 /**
266 * Check if jobs should not be popped of a queue right now.
267 * This is only used for performance, such as to avoid spamming
268 * the queue with many sub-jobs before they actually get run.
269 *
270 * @param $type string
271 * @return bool
272 */
273 public function isQueueDeprioritized( $type ) {
274 if ( $this->cache->has( 'isDeprioritized', $type, 5 ) ) {
275 return $this->cache->get( 'isDeprioritized', $type );
276 }
277 if ( $type === 'refreshLinks2' ) {
278 // Don't keep converting refreshLinks2 => refreshLinks jobs if the
279 // later jobs have not been done yet. This helps throttle queue spam.
280 $deprioritized = !$this->get( 'refreshLinks' )->isEmpty();
281 $this->cache->set( 'isDeprioritized', $type, $deprioritized );
282 return $deprioritized;
283 }
284 return false;
285 }
286
287 /**
288 * Execute any due periodic queue maintenance tasks for all queues.
289 *
290 * A task is "due" if the time ellapsed since the last run is greater than
291 * the defined run period. Concurrent calls to this function will cause tasks
292 * to be attempted twice, so they may need their own methods of mutual exclusion.
293 *
294 * @return integer Number of tasks run
295 */
296 public function executeReadyPeriodicTasks() {
297 global $wgMemc;
298
299 list( $db, $prefix ) = wfSplitWikiID( $this->wiki );
300 $key = wfForeignMemcKey( $db, $prefix, 'jobqueuegroup', 'taskruns', 'v1' );
301 $lastRuns = $wgMemc->get( $key ); // (queue => task => UNIX timestamp)
302
303 $count = 0;
304 $tasksRun = array(); // (queue => task => UNIX timestamp)
305 foreach ( $this->getQueueTypes() as $type ) {
306 $queue = $this->get( $type );
307 foreach ( $queue->getPeriodicTasks() as $task => $definition ) {
308 if ( $definition['period'] <= 0 ) {
309 continue; // disabled
310 } elseif ( !isset( $lastRuns[$type][$task] )
311 || $lastRuns[$type][$task] < ( time() - $definition['period'] ) )
312 {
313 if ( call_user_func( $definition['callback'] ) !== null ) {
314 $tasksRun[$type][$task] = time();
315 ++$count;
316 }
317 }
318 }
319 }
320
321 $wgMemc->merge( $key, function( $cache, $key, $lastRuns ) use ( $tasksRun ) {
322 if ( is_array( $lastRuns ) ) {
323 foreach ( $tasksRun as $type => $tasks ) {
324 foreach ( $tasks as $task => $timestamp ) {
325 if ( !isset( $lastRuns[$type][$task] )
326 || $timestamp > $lastRuns[$type][$task] )
327 {
328 $lastRuns[$type][$task] = $timestamp;
329 }
330 }
331 }
332 } else {
333 $lastRuns = $tasksRun;
334 }
335 return $lastRuns;
336 } );
337
338 return $count;
339 }
340
341 /**
342 * @param $name string
343 * @return mixed
344 */
345 private function getCachedConfigVar( $name ) {
346 global $wgConf, $wgMemc;
347
348 if ( $this->wiki === wfWikiID() ) {
349 return $GLOBALS[$name]; // common case
350 } else {
351 list( $db, $prefix ) = wfSplitWikiID( $this->wiki );
352 $key = wfForeignMemcKey( $db, $prefix, 'configvalue', $name );
353 $value = $wgMemc->get( $key ); // ('v' => ...) or false
354 if ( is_array( $value ) ) {
355 return $value['v'];
356 } else {
357 $value = $wgConf->getConfig( $this->wiki, $name );
358 $wgMemc->set( $key, array( 'v' => $value ), 86400 + mt_rand( 0, 86400 ) );
359 return $value;
360 }
361 }
362 }
363 }