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