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