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