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