Merge "Revert "Remove old remapping hacks from Database::indexName()""
[lhc/web/wiklou.git] / includes / jobqueue / JobQueue.php
1 <?php
2 /**
3 * Job queue base code.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @defgroup JobQueue JobQueue
22 * @author Aaron Schulz
23 */
24 use MediaWiki\MediaWikiServices;
25
26 /**
27 * Class to handle enqueueing and running of background jobs
28 *
29 * @ingroup JobQueue
30 * @since 1.21
31 */
32 abstract class JobQueue {
33 /** @var string Wiki ID */
34 protected $wiki;
35 /** @var string Job type */
36 protected $type;
37 /** @var string Job priority for pop() */
38 protected $order;
39 /** @var int Time to live in seconds */
40 protected $claimTTL;
41 /** @var int Maximum number of times to try a job */
42 protected $maxTries;
43 /** @var string|bool Read only rationale (or false if r/w) */
44 protected $readOnlyReason;
45
46 /** @var BagOStuff */
47 protected $dupCache;
48 /** @var JobQueueAggregator */
49 protected $aggr;
50
51 const QOS_ATOMIC = 1; // integer; "all-or-nothing" job insertions
52
53 const ROOTJOB_TTL = 2419200; // integer; seconds to remember root jobs (28 days)
54
55 /**
56 * @param array $params
57 * @throws MWException
58 */
59 protected function __construct( array $params ) {
60 $this->wiki = $params['wiki'];
61 $this->type = $params['type'];
62 $this->claimTTL = isset( $params['claimTTL'] ) ? $params['claimTTL'] : 0;
63 $this->maxTries = isset( $params['maxTries'] ) ? $params['maxTries'] : 3;
64 if ( isset( $params['order'] ) && $params['order'] !== 'any' ) {
65 $this->order = $params['order'];
66 } else {
67 $this->order = $this->optimalOrder();
68 }
69 if ( !in_array( $this->order, $this->supportedOrders() ) ) {
70 throw new MWException( __CLASS__ . " does not support '{$this->order}' order." );
71 }
72 $this->dupCache = wfGetCache( CACHE_ANYTHING );
73 $this->aggr = isset( $params['aggregator'] )
74 ? $params['aggregator']
75 : new JobQueueAggregatorNull( [] );
76 $this->readOnlyReason = isset( $params['readOnlyReason'] )
77 ? $params['readOnlyReason']
78 : false;
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 simply means re-inserting them into the queue. Jobs can be
100 * attempted up to three times before being discarded.
101 * - readOnlyReason : Set this to a string to make the queue read-only.
102 *
103 * Queue classes should throw an exception if they do not support the options given.
104 *
105 * @param array $params
106 * @return JobQueue
107 * @throws MWException
108 */
109 final public static function factory( array $params ) {
110 $class = $params['class'];
111 if ( !class_exists( $class ) ) {
112 throw new MWException( "Invalid job queue class '$class'." );
113 }
114 $obj = new $class( $params );
115 if ( !( $obj instanceof self ) ) {
116 throw new MWException( "Class '$class' is not a " . __CLASS__ . " class." );
117 }
118
119 return $obj;
120 }
121
122 /**
123 * @return string Wiki ID
124 */
125 final public function getWiki() {
126 return $this->wiki;
127 }
128
129 /**
130 * @return string Job type that this queue handles
131 */
132 final public function getType() {
133 return $this->type;
134 }
135
136 /**
137 * @return string One of (random, timestamp, fifo, undefined)
138 */
139 final public function getOrder() {
140 return $this->order;
141 }
142
143 /**
144 * Get the allowed queue orders for configuration validation
145 *
146 * @return array Subset of (random, timestamp, fifo, undefined)
147 */
148 abstract protected function supportedOrders();
149
150 /**
151 * Get the default queue order to use if configuration does not specify one
152 *
153 * @return string One of (random, timestamp, fifo, undefined)
154 */
155 abstract protected function optimalOrder();
156
157 /**
158 * Find out if delayed jobs are supported for configuration validation
159 *
160 * @return bool Whether delayed jobs are supported
161 */
162 protected function supportsDelayedJobs() {
163 return false; // not implemented
164 }
165
166 /**
167 * @return bool Whether delayed jobs are enabled
168 * @since 1.22
169 */
170 final public function delayedJobsEnabled() {
171 return $this->supportsDelayedJobs();
172 }
173
174 /**
175 * @return string|bool Read-only rational or false if r/w
176 * @since 1.27
177 */
178 public function getReadOnlyReason() {
179 return $this->readOnlyReason;
180 }
181
182 /**
183 * Quickly check if the queue has no available (unacquired, non-delayed) jobs.
184 * Queue classes should use caching if they are any slower without memcached.
185 *
186 * If caching is used, this might return false when there are actually no jobs.
187 * If pop() is called and returns false then it should correct the cache. Also,
188 * calling flushCaches() first prevents this. However, this affect is typically
189 * not distinguishable from the race condition between isEmpty() and pop().
190 *
191 * @return bool
192 * @throws JobQueueError
193 */
194 final public function isEmpty() {
195 $res = $this->doIsEmpty();
196
197 return $res;
198 }
199
200 /**
201 * @see JobQueue::isEmpty()
202 * @return bool
203 */
204 abstract protected function doIsEmpty();
205
206 /**
207 * Get the number of available (unacquired, non-delayed) jobs in the queue.
208 * Queue classes should use caching if they are any slower without memcached.
209 *
210 * If caching is used, this number might be out of date for a minute.
211 *
212 * @return int
213 * @throws JobQueueError
214 */
215 final public function getSize() {
216 $res = $this->doGetSize();
217
218 return $res;
219 }
220
221 /**
222 * @see JobQueue::getSize()
223 * @return int
224 */
225 abstract protected function doGetSize();
226
227 /**
228 * Get the number of acquired jobs (these are temporarily out of the queue).
229 * Queue classes should use caching if they are any slower without memcached.
230 *
231 * If caching is used, this number might be out of date for a minute.
232 *
233 * @return int
234 * @throws JobQueueError
235 */
236 final public function getAcquiredCount() {
237 $res = $this->doGetAcquiredCount();
238
239 return $res;
240 }
241
242 /**
243 * @see JobQueue::getAcquiredCount()
244 * @return int
245 */
246 abstract protected function doGetAcquiredCount();
247
248 /**
249 * Get the number of delayed jobs (these are temporarily out of the queue).
250 * Queue classes should use caching if they are any slower without memcached.
251 *
252 * If caching is used, this number might be out of date for a minute.
253 *
254 * @return int
255 * @throws JobQueueError
256 * @since 1.22
257 */
258 final public function getDelayedCount() {
259 $res = $this->doGetDelayedCount();
260
261 return $res;
262 }
263
264 /**
265 * @see JobQueue::getDelayedCount()
266 * @return int
267 */
268 protected function doGetDelayedCount() {
269 return 0; // not implemented
270 }
271
272 /**
273 * Get the number of acquired jobs that can no longer be attempted.
274 * Queue classes should use caching if they are any slower without memcached.
275 *
276 * If caching is used, this number might be out of date for a minute.
277 *
278 * @return int
279 * @throws JobQueueError
280 */
281 final public function getAbandonedCount() {
282 $res = $this->doGetAbandonedCount();
283
284 return $res;
285 }
286
287 /**
288 * @see JobQueue::getAbandonedCount()
289 * @return int
290 */
291 protected function doGetAbandonedCount() {
292 return 0; // not implemented
293 }
294
295 /**
296 * Push one or more jobs into the queue.
297 * This does not require $wgJobClasses to be set for the given job type.
298 * Outside callers should use JobQueueGroup::push() instead of this function.
299 *
300 * @param IJobSpecification|IJobSpecification[] $jobs
301 * @param int $flags Bitfield (supports JobQueue::QOS_ATOMIC)
302 * @return void
303 * @throws JobQueueError
304 */
305 final public function push( $jobs, $flags = 0 ) {
306 $jobs = is_array( $jobs ) ? $jobs : [ $jobs ];
307 $this->batchPush( $jobs, $flags );
308 }
309
310 /**
311 * Push a batch of jobs into the queue.
312 * This does not require $wgJobClasses to be set for the given job type.
313 * Outside callers should use JobQueueGroup::push() instead of this function.
314 *
315 * @param IJobSpecification[] $jobs
316 * @param int $flags Bitfield (supports JobQueue::QOS_ATOMIC)
317 * @return void
318 * @throws MWException
319 */
320 final public function batchPush( array $jobs, $flags = 0 ) {
321 $this->assertNotReadOnly();
322
323 if ( !count( $jobs ) ) {
324 return; // nothing to do
325 }
326
327 foreach ( $jobs as $job ) {
328 if ( $job->getType() !== $this->type ) {
329 throw new MWException(
330 "Got '{$job->getType()}' job; expected a '{$this->type}' job." );
331 } elseif ( $job->getReleaseTimestamp() && !$this->supportsDelayedJobs() ) {
332 throw new MWException(
333 "Got delayed '{$job->getType()}' job; delays are not supported." );
334 }
335 }
336
337 $this->doBatchPush( $jobs, $flags );
338 $this->aggr->notifyQueueNonEmpty( $this->wiki, $this->type );
339
340 foreach ( $jobs as $job ) {
341 if ( $job->isRootJob() ) {
342 $this->deduplicateRootJob( $job );
343 }
344 }
345 }
346
347 /**
348 * @see JobQueue::batchPush()
349 * @param IJobSpecification[] $jobs
350 * @param int $flags
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 $this->assertNotReadOnly();
366 if ( $this->wiki !== wfWikiID() ) {
367 throw new MWException( "Cannot pop '{$this->type}' job off foreign wiki queue." );
368 } elseif ( !isset( $wgJobClasses[$this->type] ) ) {
369 // Do not pop jobs if there is no class for the queue type
370 throw new MWException( "Unrecognized job type '{$this->type}'." );
371 }
372
373 $job = $this->doPop();
374
375 if ( !$job ) {
376 $this->aggr->notifyQueueEmpty( $this->wiki, $this->type );
377 }
378
379 // Flag this job as an old duplicate based on its "root" job...
380 try {
381 if ( $job && $this->isRootJobOldDuplicate( $job ) ) {
382 JobQueue::incrStats( 'dupe_pops', $this->type );
383 $job = DuplicateJob::newFromJob( $job ); // convert to a no-op
384 }
385 } catch ( Exception $e ) {
386 // don't lose jobs over this
387 }
388
389 return $job;
390 }
391
392 /**
393 * @see JobQueue::pop()
394 * @return Job|bool
395 */
396 abstract protected function doPop();
397
398 /**
399 * Acknowledge that a job was completed.
400 *
401 * This does nothing for certain queue classes or if "claimTTL" is not set.
402 * Outside callers should use JobQueueGroup::ack() instead of this function.
403 *
404 * @param Job $job
405 * @return void
406 * @throws MWException
407 */
408 final public function ack( Job $job ) {
409 $this->assertNotReadOnly();
410 if ( $job->getType() !== $this->type ) {
411 throw new MWException( "Got '{$job->getType()}' job; expected '{$this->type}'." );
412 }
413
414 $this->doAck( $job );
415 }
416
417 /**
418 * @see JobQueue::ack()
419 * @param Job $job
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 range and leaf job subtypes.
438 * Since these jobs include things like page ID ranges and DB master positions,
439 * and can morph into smaller jobs recursively, simple duplicate detection
440 * for individual jobs being identical (like that of job_sha1) 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 IJobSpecification $job
451 * @throws MWException
452 * @return bool
453 */
454 final public function deduplicateRootJob( IJobSpecification $job ) {
455 $this->assertNotReadOnly();
456 if ( $job->getType() !== $this->type ) {
457 throw new MWException( "Got '{$job->getType()}' job; expected '{$this->type}'." );
458 }
459
460 return $this->doDeduplicateRootJob( $job );
461 }
462
463 /**
464 * @see JobQueue::deduplicateRootJob()
465 * @param IJobSpecification $job
466 * @throws MWException
467 * @return bool
468 */
469 protected function doDeduplicateRootJob( IJobSpecification $job ) {
470 if ( !$job->hasRootJobParams() ) {
471 throw new MWException( "Cannot register root job; missing parameters." );
472 }
473 $params = $job->getRootJobParams();
474
475 $key = $this->getRootJobCacheKey( $params['rootJobSignature'] );
476 // Callers should call batchInsert() and then this function so that if the insert
477 // fails, the de-duplication registration will be aborted. Since the insert is
478 // deferred till "transaction idle", do the same here, so that the ordering is
479 // maintained. Having only the de-duplication registration succeed would cause
480 // jobs to become no-ops without any actual jobs that made them redundant.
481 $timestamp = $this->dupCache->get( $key ); // current last timestamp of this job
482 if ( $timestamp && $timestamp >= $params['rootJobTimestamp'] ) {
483 return true; // a newer version of this root job was enqueued
484 }
485
486 // Update the timestamp of the last root job started at the location...
487 return $this->dupCache->set( $key, $params['rootJobTimestamp'], JobQueueDB::ROOTJOB_TTL );
488 }
489
490 /**
491 * Check if the "root" job of a given job has been superseded by a newer one
492 *
493 * @param Job $job
494 * @throws MWException
495 * @return bool
496 */
497 final protected function isRootJobOldDuplicate( Job $job ) {
498 if ( $job->getType() !== $this->type ) {
499 throw new MWException( "Got '{$job->getType()}' job; expected '{$this->type}'." );
500 }
501 $isDuplicate = $this->doIsRootJobOldDuplicate( $job );
502
503 return $isDuplicate;
504 }
505
506 /**
507 * @see JobQueue::isRootJobOldDuplicate()
508 * @param Job $job
509 * @return bool
510 */
511 protected function doIsRootJobOldDuplicate( Job $job ) {
512 if ( !$job->hasRootJobParams() ) {
513 return false; // job has no de-deplication info
514 }
515 $params = $job->getRootJobParams();
516
517 $key = $this->getRootJobCacheKey( $params['rootJobSignature'] );
518 // Get the last time this root job was enqueued
519 $timestamp = $this->dupCache->get( $key );
520
521 // Check if a new root job was started at the location after this one's...
522 return ( $timestamp && $timestamp > $params['rootJobTimestamp'] );
523 }
524
525 /**
526 * @param string $signature Hash identifier of the root job
527 * @return string
528 */
529 protected function getRootJobCacheKey( $signature ) {
530 list( $db, $prefix ) = wfSplitWikiID( $this->wiki );
531
532 return wfForeignMemcKey( $db, $prefix, 'jobqueue', $this->type, 'rootjob', $signature );
533 }
534
535 /**
536 * Deleted all unclaimed and delayed jobs from the queue
537 *
538 * @throws JobQueueError
539 * @since 1.22
540 * @return void
541 */
542 final public function delete() {
543 $this->assertNotReadOnly();
544
545 $this->doDelete();
546 }
547
548 /**
549 * @see JobQueue::delete()
550 * @throws MWException
551 */
552 protected function doDelete() {
553 throw new MWException( "This method is not implemented." );
554 }
555
556 /**
557 * Wait for any replica DBs or backup servers to catch up.
558 *
559 * This does nothing for certain queue classes.
560 *
561 * @return void
562 * @throws JobQueueError
563 */
564 final public function waitForBackups() {
565 $this->doWaitForBackups();
566 }
567
568 /**
569 * @see JobQueue::waitForBackups()
570 * @return void
571 */
572 protected function doWaitForBackups() {
573 }
574
575 /**
576 * Clear any process and persistent caches
577 *
578 * @return void
579 */
580 final public function flushCaches() {
581 $this->doFlushCaches();
582 }
583
584 /**
585 * @see JobQueue::flushCaches()
586 * @return void
587 */
588 protected function doFlushCaches() {
589 }
590
591 /**
592 * Get an iterator to traverse over all available jobs in this queue.
593 * This does not include jobs that are currently acquired or delayed.
594 * Note: results may be stale if the queue is concurrently modified.
595 *
596 * @return Iterator
597 * @throws JobQueueError
598 */
599 abstract public function getAllQueuedJobs();
600
601 /**
602 * Get an iterator to traverse over all delayed jobs in this queue.
603 * Note: results may be stale if the queue is concurrently modified.
604 *
605 * @return Iterator
606 * @throws JobQueueError
607 * @since 1.22
608 */
609 public function getAllDelayedJobs() {
610 return new ArrayIterator( [] ); // not implemented
611 }
612
613 /**
614 * Get an iterator to traverse over all claimed jobs in this queue
615 *
616 * Callers should be quick to iterator over it or few results
617 * will be returned due to jobs being acknowledged and deleted
618 *
619 * @return Iterator
620 * @throws JobQueueError
621 * @since 1.26
622 */
623 public function getAllAcquiredJobs() {
624 return new ArrayIterator( [] ); // not implemented
625 }
626
627 /**
628 * Get an iterator to traverse over all abandoned jobs in this queue
629 *
630 * @return Iterator
631 * @throws JobQueueError
632 * @since 1.25
633 */
634 public function getAllAbandonedJobs() {
635 return new ArrayIterator( [] ); // not implemented
636 }
637
638 /**
639 * Do not use this function outside of JobQueue/JobQueueGroup
640 *
641 * @return string
642 * @since 1.22
643 */
644 public function getCoalesceLocationInternal() {
645 return null;
646 }
647
648 /**
649 * Check whether each of the given queues are empty.
650 * This is used for batching checks for queues stored at the same place.
651 *
652 * @param array $types List of queues types
653 * @return array|null (list of non-empty queue types) or null if unsupported
654 * @throws MWException
655 * @since 1.22
656 */
657 final public function getSiblingQueuesWithJobs( array $types ) {
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 return $this->doGetSiblingQueueSizes( $types );
682 }
683
684 /**
685 * @see JobQueue::getSiblingQueuesSize()
686 * @param array $types List of queues types
687 * @return array|null (list of queue types) or null if unsupported
688 */
689 protected function doGetSiblingQueueSizes( array $types ) {
690 return null; // not supported
691 }
692
693 /**
694 * @throws JobQueueReadOnlyError
695 */
696 protected function assertNotReadOnly() {
697 if ( $this->readOnlyReason !== false ) {
698 throw new JobQueueReadOnlyError( "Job queue is read-only: {$this->readOnlyReason}" );
699 }
700 }
701
702 /**
703 * Call wfIncrStats() for the queue overall and for the queue type
704 *
705 * @param string $key Event type
706 * @param string $type Job type
707 * @param int $delta
708 * @since 1.22
709 */
710 public static function incrStats( $key, $type, $delta = 1 ) {
711 static $stats;
712 if ( !$stats ) {
713 $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
714 }
715 $stats->updateCount( "jobqueue.{$key}.all", $delta );
716 $stats->updateCount( "jobqueue.{$key}.{$type}", $delta );
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 }
729
730 class JobQueueReadOnlyError extends JobQueueError {
731
732 }