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