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