Merge "Set initial language and variant user preferences to user's preferred variant...
[lhc/web/wiklou.git] / includes / job / JobQueue.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 * @defgroup JobQueue JobQueue
22 * @author Aaron Schulz
23 */
24
25 /**
26 * Class to handle enqueueing and running of background jobs
27 *
28 * @ingroup JobQueue
29 * @since 1.21
30 */
31 abstract class JobQueue {
32 protected $wiki; // string; wiki ID
33 protected $type; // string; job type
34 protected $order; // string; job priority for pop()
35 protected $claimTTL; // integer; seconds
36 protected $maxTries; // integer; maximum number of times to try a job
37
38 const QoS_Atomic = 1; // integer; "all-or-nothing" job insertions
39
40 /**
41 * @param $params array
42 */
43 protected function __construct( array $params ) {
44 $this->wiki = $params['wiki'];
45 $this->type = $params['type'];
46 $this->claimTTL = isset( $params['claimTTL'] ) ? $params['claimTTL'] : 0;
47 $this->maxTries = isset( $params['maxTries'] ) ? $params['maxTries'] : 3;
48 if ( isset( $params['order'] ) && $params['order'] !== 'any' ) {
49 $this->order = $params['order'];
50 } else {
51 $this->order = $this->optimalOrder();
52 }
53 if ( !in_array( $this->order, $this->supportedOrders() ) ) {
54 throw new MWException( __CLASS__ . " does not support '{$this->order}' order." );
55 }
56 }
57
58 /**
59 * Get a job queue object of the specified type.
60 * $params includes:
61 * - class : What job class to use (determines job type)
62 * - wiki : wiki ID of the wiki the jobs are for (defaults to current wiki)
63 * - type : The name of the job types this queue handles
64 * - order : Order that pop() selects jobs, one of "fifo", "timestamp" or "random".
65 * If "fifo" is used, the queue will effectively be FIFO. Note that
66 * job completion will not appear to be exactly FIFO if there are multiple
67 * job runners since jobs can take different times to finish once popped.
68 * If "timestamp" is used, the queue will at least be loosely ordered
69 * by timestamp, allowing for some jobs to be popped off out of order.
70 * If "random" is used, pop() will pick jobs in random order.
71 * Note that it may only be weakly random (e.g. a lottery of the oldest X).
72 * If "any" is choosen, the queue will use whatever order is the fastest.
73 * This might be useful for improving concurrency for job acquisition.
74 * - claimTTL : If supported, the queue will recycle jobs that have been popped
75 * but not acknowledged as completed after this many seconds. Recycling
76 * of jobs simple means re-inserting them into the queue. Jobs can be
77 * attempted up to three times before being discarded.
78 *
79 * Queue classes should throw an exception if they do not support the options given.
80 *
81 * @param $params array
82 * @return JobQueue
83 * @throws MWException
84 */
85 final public static function factory( array $params ) {
86 $class = $params['class'];
87 if ( !MWInit::classExists( $class ) ) {
88 throw new MWException( "Invalid job queue class '$class'." );
89 }
90 $obj = new $class( $params );
91 if ( !( $obj instanceof self ) ) {
92 throw new MWException( "Class '$class' is not a " . __CLASS__ . " class." );
93 }
94 return $obj;
95 }
96
97 /**
98 * @return string Wiki ID
99 */
100 final public function getWiki() {
101 return $this->wiki;
102 }
103
104 /**
105 * @return string Job type that this queue handles
106 */
107 final public function getType() {
108 return $this->type;
109 }
110
111 /**
112 * @return string One of (random, timestamp, fifo)
113 */
114 final public function getOrder() {
115 return $this->order;
116 }
117
118 /**
119 * @return Array Subset of (random, timestamp, fifo)
120 */
121 abstract protected function supportedOrders();
122
123 /**
124 * @return string One of (random, timestamp, fifo)
125 */
126 abstract protected function optimalOrder();
127
128 /**
129 * Quickly check if the queue is empty (has no available jobs).
130 * Queue classes should use caching if they are any slower without memcached.
131 *
132 * If caching is used, this might return false when there are actually no jobs.
133 * If pop() is called and returns false then it should correct the cache. Also,
134 * calling flushCaches() first prevents this. However, this affect is typically
135 * not distinguishable from the race condition between isEmpty() and pop().
136 *
137 * @return bool
138 * @throws MWException
139 */
140 final public function isEmpty() {
141 wfProfileIn( __METHOD__ );
142 $res = $this->doIsEmpty();
143 wfProfileOut( __METHOD__ );
144 return $res;
145 }
146
147 /**
148 * @see JobQueue::isEmpty()
149 * @return bool
150 */
151 abstract protected function doIsEmpty();
152
153 /**
154 * Get the number of available (unacquired) jobs in the queue.
155 * Queue classes should use caching if they are any slower without memcached.
156 *
157 * If caching is used, this number might be out of date for a minute.
158 *
159 * @return integer
160 * @throws MWException
161 */
162 final public function getSize() {
163 wfProfileIn( __METHOD__ );
164 $res = $this->doGetSize();
165 wfProfileOut( __METHOD__ );
166 return $res;
167 }
168
169 /**
170 * @see JobQueue::getSize()
171 * @return integer
172 */
173 abstract protected function doGetSize();
174
175 /**
176 * Get the number of acquired jobs (these are temporarily out of the queue).
177 * Queue classes should use caching if they are any slower without memcached.
178 *
179 * If caching is used, this number might be out of date for a minute.
180 *
181 * @return integer
182 * @throws MWException
183 */
184 final public function getAcquiredCount() {
185 wfProfileIn( __METHOD__ );
186 $res = $this->doGetAcquiredCount();
187 wfProfileOut( __METHOD__ );
188 return $res;
189 }
190
191 /**
192 * @see JobQueue::getAcquiredCount()
193 * @return integer
194 */
195 abstract protected function doGetAcquiredCount();
196
197 /**
198 * Push a single jobs into the queue.
199 * This does not require $wgJobClasses to be set for the given job type.
200 * Outside callers should use JobQueueGroup::push() instead of this function.
201 *
202 * @param $jobs Job|Array
203 * @param $flags integer Bitfield (supports JobQueue::QoS_Atomic)
204 * @return bool Returns false on failure
205 * @throws MWException
206 */
207 final public function push( $jobs, $flags = 0 ) {
208 return $this->batchPush( is_array( $jobs ) ? $jobs : array( $jobs ), $flags );
209 }
210
211 /**
212 * Push a batch of jobs into the queue.
213 * This does not require $wgJobClasses to be set for the given job type.
214 * Outside callers should use JobQueueGroup::push() instead of this function.
215 *
216 * @param array $jobs List of Jobs
217 * @param $flags integer Bitfield (supports JobQueue::QoS_Atomic)
218 * @return bool Returns false on failure
219 * @throws MWException
220 */
221 final public function batchPush( array $jobs, $flags = 0 ) {
222 if ( !count( $jobs ) ) {
223 return true; // nothing to do
224 }
225
226 foreach ( $jobs as $job ) {
227 if ( $job->getType() !== $this->type ) {
228 throw new MWException( "Got '{$job->getType()}' job; expected '{$this->type}'." );
229 }
230 }
231
232 wfProfileIn( __METHOD__ );
233 $ok = $this->doBatchPush( $jobs, $flags );
234 wfProfileOut( __METHOD__ );
235 return $ok;
236 }
237
238 /**
239 * @see JobQueue::batchPush()
240 * @return bool
241 */
242 abstract protected function doBatchPush( array $jobs, $flags );
243
244 /**
245 * Pop a job off of the queue.
246 * This requires $wgJobClasses to be set for the given job type.
247 * Outside callers should use JobQueueGroup::pop() instead of this function.
248 *
249 * @return Job|bool Returns false if there are no jobs
250 * @throws MWException
251 */
252 final public function pop() {
253 global $wgJobClasses;
254
255 if ( $this->wiki !== wfWikiID() ) {
256 throw new MWException( "Cannot pop '{$this->type}' job off foreign wiki queue." );
257 } elseif ( !isset( $wgJobClasses[$this->type] ) ) {
258 // Do not pop jobs if there is no class for the queue type
259 throw new MWException( "Unrecognized job type '{$this->type}'." );
260 }
261
262 wfProfileIn( __METHOD__ );
263 $job = $this->doPop();
264 wfProfileOut( __METHOD__ );
265 return $job;
266 }
267
268 /**
269 * @see JobQueue::pop()
270 * @return Job
271 */
272 abstract protected function doPop();
273
274 /**
275 * Acknowledge that a job was completed.
276 *
277 * This does nothing for certain queue classes or if "claimTTL" is not set.
278 * Outside callers should use JobQueueGroup::ack() instead of this function.
279 *
280 * @param $job Job
281 * @return bool
282 * @throws MWException
283 */
284 final public function ack( Job $job ) {
285 if ( $job->getType() !== $this->type ) {
286 throw new MWException( "Got '{$job->getType()}' job; expected '{$this->type}'." );
287 }
288 wfProfileIn( __METHOD__ );
289 $ok = $this->doAck( $job );
290 wfProfileOut( __METHOD__ );
291 return $ok;
292 }
293
294 /**
295 * @see JobQueue::ack()
296 * @return bool
297 */
298 abstract protected function doAck( Job $job );
299
300 /**
301 * Register the "root job" of a given job into the queue for de-duplication.
302 * This should only be called right *after* all the new jobs have been inserted.
303 * This is used to turn older, duplicate, job entries into no-ops. The root job
304 * information will remain in the registry until it simply falls out of cache.
305 *
306 * This requires that $job has two special fields in the "params" array:
307 * - rootJobSignature : hash (e.g. SHA1) that identifies the task
308 * - rootJobTimestamp : TS_MW timestamp of this instance of the task
309 *
310 * A "root job" is a conceptual job that consist of potentially many smaller jobs
311 * that are actually inserted into the queue. For example, "refreshLinks" jobs are
312 * spawned when a template is edited. One can think of the task as "update links
313 * of pages that use template X" and an instance of that task as a "root job".
314 * However, what actually goes into the queue are potentially many refreshLinks2 jobs.
315 * Since these jobs include things like page ID ranges and DB master positions, and morph
316 * into smaller refreshLinks2 jobs recursively, simple duplicate detection (like job_sha1)
317 * for individual jobs being identical is not useful.
318 *
319 * In the case of "refreshLinks", if these jobs are still in the queue when the template
320 * is edited again, we want all of these old refreshLinks jobs for that template to become
321 * no-ops. This can greatly reduce server load, since refreshLinks jobs involves parsing.
322 * Essentially, the new batch of jobs belong to a new "root job" and the older ones to a
323 * previous "root job" for the same task of "update links of pages that use template X".
324 *
325 * This does nothing for certain queue classes.
326 *
327 * @param $job Job
328 * @return bool
329 * @throws MWException
330 */
331 final public function deduplicateRootJob( Job $job ) {
332 if ( $job->getType() !== $this->type ) {
333 throw new MWException( "Got '{$job->getType()}' job; expected '{$this->type}'." );
334 }
335 wfProfileIn( __METHOD__ );
336 $ok = $this->doDeduplicateRootJob( $job );
337 wfProfileOut( __METHOD__ );
338 return $ok;
339 }
340
341 /**
342 * @see JobQueue::deduplicateRootJob()
343 * @param $job Job
344 * @return bool
345 */
346 protected function doDeduplicateRootJob( Job $job ) {
347 return true;
348 }
349
350 /**
351 * Wait for any slaves or backup servers to catch up.
352 *
353 * This does nothing for certain queue classes.
354 *
355 * @return void
356 * @throws MWException
357 */
358 final public function waitForBackups() {
359 wfProfileIn( __METHOD__ );
360 $this->doWaitForBackups();
361 wfProfileOut( __METHOD__ );
362 }
363
364 /**
365 * @see JobQueue::waitForBackups()
366 * @return void
367 */
368 protected function doWaitForBackups() {}
369
370 /**
371 * Return a map of task names to task definition maps.
372 * A "task" is a fast periodic queue maintenance action.
373 * Mutually exclusive tasks must implement their own locking in the callback.
374 *
375 * Each task value is an associative array with:
376 * - name : the name of the task
377 * - callback : a PHP callable that performs the task
378 * - period : the period in seconds corresponding to the task frequency
379 *
380 * @return Array
381 */
382 final public function getPeriodicTasks() {
383 $tasks = $this->doGetPeriodicTasks();
384 foreach ( $tasks as $name => &$def ) {
385 $def['name'] = $name;
386 }
387 return $tasks;
388 }
389
390 /**
391 * @see JobQueue::getPeriodicTasks()
392 * @return Array
393 */
394 protected function doGetPeriodicTasks() {
395 return array();
396 }
397
398 /**
399 * Clear any process and persistent caches
400 *
401 * @return void
402 */
403 final public function flushCaches() {
404 wfProfileIn( __METHOD__ );
405 $this->doFlushCaches();
406 wfProfileOut( __METHOD__ );
407 }
408
409 /**
410 * @see JobQueue::flushCaches()
411 * @return void
412 */
413 protected function doFlushCaches() {}
414
415 /**
416 * Get an iterator to traverse over all of the jobs in this queue.
417 * This does not include jobs that are current acquired. In general,
418 * this should only be called on a queue that is no longer being popped.
419 *
420 * @return Iterator|Traversable|Array
421 * @throws MWException
422 */
423 abstract public function getAllQueuedJobs();
424
425 /**
426 * Namespace the queue with a key to isolate it for testing
427 *
428 * @param $key string
429 * @return void
430 * @throws MWException
431 */
432 public function setTestingPrefix( $key ) {
433 throw new MWException( "Queue namespacing not supported for this queue type." );
434 }
435 }