Merge "Update Chechen language namespace names from translatewiki"
[lhc/web/wiklou.git] / includes / job / JobQueue.php
1 <?php
2 /**
3 * Job queue base code.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @defgroup JobQueue JobQueue
22 * @author Aaron Schulz
23 */
24
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 protected $wiki; // string; wiki ID
33 protected $type; // string; job type
34 protected $order; // string; job priority for pop()
35 protected $claimTTL; // integer; seconds
36 protected $maxTries; // integer; maximum number of times to try a job
37 protected $checkDelay; // boolean; allow delayed jobs
38
39 const QOS_ATOMIC = 1; // integer; "all-or-nothing" job insertions
40 const QoS_Atomic = 1; // integer; "all-or-nothing" job insertions (b/c)
41
42 const ROOTJOB_TTL = 2419200; // integer; seconds to remember root jobs (28 days)
43
44 /**
45 * @param $params array
46 */
47 protected function __construct( array $params ) {
48 $this->wiki = $params['wiki'];
49 $this->type = $params['type'];
50 $this->claimTTL = isset( $params['claimTTL'] ) ? $params['claimTTL'] : 0;
51 $this->maxTries = isset( $params['maxTries'] ) ? $params['maxTries'] : 3;
52 if ( isset( $params['order'] ) && $params['order'] !== 'any' ) {
53 $this->order = $params['order'];
54 } else {
55 $this->order = $this->optimalOrder();
56 }
57 if ( !in_array( $this->order, $this->supportedOrders() ) ) {
58 throw new MWException( __CLASS__ . " does not support '{$this->order}' order." );
59 }
60 $this->checkDelay = !empty( $params['checkDelay'] );
61 if ( $this->checkDelay && !$this->supportsDelayedJobs() ) {
62 throw new MWException( __CLASS__ . " does not support delayed jobs." );
63 }
64 }
65
66 /**
67 * Get a job queue object of the specified type.
68 * $params includes:
69 * - class : What job class to use (determines job type)
70 * - wiki : wiki ID of the wiki the jobs are for (defaults to current wiki)
71 * - type : The name of the job types this queue handles
72 * - order : Order that pop() selects jobs, one of "fifo", "timestamp" or "random".
73 * If "fifo" is used, the queue will effectively be FIFO. Note that job
74 * completion will not appear to be exactly FIFO if there are multiple
75 * job runners since jobs can take different times to finish once popped.
76 * If "timestamp" is used, the queue will at least be loosely ordered
77 * by timestamp, allowing for some jobs to be popped off out of order.
78 * If "random" is used, pop() will pick jobs in random order.
79 * Note that it may only be weakly random (e.g. a lottery of the oldest X).
80 * If "any" is choosen, the queue will use whatever order is the fastest.
81 * This might be useful for improving concurrency for job acquisition.
82 * - claimTTL : If supported, the queue will recycle jobs that have been popped
83 * but not acknowledged as completed after this many seconds. Recycling
84 * of jobs simple means re-inserting them into the queue. Jobs can be
85 * attempted up to three times before being discarded.
86 * - checkDelay : If supported, respect Job::getReleaseTimestamp() in the push functions.
87 * This lets delayed jobs wait in a staging area until a given timestamp is
88 * reached, at which point they will enter the queue. If this is not enabled
89 * or not supported, an exception will be thrown on delayed job insertion.
90 *
91 * Queue classes should throw an exception if they do not support the options given.
92 *
93 * @param $params array
94 * @return JobQueue
95 * @throws MWException
96 */
97 final public static function factory( array $params ) {
98 $class = $params['class'];
99 if ( !class_exists( $class ) ) {
100 throw new MWException( "Invalid job queue class '$class'." );
101 }
102 $obj = new $class( $params );
103 if ( !( $obj instanceof self ) ) {
104 throw new MWException( "Class '$class' is not a " . __CLASS__ . " class." );
105 }
106 return $obj;
107 }
108
109 /**
110 * @return string Wiki ID
111 */
112 final public function getWiki() {
113 return $this->wiki;
114 }
115
116 /**
117 * @return string Job type that this queue handles
118 */
119 final public function getType() {
120 return $this->type;
121 }
122
123 /**
124 * @return string One of (random, timestamp, fifo, undefined)
125 */
126 final public function getOrder() {
127 return $this->order;
128 }
129
130 /**
131 * @return bool Whether delayed jobs are enabled
132 * @since 1.22
133 */
134 final public function delayedJobsEnabled() {
135 return $this->checkDelay;
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 boolean Whether delayed jobs are supported
156 */
157 protected function supportsDelayedJobs() {
158 return false; // not implemented
159 }
160
161 /**
162 * Quickly check if the queue has no available (unacquired, non-delayed) jobs.
163 * Queue classes should use caching if they are any slower without memcached.
164 *
165 * If caching is used, this might return false when there are actually no jobs.
166 * If pop() is called and returns false then it should correct the cache. Also,
167 * calling flushCaches() first prevents this. However, this affect is typically
168 * not distinguishable from the race condition between isEmpty() and pop().
169 *
170 * @return bool
171 * @throws JobQueueError
172 */
173 final public function isEmpty() {
174 wfProfileIn( __METHOD__ );
175 $res = $this->doIsEmpty();
176 wfProfileOut( __METHOD__ );
177 return $res;
178 }
179
180 /**
181 * @see JobQueue::isEmpty()
182 * @return bool
183 */
184 abstract protected function doIsEmpty();
185
186 /**
187 * Get the number of available (unacquired, non-delayed) jobs in the queue.
188 * Queue classes should use caching if they are any slower without memcached.
189 *
190 * If caching is used, this number might be out of date for a minute.
191 *
192 * @return integer
193 * @throws JobQueueError
194 */
195 final public function getSize() {
196 wfProfileIn( __METHOD__ );
197 $res = $this->doGetSize();
198 wfProfileOut( __METHOD__ );
199 return $res;
200 }
201
202 /**
203 * @see JobQueue::getSize()
204 * @return integer
205 */
206 abstract protected function doGetSize();
207
208 /**
209 * Get the number of acquired jobs (these are temporarily out of the queue).
210 * Queue classes should use caching if they are any slower without memcached.
211 *
212 * If caching is used, this number might be out of date for a minute.
213 *
214 * @return integer
215 * @throws JobQueueError
216 */
217 final public function getAcquiredCount() {
218 wfProfileIn( __METHOD__ );
219 $res = $this->doGetAcquiredCount();
220 wfProfileOut( __METHOD__ );
221 return $res;
222 }
223
224 /**
225 * @see JobQueue::getAcquiredCount()
226 * @return integer
227 */
228 abstract protected function doGetAcquiredCount();
229
230 /**
231 * Get the number of delayed 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 integer
237 * @throws JobQueueError
238 * @since 1.22
239 */
240 final public function getDelayedCount() {
241 wfProfileIn( __METHOD__ );
242 $res = $this->doGetDelayedCount();
243 wfProfileOut( __METHOD__ );
244 return $res;
245 }
246
247 /**
248 * @see JobQueue::getDelayedCount()
249 * @return integer
250 */
251 protected function doGetDelayedCount() {
252 return 0; // not implemented
253 }
254
255 /**
256 * Get the number of acquired jobs that can no longer be attempted.
257 * Queue classes should use caching if they are any slower without memcached.
258 *
259 * If caching is used, this number might be out of date for a minute.
260 *
261 * @return integer
262 * @throws JobQueueError
263 */
264 final public function getAbandonedCount() {
265 wfProfileIn( __METHOD__ );
266 $res = $this->doGetAbandonedCount();
267 wfProfileOut( __METHOD__ );
268 return $res;
269 }
270
271 /**
272 * @see JobQueue::getAbandonedCount()
273 * @return integer
274 */
275 protected function doGetAbandonedCount() {
276 return 0; // not implemented
277 }
278
279 /**
280 * Push a single jobs into the queue.
281 * This does not require $wgJobClasses to be set for the given job type.
282 * Outside callers should use JobQueueGroup::push() instead of this function.
283 *
284 * @param $jobs Job|Array
285 * @param $flags integer Bitfield (supports JobQueue::QOS_ATOMIC)
286 * @return bool Returns false on failure
287 * @throws JobQueueError
288 */
289 final public function push( $jobs, $flags = 0 ) {
290 return $this->batchPush( is_array( $jobs ) ? $jobs : array( $jobs ), $flags );
291 }
292
293 /**
294 * Push a batch of jobs into the queue.
295 * This does not require $wgJobClasses to be set for the given job type.
296 * Outside callers should use JobQueueGroup::push() instead of this function.
297 *
298 * @param array $jobs List of Jobs
299 * @param $flags integer Bitfield (supports JobQueue::QOS_ATOMIC)
300 * @return bool Returns false on failure
301 * @throws JobQueueError
302 */
303 final public function batchPush( array $jobs, $flags = 0 ) {
304 if ( !count( $jobs ) ) {
305 return true; // nothing to do
306 }
307
308 foreach ( $jobs as $job ) {
309 if ( $job->getType() !== $this->type ) {
310 throw new MWException(
311 "Got '{$job->getType()}' job; expected a '{$this->type}' job." );
312 } elseif ( $job->getReleaseTimestamp() && !$this->checkDelay ) {
313 throw new MWException(
314 "Got delayed '{$job->getType()}' job; delays are not supported." );
315 }
316 }
317
318 wfProfileIn( __METHOD__ );
319 $ok = $this->doBatchPush( $jobs, $flags );
320 wfProfileOut( __METHOD__ );
321 return $ok;
322 }
323
324 /**
325 * @see JobQueue::batchPush()
326 * @return bool
327 */
328 abstract protected function doBatchPush( array $jobs, $flags );
329
330 /**
331 * Pop a job off of the queue.
332 * This requires $wgJobClasses to be set for the given job type.
333 * Outside callers should use JobQueueGroup::pop() instead of this function.
334 *
335 * @return Job|bool Returns false if there are no jobs
336 * @throws JobQueueError
337 */
338 final public function pop() {
339 global $wgJobClasses;
340
341 if ( $this->wiki !== wfWikiID() ) {
342 throw new MWException( "Cannot pop '{$this->type}' job off foreign wiki queue." );
343 } elseif ( !isset( $wgJobClasses[$this->type] ) ) {
344 // Do not pop jobs if there is no class for the queue type
345 throw new MWException( "Unrecognized job type '{$this->type}'." );
346 }
347
348 wfProfileIn( __METHOD__ );
349 $job = $this->doPop();
350 wfProfileOut( __METHOD__ );
351
352 // Flag this job as an old duplicate based on its "root" job...
353 try {
354 if ( $job && $this->isRootJobOldDuplicate( $job ) ) {
355 JobQueue::incrStats( 'job-pop-duplicate', $this->type );
356 $job = DuplicateJob::newFromJob( $job ); // convert to a no-op
357 }
358 } catch ( MWException $e ) {} // don't lose jobs over this
359
360 return $job;
361 }
362
363 /**
364 * @see JobQueue::pop()
365 * @return Job
366 */
367 abstract protected function doPop();
368
369 /**
370 * Acknowledge that a job was completed.
371 *
372 * This does nothing for certain queue classes or if "claimTTL" is not set.
373 * Outside callers should use JobQueueGroup::ack() instead of this function.
374 *
375 * @param $job Job
376 * @return bool
377 * @throws JobQueueError
378 */
379 final public function ack( Job $job ) {
380 if ( $job->getType() !== $this->type ) {
381 throw new MWException( "Got '{$job->getType()}' job; expected '{$this->type}'." );
382 }
383 wfProfileIn( __METHOD__ );
384 $ok = $this->doAck( $job );
385 wfProfileOut( __METHOD__ );
386 return $ok;
387 }
388
389 /**
390 * @see JobQueue::ack()
391 * @return bool
392 */
393 abstract protected function doAck( Job $job );
394
395 /**
396 * Register the "root job" of a given job into the queue for de-duplication.
397 * This should only be called right *after* all the new jobs have been inserted.
398 * This is used to turn older, duplicate, job entries into no-ops. The root job
399 * information will remain in the registry until it simply falls out of cache.
400 *
401 * This requires that $job has two special fields in the "params" array:
402 * - rootJobSignature : hash (e.g. SHA1) that identifies the task
403 * - rootJobTimestamp : TS_MW timestamp of this instance of the task
404 *
405 * A "root job" is a conceptual job that consist of potentially many smaller jobs
406 * that are actually inserted into the queue. For example, "refreshLinks" jobs are
407 * spawned when a template is edited. One can think of the task as "update links
408 * of pages that use template X" and an instance of that task as a "root job".
409 * However, what actually goes into the queue are potentially many refreshLinks2 jobs.
410 * Since these jobs include things like page ID ranges and DB master positions, and morph
411 * into smaller refreshLinks2 jobs recursively, simple duplicate detection (like job_sha1)
412 * for individual jobs being identical is not useful.
413 *
414 * In the case of "refreshLinks", if these jobs are still in the queue when the template
415 * is edited again, we want all of these old refreshLinks jobs for that template to become
416 * no-ops. This can greatly reduce server load, since refreshLinks jobs involves parsing.
417 * Essentially, the new batch of jobs belong to a new "root job" and the older ones to a
418 * previous "root job" for the same task of "update links of pages that use template X".
419 *
420 * This does nothing for certain queue classes.
421 *
422 * @param $job Job
423 * @return bool
424 * @throws JobQueueError
425 */
426 final public function deduplicateRootJob( Job $job ) {
427 if ( $job->getType() !== $this->type ) {
428 throw new MWException( "Got '{$job->getType()}' job; expected '{$this->type}'." );
429 }
430 wfProfileIn( __METHOD__ );
431 $ok = $this->doDeduplicateRootJob( $job );
432 wfProfileOut( __METHOD__ );
433 return $ok;
434 }
435
436 /**
437 * @see JobQueue::deduplicateRootJob()
438 * @param $job Job
439 * @return bool
440 */
441 protected function doDeduplicateRootJob( Job $job ) {
442 global $wgMemc;
443
444 if ( !$job->hasRootJobParams() ) {
445 throw new MWException( "Cannot register root job; missing parameters." );
446 }
447 $params = $job->getRootJobParams();
448
449 $key = $this->getRootJobCacheKey( $params['rootJobSignature'] );
450 // Callers should call batchInsert() and then this function so that if the insert
451 // fails, the de-duplication registration will be aborted. Since the insert is
452 // deferred till "transaction idle", do the same here, so that the ordering is
453 // maintained. Having only the de-duplication registration succeed would cause
454 // jobs to become no-ops without any actual jobs that made them redundant.
455 $timestamp = $wgMemc->get( $key ); // current last timestamp of this job
456 if ( $timestamp && $timestamp >= $params['rootJobTimestamp'] ) {
457 return true; // a newer version of this root job was enqueued
458 }
459
460 // Update the timestamp of the last root job started at the location...
461 return $wgMemc->set( $key, $params['rootJobTimestamp'], JobQueueDB::ROOTJOB_TTL );
462 }
463
464 /**
465 * Check if the "root" job of a given job has been superseded by a newer one
466 *
467 * @param $job Job
468 * @return bool
469 * @throws JobQueueError
470 */
471 final protected function isRootJobOldDuplicate( Job $job ) {
472 if ( $job->getType() !== $this->type ) {
473 throw new MWException( "Got '{$job->getType()}' job; expected '{$this->type}'." );
474 }
475 wfProfileIn( __METHOD__ );
476 $isDuplicate = $this->doIsRootJobOldDuplicate( $job );
477 wfProfileOut( __METHOD__ );
478 return $isDuplicate;
479 }
480
481 /**
482 * @see JobQueue::isRootJobOldDuplicate()
483 * @param Job $job
484 * @return bool
485 */
486 protected function doIsRootJobOldDuplicate( Job $job ) {
487 global $wgMemc;
488
489 if ( !$job->hasRootJobParams() ) {
490 return false; // job has no de-deplication info
491 }
492 $params = $job->getRootJobParams();
493
494 // Get the last time this root job was enqueued
495 $timestamp = $wgMemc->get( $this->getRootJobCacheKey( $params['rootJobSignature'] ) );
496
497 // Check if a new root job was started at the location after this one's...
498 return ( $timestamp && $timestamp > $params['rootJobTimestamp'] );
499 }
500
501 /**
502 * @param string $signature Hash identifier of the root job
503 * @return string
504 */
505 protected function getRootJobCacheKey( $signature ) {
506 list( $db, $prefix ) = wfSplitWikiID( $this->wiki );
507 return wfForeignMemcKey( $db, $prefix, 'jobqueue', $this->type, 'rootjob', $signature );
508 }
509
510 /**
511 * Deleted all unclaimed and delayed jobs from the queue
512 *
513 * @return bool Success
514 * @throws JobQueueError
515 * @since 1.22
516 */
517 final public function delete() {
518 wfProfileIn( __METHOD__ );
519 $res = $this->doDelete();
520 wfProfileOut( __METHOD__ );
521 return $res;
522 }
523
524 /**
525 * @see JobQueue::delete()
526 * @return bool Success
527 */
528 protected function doDelete() {
529 throw new MWException( "This method is not implemented." );
530 }
531
532 /**
533 * Wait for any slaves or backup servers to catch up.
534 *
535 * This does nothing for certain queue classes.
536 *
537 * @return void
538 * @throws JobQueueError
539 */
540 final public function waitForBackups() {
541 wfProfileIn( __METHOD__ );
542 $this->doWaitForBackups();
543 wfProfileOut( __METHOD__ );
544 }
545
546 /**
547 * @see JobQueue::waitForBackups()
548 * @return void
549 */
550 protected function doWaitForBackups() {}
551
552 /**
553 * Return a map of task names to task definition maps.
554 * A "task" is a fast periodic queue maintenance action.
555 * Mutually exclusive tasks must implement their own locking in the callback.
556 *
557 * Each task value is an associative array with:
558 * - name : the name of the task
559 * - callback : a PHP callable that performs the task
560 * - period : the period in seconds corresponding to the task frequency
561 *
562 * @return Array
563 */
564 final public function getPeriodicTasks() {
565 $tasks = $this->doGetPeriodicTasks();
566 foreach ( $tasks as $name => &$def ) {
567 $def['name'] = $name;
568 }
569 return $tasks;
570 }
571
572 /**
573 * @see JobQueue::getPeriodicTasks()
574 * @return Array
575 */
576 protected function doGetPeriodicTasks() {
577 return array();
578 }
579
580 /**
581 * Clear any process and persistent caches
582 *
583 * @return void
584 */
585 final public function flushCaches() {
586 wfProfileIn( __METHOD__ );
587 $this->doFlushCaches();
588 wfProfileOut( __METHOD__ );
589 }
590
591 /**
592 * @see JobQueue::flushCaches()
593 * @return void
594 */
595 protected function doFlushCaches() {}
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( array() ); // not implemented
617 }
618
619 /**
620 * Call wfIncrStats() for the queue overall and for the queue type
621 *
622 * @param string $key Event type
623 * @param string $type Job type
624 * @param integer $delta
625 * @since 1.22
626 */
627 public static function incrStats( $key, $type, $delta = 1 ) {
628 wfIncrStats( $key, $delta );
629 wfIncrStats( "{$key}-{$type}", $delta );
630 }
631
632 /**
633 * Namespace the queue with a key to isolate it for testing
634 *
635 * @param $key string
636 * @return void
637 * @throws MWException
638 */
639 public function setTestingPrefix( $key ) {
640 throw new MWException( "Queue namespacing not supported for this queue type." );
641 }
642 }
643
644 /**
645 * @ingroup JobQueue
646 * @since 1.22
647 */
648 class JobQueueError extends MWException {}
649 class JobQueueConnectionError extends JobQueueError {}