[JobQueue] Made supportedOrders() protected.
[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 * @return bool
133 * @throws MWException
134 */
135 final public function isEmpty() {
136 wfProfileIn( __METHOD__ );
137 $res = $this->doIsEmpty();
138 wfProfileOut( __METHOD__ );
139 return $res;
140 }
141
142 /**
143 * @see JobQueue::isEmpty()
144 * @return bool
145 */
146 abstract protected function doIsEmpty();
147
148 /**
149 * Get the number of available jobs in the queue.
150 * Queue classes should use caching if they are any slower without memcached.
151 *
152 * @return integer
153 * @throws MWException
154 */
155 final public function getSize() {
156 wfProfileIn( __METHOD__ );
157 $res = $this->doGetSize();
158 wfProfileOut( __METHOD__ );
159 return $res;
160 }
161
162 /**
163 * @see JobQueue::getSize()
164 * @return integer
165 */
166 abstract protected function doGetSize();
167
168 /**
169 * Get the number of acquired jobs (these are temporarily out of the queue).
170 * Queue classes should use caching if they are any slower without memcached.
171 *
172 * @return integer
173 * @throws MWException
174 */
175 final public function getAcquiredCount() {
176 wfProfileIn( __METHOD__ );
177 $res = $this->doGetAcquiredCount();
178 wfProfileOut( __METHOD__ );
179 return $res;
180 }
181
182 /**
183 * @see JobQueue::getAcquiredCount()
184 * @return integer
185 */
186 abstract protected function doGetAcquiredCount();
187
188 /**
189 * Push a single jobs into the queue.
190 * This does not require $wgJobClasses to be set for the given job type.
191 * Outside callers should use JobQueueGroup::push() instead of this function.
192 *
193 * @param $jobs Job|Array
194 * @param $flags integer Bitfield (supports JobQueue::QoS_Atomic)
195 * @return bool Returns false on failure
196 * @throws MWException
197 */
198 final public function push( $jobs, $flags = 0 ) {
199 return $this->batchPush( is_array( $jobs ) ? $jobs : array( $jobs ), $flags );
200 }
201
202 /**
203 * Push a batch of jobs into the queue.
204 * This does not require $wgJobClasses to be set for the given job type.
205 * Outside callers should use JobQueueGroup::push() instead of this function.
206 *
207 * @param $jobs array List of Jobs
208 * @param $flags integer Bitfield (supports JobQueue::QoS_Atomic)
209 * @return bool Returns false on failure
210 * @throws MWException
211 */
212 final public function batchPush( array $jobs, $flags = 0 ) {
213 if ( !count( $jobs ) ) {
214 return true; // nothing to do
215 }
216 foreach ( $jobs as $job ) {
217 if ( $job->getType() !== $this->type ) {
218 throw new MWException( "Got '{$job->getType()}' job; expected '{$this->type}'." );
219 }
220 }
221
222 wfProfileIn( __METHOD__ );
223 $ok = $this->doBatchPush( $jobs, $flags );
224 wfProfileOut( __METHOD__ );
225 return $ok;
226 }
227
228 /**
229 * @see JobQueue::batchPush()
230 * @return bool
231 */
232 abstract protected function doBatchPush( array $jobs, $flags );
233
234 /**
235 * Pop a job off of the queue.
236 * This requires $wgJobClasses to be set for the given job type.
237 * Outside callers should use JobQueueGroup::pop() instead of this function.
238 *
239 * @return Job|bool Returns false if there are no jobs
240 * @throws MWException
241 */
242 final public function pop() {
243 global $wgJobClasses;
244
245 if ( $this->wiki !== wfWikiID() ) {
246 throw new MWException( "Cannot pop '{$this->type}' job off foreign wiki queue." );
247 } elseif ( !isset( $wgJobClasses[$this->type] ) ) {
248 // Do not pop jobs if there is no class for the queue type
249 throw new MWException( "Unrecognized job type '{$this->type}'." );
250 }
251
252 wfProfileIn( __METHOD__ );
253 $job = $this->doPop();
254 wfProfileOut( __METHOD__ );
255 return $job;
256 }
257
258 /**
259 * @see JobQueue::pop()
260 * @return Job
261 */
262 abstract protected function doPop();
263
264 /**
265 * Acknowledge that a job was completed.
266 *
267 * This does nothing for certain queue classes or if "claimTTL" is not set.
268 * Outside callers should use JobQueueGroup::ack() instead of this function.
269 *
270 * @param $job Job
271 * @return bool
272 * @throws MWException
273 */
274 final public function ack( Job $job ) {
275 if ( $job->getType() !== $this->type ) {
276 throw new MWException( "Got '{$job->getType()}' job; expected '{$this->type}'." );
277 }
278 wfProfileIn( __METHOD__ );
279 $ok = $this->doAck( $job );
280 wfProfileOut( __METHOD__ );
281 return $ok;
282 }
283
284 /**
285 * @see JobQueue::ack()
286 * @return bool
287 */
288 abstract protected function doAck( Job $job );
289
290 /**
291 * Register the "root job" of a given job into the queue for de-duplication.
292 * This should only be called right *after* all the new jobs have been inserted.
293 * This is used to turn older, duplicate, job entries into no-ops. The root job
294 * information will remain in the registry until it simply falls out of cache.
295 *
296 * This requires that $job has two special fields in the "params" array:
297 * - rootJobSignature : hash (e.g. SHA1) that identifies the task
298 * - rootJobTimestamp : TS_MW timestamp of this instance of the task
299 *
300 * A "root job" is a conceptual job that consist of potentially many smaller jobs
301 * that are actually inserted into the queue. For example, "refreshLinks" jobs are
302 * spawned when a template is edited. One can think of the task as "update links
303 * of pages that use template X" and an instance of that task as a "root job".
304 * However, what actually goes into the queue are potentially many refreshLinks2 jobs.
305 * Since these jobs include things like page ID ranges and DB master positions, and morph
306 * into smaller refreshLinks2 jobs recursively, simple duplicate detection (like job_sha1)
307 * for individual jobs being identical is not useful.
308 *
309 * In the case of "refreshLinks", if these jobs are still in the queue when the template
310 * is edited again, we want all of these old refreshLinks jobs for that template to become
311 * no-ops. This can greatly reduce server load, since refreshLinks jobs involves parsing.
312 * Essentially, the new batch of jobs belong to a new "root job" and the older ones to a
313 * previous "root job" for the same task of "update links of pages that use template X".
314 *
315 * This does nothing for certain queue classes.
316 *
317 * @param $job Job
318 * @return bool
319 * @throws MWException
320 */
321 final public function deduplicateRootJob( Job $job ) {
322 if ( $job->getType() !== $this->type ) {
323 throw new MWException( "Got '{$job->getType()}' job; expected '{$this->type}'." );
324 }
325 wfProfileIn( __METHOD__ );
326 $ok = $this->doDeduplicateRootJob( $job );
327 wfProfileOut( __METHOD__ );
328 return $ok;
329 }
330
331 /**
332 * @see JobQueue::deduplicateRootJob()
333 * @param $job Job
334 * @return bool
335 */
336 protected function doDeduplicateRootJob( Job $job ) {
337 return true;
338 }
339
340 /**
341 * Wait for any slaves or backup servers to catch up.
342 *
343 * This does nothing for certain queue classes.
344 *
345 * @return void
346 * @throws MWException
347 */
348 final public function waitForBackups() {
349 wfProfileIn( __METHOD__ );
350 $this->doWaitForBackups();
351 wfProfileOut( __METHOD__ );
352 }
353
354 /**
355 * @see JobQueue::waitForBackups()
356 * @return void
357 */
358 protected function doWaitForBackups() {}
359
360 /**
361 * Return a map of task names to task definition maps.
362 * A "task" is a fast periodic queue maintenance action.
363 * Mutually exclusive tasks must implement their own locking in the callback.
364 *
365 * Each task value is an associative array with:
366 * - name : the name of the task
367 * - callback : a PHP callable that performs the task
368 * - period : the period in seconds corresponding to the task frequency
369 *
370 * @return Array
371 */
372 final public function getPeriodicTasks() {
373 $tasks = $this->doGetPeriodicTasks();
374 foreach ( $tasks as $name => &$def ) {
375 $def['name'] = $name;
376 }
377 return $tasks;
378 }
379
380 /**
381 * @see JobQueue::getPeriodicTasks()
382 * @return Array
383 */
384 protected function doGetPeriodicTasks() {
385 return array();
386 }
387
388 /**
389 * Clear any process and persistent caches
390 *
391 * @return void
392 */
393 final public function flushCaches() {
394 wfProfileIn( __METHOD__ );
395 $this->doFlushCaches();
396 wfProfileOut( __METHOD__ );
397 }
398
399 /**
400 * @see JobQueue::flushCaches()
401 * @return void
402 */
403 protected function doFlushCaches() {}
404
405 /**
406 * Get an iterator to traverse over all of the jobs in this queue.
407 * This does not include jobs that are current acquired. In general,
408 * this should only be called on a queue that is no longer being popped.
409 *
410 * @return Iterator|Traversable|Array
411 * @throws MWException
412 */
413 abstract public function getAllQueuedJobs();
414
415 /**
416 * Namespace the queue with a key to isolate it for testing
417 *
418 * @param $key string
419 * @return void
420 * @throws MWException
421 */
422 public function setTestingPrefix( $key ) {
423 throw new MWException( "Queue namespacing not supported for this queue type." );
424 }
425 }