Merge "Set visibility on class properties in LocalFile.php"
[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 /** @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 wfProfileIn( __METHOD__ );
191 $res = $this->doIsEmpty();
192 wfProfileOut( __METHOD__ );
193
194 return $res;
195 }
196
197 /**
198 * @see JobQueue::isEmpty()
199 * @return bool
200 */
201 abstract protected function doIsEmpty();
202
203 /**
204 * Get the number of available (unacquired, non-delayed) jobs in the queue.
205 * Queue classes should use caching if they are any slower without memcached.
206 *
207 * If caching is used, this number might be out of date for a minute.
208 *
209 * @return int
210 * @throws JobQueueError
211 */
212 final public function getSize() {
213 wfProfileIn( __METHOD__ );
214 $res = $this->doGetSize();
215 wfProfileOut( __METHOD__ );
216
217 return $res;
218 }
219
220 /**
221 * @see JobQueue::getSize()
222 * @return int
223 */
224 abstract protected function doGetSize();
225
226 /**
227 * Get the number of acquired jobs (these are temporarily out of the queue).
228 * Queue classes should use caching if they are any slower without memcached.
229 *
230 * If caching is used, this number might be out of date for a minute.
231 *
232 * @return int
233 * @throws JobQueueError
234 */
235 final public function getAcquiredCount() {
236 wfProfileIn( __METHOD__ );
237 $res = $this->doGetAcquiredCount();
238 wfProfileOut( __METHOD__ );
239
240 return $res;
241 }
242
243 /**
244 * @see JobQueue::getAcquiredCount()
245 * @return int
246 */
247 abstract protected function doGetAcquiredCount();
248
249 /**
250 * Get the number of delayed jobs (these are temporarily out of the queue).
251 * Queue classes should use caching if they are any slower without memcached.
252 *
253 * If caching is used, this number might be out of date for a minute.
254 *
255 * @return int
256 * @throws JobQueueError
257 * @since 1.22
258 */
259 final public function getDelayedCount() {
260 wfProfileIn( __METHOD__ );
261 $res = $this->doGetDelayedCount();
262 wfProfileOut( __METHOD__ );
263
264 return $res;
265 }
266
267 /**
268 * @see JobQueue::getDelayedCount()
269 * @return int
270 */
271 protected function doGetDelayedCount() {
272 return 0; // not implemented
273 }
274
275 /**
276 * Get the number of acquired jobs that can no longer be attempted.
277 * Queue classes should use caching if they are any slower without memcached.
278 *
279 * If caching is used, this number might be out of date for a minute.
280 *
281 * @return int
282 * @throws JobQueueError
283 */
284 final public function getAbandonedCount() {
285 wfProfileIn( __METHOD__ );
286 $res = $this->doGetAbandonedCount();
287 wfProfileOut( __METHOD__ );
288
289 return $res;
290 }
291
292 /**
293 * @see JobQueue::getAbandonedCount()
294 * @return int
295 */
296 protected function doGetAbandonedCount() {
297 return 0; // not implemented
298 }
299
300 /**
301 * Push a single jobs into the queue.
302 * This does not require $wgJobClasses to be set for the given job type.
303 * Outside callers should use JobQueueGroup::push() instead of this function.
304 *
305 * @param Job|array $jobs A single job or an array of Jobs
306 * @param int $flags Bitfield (supports JobQueue::QOS_ATOMIC)
307 * @return bool Returns false on failure
308 * @throws JobQueueError
309 */
310 final public function push( $jobs, $flags = 0 ) {
311 return $this->batchPush( is_array( $jobs ) ? $jobs : array( $jobs ), $flags );
312 }
313
314 /**
315 * Push a batch of jobs into the queue.
316 * This does not require $wgJobClasses to be set for the given job type.
317 * Outside callers should use JobQueueGroup::push() instead of this function.
318 *
319 * @param array $jobs List of Jobs
320 * @param int $flags Bitfield (supports JobQueue::QOS_ATOMIC)
321 * @throws MWException
322 * @return bool Returns false on failure
323 */
324 final public function batchPush( array $jobs, $flags = 0 ) {
325 if ( !count( $jobs ) ) {
326 return true; // nothing to do
327 }
328
329 foreach ( $jobs as $job ) {
330 if ( $job->getType() !== $this->type ) {
331 throw new MWException(
332 "Got '{$job->getType()}' job; expected a '{$this->type}' job." );
333 } elseif ( $job->getReleaseTimestamp() && !$this->checkDelay ) {
334 throw new MWException(
335 "Got delayed '{$job->getType()}' job; delays are not supported." );
336 }
337 }
338
339 wfProfileIn( __METHOD__ );
340 $ok = $this->doBatchPush( $jobs, $flags );
341 wfProfileOut( __METHOD__ );
342
343 return $ok;
344 }
345
346 /**
347 * @see JobQueue::batchPush()
348 * @param array $jobs
349 * @param $flags
350 * @return bool
351 */
352 abstract protected function doBatchPush( array $jobs, $flags );
353
354 /**
355 * Pop a job off of the queue.
356 * This requires $wgJobClasses to be set for the given job type.
357 * Outside callers should use JobQueueGroup::pop() instead of this function.
358 *
359 * @throws MWException
360 * @return Job|bool Returns false if there are no jobs
361 */
362 final public function pop() {
363 global $wgJobClasses;
364
365 if ( $this->wiki !== wfWikiID() ) {
366 throw new MWException( "Cannot pop '{$this->type}' job off foreign wiki queue." );
367 } elseif ( !isset( $wgJobClasses[$this->type] ) ) {
368 // Do not pop jobs if there is no class for the queue type
369 throw new MWException( "Unrecognized job type '{$this->type}'." );
370 }
371
372 wfProfileIn( __METHOD__ );
373 $job = $this->doPop();
374 wfProfileOut( __METHOD__ );
375
376 // Flag this job as an old duplicate based on its "root" job...
377 try {
378 if ( $job && $this->isRootJobOldDuplicate( $job ) ) {
379 JobQueue::incrStats( 'job-pop-duplicate', $this->type );
380 $job = DuplicateJob::newFromJob( $job ); // convert to a no-op
381 }
382 } catch ( MWException $e ) {
383 // don't lose jobs over this
384 }
385
386 return $job;
387 }
388
389 /**
390 * @see JobQueue::pop()
391 * @return Job
392 */
393 abstract protected function doPop();
394
395 /**
396 * Acknowledge that a job was completed.
397 *
398 * This does nothing for certain queue classes or if "claimTTL" is not set.
399 * Outside callers should use JobQueueGroup::ack() instead of this function.
400 *
401 * @param Job $job
402 * @throws MWException
403 * @return bool
404 */
405 final public function ack( Job $job ) {
406 if ( $job->getType() !== $this->type ) {
407 throw new MWException( "Got '{$job->getType()}' job; expected '{$this->type}'." );
408 }
409 wfProfileIn( __METHOD__ );
410 $ok = $this->doAck( $job );
411 wfProfileOut( __METHOD__ );
412
413 return $ok;
414 }
415
416 /**
417 * @see JobQueue::ack()
418 * @param Job $job
419 * @return bool
420 */
421 abstract protected function doAck( Job $job );
422
423 /**
424 * Register the "root job" of a given job into the queue for de-duplication.
425 * This should only be called right *after* all the new jobs have been inserted.
426 * This is used to turn older, duplicate, job entries into no-ops. The root job
427 * information will remain in the registry until it simply falls out of cache.
428 *
429 * This requires that $job has two special fields in the "params" array:
430 * - rootJobSignature : hash (e.g. SHA1) that identifies the task
431 * - rootJobTimestamp : TS_MW timestamp of this instance of the task
432 *
433 * A "root job" is a conceptual job that consist of potentially many smaller jobs
434 * that are actually inserted into the queue. For example, "refreshLinks" jobs are
435 * spawned when a template is edited. One can think of the task as "update links
436 * of pages that use template X" and an instance of that task as a "root job".
437 * However, what actually goes into the queue are potentially many refreshLinks2 jobs.
438 * Since these jobs include things like page ID ranges and DB master positions, and morph
439 * into smaller refreshLinks2 jobs recursively, simple duplicate detection (like job_sha1)
440 * for individual jobs being identical is not useful.
441 *
442 * In the case of "refreshLinks", if these jobs are still in the queue when the template
443 * is edited again, we want all of these old refreshLinks jobs for that template to become
444 * no-ops. This can greatly reduce server load, since refreshLinks jobs involves parsing.
445 * Essentially, the new batch of jobs belong to a new "root job" and the older ones to a
446 * previous "root job" for the same task of "update links of pages that use template X".
447 *
448 * This does nothing for certain queue classes.
449 *
450 * @param Job $job
451 * @throws MWException
452 * @return bool
453 */
454 final public function deduplicateRootJob( Job $job ) {
455 if ( $job->getType() !== $this->type ) {
456 throw new MWException( "Got '{$job->getType()}' job; expected '{$this->type}'." );
457 }
458 wfProfileIn( __METHOD__ );
459 $ok = $this->doDeduplicateRootJob( $job );
460 wfProfileOut( __METHOD__ );
461
462 return $ok;
463 }
464
465 /**
466 * @see JobQueue::deduplicateRootJob()
467 * @param Job $job
468 * @throws MWException
469 * @return bool
470 */
471 protected function doDeduplicateRootJob( Job $job ) {
472 if ( !$job->hasRootJobParams() ) {
473 throw new MWException( "Cannot register root job; missing parameters." );
474 }
475 $params = $job->getRootJobParams();
476
477 $key = $this->getRootJobCacheKey( $params['rootJobSignature'] );
478 // Callers should call batchInsert() and then this function so that if the insert
479 // fails, the de-duplication registration will be aborted. Since the insert is
480 // deferred till "transaction idle", do the same here, so that the ordering is
481 // maintained. Having only the de-duplication registration succeed would cause
482 // jobs to become no-ops without any actual jobs that made them redundant.
483 $timestamp = $this->dupCache->get( $key ); // current last timestamp of this job
484 if ( $timestamp && $timestamp >= $params['rootJobTimestamp'] ) {
485 return true; // a newer version of this root job was enqueued
486 }
487
488 // Update the timestamp of the last root job started at the location...
489 return $this->dupCache->set( $key, $params['rootJobTimestamp'], JobQueueDB::ROOTJOB_TTL );
490 }
491
492 /**
493 * Check if the "root" job of a given job has been superseded by a newer one
494 *
495 * @param Job $job
496 * @throws MWException
497 * @return bool
498 */
499 final protected function isRootJobOldDuplicate( Job $job ) {
500 if ( $job->getType() !== $this->type ) {
501 throw new MWException( "Got '{$job->getType()}' job; expected '{$this->type}'." );
502 }
503 wfProfileIn( __METHOD__ );
504 $isDuplicate = $this->doIsRootJobOldDuplicate( $job );
505 wfProfileOut( __METHOD__ );
506
507 return $isDuplicate;
508 }
509
510 /**
511 * @see JobQueue::isRootJobOldDuplicate()
512 * @param Job $job
513 * @return bool
514 */
515 protected function doIsRootJobOldDuplicate( Job $job ) {
516 if ( !$job->hasRootJobParams() ) {
517 return false; // job has no de-deplication info
518 }
519 $params = $job->getRootJobParams();
520
521 $key = $this->getRootJobCacheKey( $params['rootJobSignature'] );
522 // Get the last time this root job was enqueued
523 $timestamp = $this->dupCache->get( $key );
524
525 // Check if a new root job was started at the location after this one's...
526 return ( $timestamp && $timestamp > $params['rootJobTimestamp'] );
527 }
528
529 /**
530 * @param string $signature Hash identifier of the root job
531 * @return string
532 */
533 protected function getRootJobCacheKey( $signature ) {
534 list( $db, $prefix ) = wfSplitWikiID( $this->wiki );
535
536 return wfForeignMemcKey( $db, $prefix, 'jobqueue', $this->type, 'rootjob', $signature );
537 }
538
539 /**
540 * Deleted all unclaimed and delayed jobs from the queue
541 *
542 * @return bool Success
543 * @throws JobQueueError
544 * @since 1.22
545 */
546 final public function delete() {
547 wfProfileIn( __METHOD__ );
548 $res = $this->doDelete();
549 wfProfileOut( __METHOD__ );
550
551 return $res;
552 }
553
554 /**
555 * @see JobQueue::delete()
556 * @throws MWException
557 * @return bool Success
558 */
559 protected function doDelete() {
560 throw new MWException( "This method is not implemented." );
561 }
562
563 /**
564 * Wait for any slaves or backup servers to catch up.
565 *
566 * This does nothing for certain queue classes.
567 *
568 * @return void
569 * @throws JobQueueError
570 */
571 final public function waitForBackups() {
572 wfProfileIn( __METHOD__ );
573 $this->doWaitForBackups();
574 wfProfileOut( __METHOD__ );
575 }
576
577 /**
578 * @see JobQueue::waitForBackups()
579 * @return void
580 */
581 protected function doWaitForBackups() {
582 }
583
584 /**
585 * Return a map of task names to task definition maps.
586 * A "task" is a fast periodic queue maintenance action.
587 * Mutually exclusive tasks must implement their own locking in the callback.
588 *
589 * Each task value is an associative array with:
590 * - name : the name of the task
591 * - callback : a PHP callable that performs the task
592 * - period : the period in seconds corresponding to the task frequency
593 *
594 * @return array
595 */
596 final public function getPeriodicTasks() {
597 $tasks = $this->doGetPeriodicTasks();
598 foreach ( $tasks as $name => &$def ) {
599 $def['name'] = $name;
600 }
601
602 return $tasks;
603 }
604
605 /**
606 * @see JobQueue::getPeriodicTasks()
607 * @return array
608 */
609 protected function doGetPeriodicTasks() {
610 return array();
611 }
612
613 /**
614 * Clear any process and persistent caches
615 *
616 * @return void
617 */
618 final public function flushCaches() {
619 wfProfileIn( __METHOD__ );
620 $this->doFlushCaches();
621 wfProfileOut( __METHOD__ );
622 }
623
624 /**
625 * @see JobQueue::flushCaches()
626 * @return void
627 */
628 protected function doFlushCaches() {
629 }
630
631 /**
632 * Get an iterator to traverse over all available jobs in this queue.
633 * This does not include jobs that are currently acquired or delayed.
634 * Note: results may be stale if the queue is concurrently modified.
635 *
636 * @return Iterator
637 * @throws JobQueueError
638 */
639 abstract public function getAllQueuedJobs();
640
641 /**
642 * Get an iterator to traverse over all delayed jobs in this queue.
643 * Note: results may be stale if the queue is concurrently modified.
644 *
645 * @return Iterator
646 * @throws JobQueueError
647 * @since 1.22
648 */
649 public function getAllDelayedJobs() {
650 return new ArrayIterator( array() ); // not implemented
651 }
652
653 /**
654 * Do not use this function outside of JobQueue/JobQueueGroup
655 *
656 * @return string
657 * @since 1.22
658 */
659 public function getCoalesceLocationInternal() {
660 return null;
661 }
662
663 /**
664 * Check whether each of the given queues are empty.
665 * This is used for batching checks for queues stored at the same place.
666 *
667 * @param array $types List of queues types
668 * @return array|null (list of non-empty queue types) or null if unsupported
669 * @throws MWException
670 * @since 1.22
671 */
672 final public function getSiblingQueuesWithJobs( array $types ) {
673 $section = new ProfileSection( __METHOD__ );
674
675 return $this->doGetSiblingQueuesWithJobs( $types );
676 }
677
678 /**
679 * @see JobQueue::getSiblingQueuesWithJobs()
680 * @param array $types List of queues types
681 * @return array|null (list of queue types) or null if unsupported
682 */
683 protected function doGetSiblingQueuesWithJobs( array $types ) {
684 return null; // not supported
685 }
686
687 /**
688 * Check the size of each of the given queues.
689 * For queues not served by the same store as this one, 0 is returned.
690 * This is used for batching checks for queues stored at the same place.
691 *
692 * @param array $types List of queues types
693 * @return array|null (job type => whether queue is empty) or null if unsupported
694 * @throws MWException
695 * @since 1.22
696 */
697 final public function getSiblingQueueSizes( array $types ) {
698 $section = new ProfileSection( __METHOD__ );
699
700 return $this->doGetSiblingQueueSizes( $types );
701 }
702
703 /**
704 * @see JobQueue::getSiblingQueuesSize()
705 * @param array $types List of queues types
706 * @return array|null (list of queue types) or null if unsupported
707 */
708 protected function doGetSiblingQueueSizes( array $types ) {
709 return null; // not supported
710 }
711
712 /**
713 * Call wfIncrStats() for the queue overall and for the queue type
714 *
715 * @param string $key Event type
716 * @param string $type Job type
717 * @param int $delta
718 * @since 1.22
719 */
720 public static function incrStats( $key, $type, $delta = 1 ) {
721 wfIncrStats( $key, $delta );
722 wfIncrStats( "{$key}-{$type}", $delta );
723 }
724
725 /**
726 * Namespace the queue with a key to isolate it for testing
727 *
728 * @param string $key
729 * @return void
730 * @throws MWException
731 */
732 public function setTestingPrefix( $key ) {
733 throw new MWException( "Queue namespacing not supported for this queue type." );
734 }
735 }
736
737 /**
738 * @ingroup JobQueue
739 * @since 1.22
740 */
741 class JobQueueError extends MWException {
742 }
743
744 class JobQueueConnectionError extends JobQueueError {
745 }