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