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