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