Merge "Exclude redirects from Special:Fewestrevisions"
[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 WANObjectCache */
48 protected $wanCache;
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 * - type : A job type
57 * - domain : A DB domain ID
58 * - wanCache : An instance of WANObjectCache to use for caching [default: none]
59 * - stats : An instance of StatsdDataFactoryInterface [default: none]
60 * - claimTTL : Seconds a job can be claimed for exclusive execution [default: forever]
61 * - maxTries : Total times a job can be tried, assuming claims expire [default: 3]
62 * - order : Queue order, one of ("fifo", "timestamp", "random") [default: variable]
63 * - readOnlyReason : Mark the queue as read-only with this reason [default: false]
64 * @throws JobQueueError
65 */
66 protected function __construct( array $params ) {
67 $this->domain = $params['domain'] ?? $params['wiki']; // b/c
68 $this->type = $params['type'];
69 $this->claimTTL = $params['claimTTL'] ?? 0;
70 $this->maxTries = $params['maxTries'] ?? 3;
71 if ( isset( $params['order'] ) && $params['order'] !== 'any' ) {
72 $this->order = $params['order'];
73 } else {
74 $this->order = $this->optimalOrder();
75 }
76 if ( !in_array( $this->order, $this->supportedOrders() ) ) {
77 throw new JobQueueError( __CLASS__ . " does not support '{$this->order}' order." );
78 }
79 $this->readOnlyReason = $params['readOnlyReason'] ?? false;
80 $this->stats = $params['stats'] ?? new NullStatsdDataFactory();
81 $this->wanCache = $params['wanCache'] ?? WANObjectCache::newEmpty();
82 }
83
84 /**
85 * Get a job queue object of the specified type.
86 * $params includes:
87 * - class : What job class to use (determines job type)
88 * - domain : Database domain ID of the wiki the jobs are for (defaults to current wiki)
89 * - type : The name of the job types this queue handles
90 * - order : Order that pop() selects jobs, one of "fifo", "timestamp" or "random".
91 * If "fifo" is used, the queue will effectively be FIFO. Note that job
92 * completion will not appear to be exactly FIFO if there are multiple
93 * job runners since jobs can take different times to finish once popped.
94 * If "timestamp" is used, the queue will at least be loosely ordered
95 * by timestamp, allowing for some jobs to be popped off out of order.
96 * If "random" is used, pop() will pick jobs in random order.
97 * Note that it may only be weakly random (e.g. a lottery of the oldest X).
98 * If "any" is choosen, the queue will use whatever order is the fastest.
99 * This might be useful for improving concurrency for job acquisition.
100 * - claimTTL : If supported, the queue will recycle jobs that have been popped
101 * but not acknowledged as completed after this many seconds. Recycling
102 * of jobs simply means re-inserting them into the queue. Jobs can be
103 * attempted up to three times before being discarded.
104 * - readOnlyReason : Set this to a string to make the queue read-only.
105 * - stash : A BagOStuff instance that can be used for root job deduplication
106 * - stats : A StatsdDataFactoryInterface [optional]
107 *
108 * Queue classes should throw an exception if they do not support the options given.
109 *
110 * @param array $params
111 * @return JobQueue
112 * @throws JobQueueError
113 */
114 final public static function factory( array $params ) {
115 $class = $params['class'];
116 if ( !class_exists( $class ) ) {
117 throw new JobQueueError( "Invalid job queue class '$class'." );
118 }
119 $obj = new $class( $params );
120 if ( !( $obj instanceof self ) ) {
121 throw new JobQueueError( "Class '$class' is not a " . __CLASS__ . " class." );
122 }
123
124 return $obj;
125 }
126
127 /**
128 * @return string Database domain ID
129 */
130 final public function getDomain() {
131 return $this->domain;
132 }
133
134 /**
135 * @return string Wiki ID
136 * @deprecated 1.33
137 */
138 final public function getWiki() {
139 return WikiMap::getWikiIdFromDbDomain( $this->domain );
140 }
141
142 /**
143 * @return string Job type that this queue handles
144 */
145 final public function getType() {
146 return $this->type;
147 }
148
149 /**
150 * @return string One of (random, timestamp, fifo, undefined)
151 */
152 final public function getOrder() {
153 return $this->order;
154 }
155
156 /**
157 * Get the allowed queue orders for configuration validation
158 *
159 * @return array Subset of (random, timestamp, fifo, undefined)
160 */
161 abstract protected function supportedOrders();
162
163 /**
164 * Get the default queue order to use if configuration does not specify one
165 *
166 * @return string One of (random, timestamp, fifo, undefined)
167 */
168 abstract protected function optimalOrder();
169
170 /**
171 * Find out if delayed jobs are supported for configuration validation
172 *
173 * @return bool Whether delayed jobs are supported
174 */
175 protected function supportsDelayedJobs() {
176 return false; // not implemented
177 }
178
179 /**
180 * @return bool Whether delayed jobs are enabled
181 * @since 1.22
182 */
183 final public function delayedJobsEnabled() {
184 return $this->supportsDelayedJobs();
185 }
186
187 /**
188 * @return string|bool Read-only rational or false if r/w
189 * @since 1.27
190 */
191 public function getReadOnlyReason() {
192 return $this->readOnlyReason;
193 }
194
195 /**
196 * Quickly check if the queue has no available (unacquired, non-delayed) jobs.
197 * Queue classes should use caching if they are any slower without memcached.
198 *
199 * If caching is used, this might return false when there are actually no jobs.
200 * If pop() is called and returns false then it should correct the cache. Also,
201 * calling flushCaches() first prevents this. However, this affect is typically
202 * not distinguishable from the race condition between isEmpty() and pop().
203 *
204 * @return bool
205 * @throws JobQueueError
206 */
207 final public function isEmpty() {
208 $res = $this->doIsEmpty();
209
210 return $res;
211 }
212
213 /**
214 * @see JobQueue::isEmpty()
215 * @return bool
216 */
217 abstract protected function doIsEmpty();
218
219 /**
220 * Get the number of available (unacquired, non-delayed) jobs in the queue.
221 * Queue classes should use caching if they are any slower without memcached.
222 *
223 * If caching is used, this number might be out of date for a minute.
224 *
225 * @return int
226 * @throws JobQueueError
227 */
228 final public function getSize() {
229 $res = $this->doGetSize();
230
231 return $res;
232 }
233
234 /**
235 * @see JobQueue::getSize()
236 * @return int
237 */
238 abstract protected function doGetSize();
239
240 /**
241 * Get the number of acquired jobs (these are temporarily out of the queue).
242 * Queue classes should use caching if they are any slower without memcached.
243 *
244 * If caching is used, this number might be out of date for a minute.
245 *
246 * @return int
247 * @throws JobQueueError
248 */
249 final public function getAcquiredCount() {
250 $res = $this->doGetAcquiredCount();
251
252 return $res;
253 }
254
255 /**
256 * @see JobQueue::getAcquiredCount()
257 * @return int
258 */
259 abstract protected function doGetAcquiredCount();
260
261 /**
262 * Get the number of delayed jobs (these are temporarily out of the queue).
263 * Queue classes should use caching if they are any slower without memcached.
264 *
265 * If caching is used, this number might be out of date for a minute.
266 *
267 * @return int
268 * @throws JobQueueError
269 * @since 1.22
270 */
271 final public function getDelayedCount() {
272 $res = $this->doGetDelayedCount();
273
274 return $res;
275 }
276
277 /**
278 * @see JobQueue::getDelayedCount()
279 * @return int
280 */
281 protected function doGetDelayedCount() {
282 return 0; // not implemented
283 }
284
285 /**
286 * Get the number of acquired jobs that can no longer be attempted.
287 * Queue classes should use caching if they are any slower without memcached.
288 *
289 * If caching is used, this number might be out of date for a minute.
290 *
291 * @return int
292 * @throws JobQueueError
293 */
294 final public function getAbandonedCount() {
295 $res = $this->doGetAbandonedCount();
296
297 return $res;
298 }
299
300 /**
301 * @see JobQueue::getAbandonedCount()
302 * @return int
303 */
304 protected function doGetAbandonedCount() {
305 return 0; // not implemented
306 }
307
308 /**
309 * Push one or more jobs into the queue.
310 * This does not require $wgJobClasses to be set for the given job type.
311 * Outside callers should use JobQueueGroup::push() instead of this function.
312 *
313 * @param IJobSpecification|IJobSpecification[] $jobs
314 * @param int $flags Bitfield (supports JobQueue::QOS_ATOMIC)
315 * @return void
316 * @throws JobQueueError
317 */
318 final public function push( $jobs, $flags = 0 ) {
319 $jobs = is_array( $jobs ) ? $jobs : [ $jobs ];
320 $this->batchPush( $jobs, $flags );
321 }
322
323 /**
324 * Push a batch of jobs into the queue.
325 * This does not require $wgJobClasses to be set for the given job type.
326 * Outside callers should use JobQueueGroup::push() instead of this function.
327 *
328 * @param IJobSpecification[] $jobs
329 * @param int $flags Bitfield (supports JobQueue::QOS_ATOMIC)
330 * @return void
331 * @throws JobQueueError
332 */
333 final public function batchPush( array $jobs, $flags = 0 ) {
334 $this->assertNotReadOnly();
335
336 if ( $jobs === [] ) {
337 return; // nothing to do
338 }
339
340 foreach ( $jobs as $job ) {
341 if ( $job->getType() !== $this->type ) {
342 throw new JobQueueError(
343 "Got '{$job->getType()}' job; expected a '{$this->type}' job." );
344 } elseif ( $job->getReleaseTimestamp() && !$this->supportsDelayedJobs() ) {
345 throw new JobQueueError(
346 "Got delayed '{$job->getType()}' job; delays are not supported." );
347 }
348 }
349
350 $this->doBatchPush( $jobs, $flags );
351
352 foreach ( $jobs as $job ) {
353 if ( $job->isRootJob() ) {
354 $this->deduplicateRootJob( $job );
355 }
356 }
357 }
358
359 /**
360 * @see JobQueue::batchPush()
361 * @param IJobSpecification[] $jobs
362 * @param int $flags
363 */
364 abstract protected function doBatchPush( array $jobs, $flags );
365
366 /**
367 * Pop a job off of the queue.
368 * This requires $wgJobClasses to be set for the given job type.
369 * Outside callers should use JobQueueGroup::pop() instead of this function.
370 *
371 * @throws JobQueueError
372 * @return RunnableJob|bool Returns false if there are no jobs
373 */
374 final public function pop() {
375 $this->assertNotReadOnly();
376
377 $job = $this->doPop();
378
379 // Flag this job as an old duplicate based on its "root" job...
380 try {
381 if ( $job && $this->isRootJobOldDuplicate( $job ) ) {
382 $this->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 RunnableJob|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 RunnableJob $job
405 * @return void
406 * @throws JobQueueError
407 */
408 final public function ack( RunnableJob $job ) {
409 $this->assertNotReadOnly();
410 if ( $job->getType() !== $this->type ) {
411 throw new JobQueueError( "Got '{$job->getType()}' job; expected '{$this->type}'." );
412 }
413
414 $this->doAck( $job );
415 }
416
417 /**
418 * @see JobQueue::ack()
419 * @param RunnableJob $job
420 */
421 abstract protected function doAck( RunnableJob $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 JobQueueError
452 * @return bool
453 */
454 final public function deduplicateRootJob( IJobSpecification $job ) {
455 $this->assertNotReadOnly();
456 if ( $job->getType() !== $this->type ) {
457 throw new JobQueueError( "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 JobQueueError
467 * @return bool
468 */
469 protected function doDeduplicateRootJob( IJobSpecification $job ) {
470 $params = $job->hasRootJobParams() ? $job->getRootJobParams() : null;
471 if ( !$params ) {
472 throw new JobQueueError( "Cannot register root job; missing parameters." );
473 }
474
475 $key = $this->getRootJobCacheKey( $params['rootJobSignature'] );
476 // Callers should call JobQueueGroup::push() before this method so that if the
477 // insert fails, the de-duplication registration will be aborted. Having only the
478 // de-duplication registration succeed would cause jobs to become no-ops without
479 // any actual jobs that made them redundant.
480 $timestamp = $this->wanCache->get( $key ); // last known timestamp of such a root job
481 if ( $timestamp !== false && $timestamp >= $params['rootJobTimestamp'] ) {
482 return true; // a newer version of this root job was enqueued
483 }
484
485 // Update the timestamp of the last root job started at the location...
486 return $this->wanCache->set( $key, $params['rootJobTimestamp'], self::ROOTJOB_TTL );
487 }
488
489 /**
490 * Check if the "root" job of a given job has been superseded by a newer one
491 *
492 * @param IJobSpecification $job
493 * @throws JobQueueError
494 * @return bool
495 */
496 final protected function isRootJobOldDuplicate( IJobSpecification $job ) {
497 if ( $job->getType() !== $this->type ) {
498 throw new JobQueueError( "Got '{$job->getType()}' job; expected '{$this->type}'." );
499 }
500
501 return $this->doIsRootJobOldDuplicate( $job );
502 }
503
504 /**
505 * @see JobQueue::isRootJobOldDuplicate()
506 * @param IJobSpecification $job
507 * @return bool
508 */
509 protected function doIsRootJobOldDuplicate( IJobSpecification $job ) {
510 $params = $job->hasRootJobParams() ? $job->getRootJobParams() : null;
511 if ( !$params ) {
512 return false; // job has no de-deplication info
513 }
514
515 $key = $this->getRootJobCacheKey( $params['rootJobSignature'] );
516 // Get the last time this root job was enqueued
517 $timestamp = $this->wanCache->get( $key );
518 if ( $timestamp === false || $params['rootJobTimestamp'] > $timestamp ) {
519 // Update the timestamp of the last known root job started at the location...
520 $this->wanCache->set( $key, $params['rootJobTimestamp'], self::ROOTJOB_TTL );
521 }
522
523 // Check if a new root job was started at the location after this one's...
524 return ( $timestamp && $timestamp > $params['rootJobTimestamp'] );
525 }
526
527 /**
528 * @param string $signature Hash identifier of the root job
529 * @return string
530 */
531 protected function getRootJobCacheKey( $signature ) {
532 return $this->wanCache->makeGlobalKey(
533 'jobqueue',
534 $this->domain,
535 $this->type,
536 'rootjob',
537 $signature
538 );
539 }
540
541 /**
542 * Deleted all unclaimed and delayed jobs from the queue
543 *
544 * @throws JobQueueError
545 * @since 1.22
546 * @return void
547 */
548 final public function delete() {
549 $this->assertNotReadOnly();
550
551 $this->doDelete();
552 }
553
554 /**
555 * @see JobQueue::delete()
556 * @throws JobQueueError
557 */
558 protected function doDelete() {
559 throw new JobQueueError( "This method is not implemented." );
560 }
561
562 /**
563 * Wait for any replica DBs or backup servers to catch up.
564 *
565 * This does nothing for certain queue classes.
566 *
567 * @return void
568 * @throws JobQueueError
569 */
570 final public function waitForBackups() {
571 $this->doWaitForBackups();
572 }
573
574 /**
575 * @see JobQueue::waitForBackups()
576 * @return void
577 */
578 protected function doWaitForBackups() {
579 }
580
581 /**
582 * Clear any process and persistent caches
583 *
584 * @return void
585 */
586 final public function flushCaches() {
587 $this->doFlushCaches();
588 }
589
590 /**
591 * @see JobQueue::flushCaches()
592 * @return void
593 */
594 protected function doFlushCaches() {
595 }
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( [] ); // not implemented
617 }
618
619 /**
620 * Get an iterator to traverse over all claimed jobs in this queue
621 *
622 * Callers should be quick to iterator over it or few results
623 * will be returned due to jobs being acknowledged and deleted
624 *
625 * @return Iterator
626 * @throws JobQueueError
627 * @since 1.26
628 */
629 public function getAllAcquiredJobs() {
630 return new ArrayIterator( [] ); // not implemented
631 }
632
633 /**
634 * Get an iterator to traverse over all abandoned jobs in this queue
635 *
636 * @return Iterator
637 * @throws JobQueueError
638 * @since 1.25
639 */
640 public function getAllAbandonedJobs() {
641 return new ArrayIterator( [] ); // not implemented
642 }
643
644 /**
645 * Do not use this function outside of JobQueue/JobQueueGroup
646 *
647 * @return string
648 * @since 1.22
649 */
650 public function getCoalesceLocationInternal() {
651 return null;
652 }
653
654 /**
655 * Check whether each of the given queues are empty.
656 * This is used for batching checks for queues stored at the same place.
657 *
658 * @param array $types List of queues types
659 * @return array|null (list of non-empty queue types) or null if unsupported
660 * @throws JobQueueError
661 * @since 1.22
662 */
663 final public function getSiblingQueuesWithJobs( array $types ) {
664 return $this->doGetSiblingQueuesWithJobs( $types );
665 }
666
667 /**
668 * @see JobQueue::getSiblingQueuesWithJobs()
669 * @param array $types List of queues types
670 * @return array|null (list of queue types) or null if unsupported
671 */
672 protected function doGetSiblingQueuesWithJobs( array $types ) {
673 return null; // not supported
674 }
675
676 /**
677 * Check the size of each of the given queues.
678 * For queues not served by the same store as this one, 0 is returned.
679 * This is used for batching checks for queues stored at the same place.
680 *
681 * @param array $types List of queues types
682 * @return array|null (job type => whether queue is empty) or null if unsupported
683 * @throws JobQueueError
684 * @since 1.22
685 */
686 final public function getSiblingQueueSizes( array $types ) {
687 return $this->doGetSiblingQueueSizes( $types );
688 }
689
690 /**
691 * @see JobQueue::getSiblingQueuesSize()
692 * @param array $types List of queues types
693 * @return array|null (list of queue types) or null if unsupported
694 */
695 protected function doGetSiblingQueueSizes( array $types ) {
696 return null; // not supported
697 }
698
699 /**
700 * @param string $command
701 * @param array $params
702 * @return Job
703 */
704 protected function factoryJob( $command, $params ) {
705 // @TODO: dependency inject this as a callback
706 return Job::factory( $command, $params );
707 }
708
709 /**
710 * @throws JobQueueReadOnlyError
711 */
712 protected function assertNotReadOnly() {
713 if ( $this->readOnlyReason !== false ) {
714 throw new JobQueueReadOnlyError( "Job queue is read-only: {$this->readOnlyReason}" );
715 }
716 }
717
718 /**
719 * Call wfIncrStats() for the queue overall and for the queue type
720 *
721 * @param string $key Event type
722 * @param string $type Job type
723 * @param int $delta
724 * @since 1.22
725 */
726 protected function incrStats( $key, $type, $delta = 1 ) {
727 $this->stats->updateCount( "jobqueue.{$key}.all", $delta );
728 $this->stats->updateCount( "jobqueue.{$key}.{$type}", $delta );
729 }
730 }