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