Merge "Remove several ancient skins"
[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 ( !MWInit::classExists( $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)
125 */
126 final public function getOrder() {
127 return $this->order;
128 }
129
130 /**
131 * @return Array Subset of (random, timestamp, fifo)
132 */
133 abstract protected function supportedOrders();
134
135 /**
136 * @return string One of (random, timestamp, fifo)
137 */
138 abstract protected function optimalOrder();
139
140 /**
141 * @return boolean Whether delayed jobs are supported
142 */
143 protected function supportsDelayedJobs() {
144 return false; // not implemented
145 }
146
147 /**
148 * Quickly check if the queue has no available (unacquired, non-delayed) jobs.
149 * Queue classes should use caching if they are any slower without memcached.
150 *
151 * If caching is used, this might return false when there are actually no jobs.
152 * If pop() is called and returns false then it should correct the cache. Also,
153 * calling flushCaches() first prevents this. However, this affect is typically
154 * not distinguishable from the race condition between isEmpty() and pop().
155 *
156 * @return bool
157 * @throws MWException
158 */
159 final public function isEmpty() {
160 wfProfileIn( __METHOD__ );
161 $res = $this->doIsEmpty();
162 wfProfileOut( __METHOD__ );
163 return $res;
164 }
165
166 /**
167 * @see JobQueue::isEmpty()
168 * @return bool
169 */
170 abstract protected function doIsEmpty();
171
172 /**
173 * Get the number of available (unacquired, non-delayed) jobs in the queue.
174 * Queue classes should use caching if they are any slower without memcached.
175 *
176 * If caching is used, this number might be out of date for a minute.
177 *
178 * @return integer
179 * @throws MWException
180 */
181 final public function getSize() {
182 wfProfileIn( __METHOD__ );
183 $res = $this->doGetSize();
184 wfProfileOut( __METHOD__ );
185 return $res;
186 }
187
188 /**
189 * @see JobQueue::getSize()
190 * @return integer
191 */
192 abstract protected function doGetSize();
193
194 /**
195 * Get the number of acquired jobs (these are temporarily out of the queue).
196 * Queue classes should use caching if they are any slower without memcached.
197 *
198 * If caching is used, this number might be out of date for a minute.
199 *
200 * @return integer
201 * @throws MWException
202 */
203 final public function getAcquiredCount() {
204 wfProfileIn( __METHOD__ );
205 $res = $this->doGetAcquiredCount();
206 wfProfileOut( __METHOD__ );
207 return $res;
208 }
209
210 /**
211 * @see JobQueue::getAcquiredCount()
212 * @return integer
213 */
214 abstract protected function doGetAcquiredCount();
215
216 /**
217 * Get the number of delayed jobs (these are temporarily out of the queue).
218 * Queue classes should use caching if they are any slower without memcached.
219 *
220 * If caching is used, this number might be out of date for a minute.
221 *
222 * @return integer
223 * @throws MWException
224 * @since 1.22
225 */
226 final public function getDelayedCount() {
227 wfProfileIn( __METHOD__ );
228 $res = $this->doGetDelayedCount();
229 wfProfileOut( __METHOD__ );
230 return $res;
231 }
232
233 /**
234 * @see JobQueue::getDelayedCount()
235 * @return integer
236 */
237 protected function doGetDelayedCount() {
238 return 0; // not implemented
239 }
240
241 /**
242 * Get the number of acquired jobs that can no longer be attempted.
243 * Queue classes should use caching if they are any slower without memcached.
244 *
245 * If caching is used, this number might be out of date for a minute.
246 *
247 * @return integer
248 * @throws MWException
249 */
250 final public function getAbandonedCount() {
251 wfProfileIn( __METHOD__ );
252 $res = $this->doGetAbandonedCount();
253 wfProfileOut( __METHOD__ );
254 return $res;
255 }
256
257 /**
258 * @see JobQueue::getAbandonedCount()
259 * @return integer
260 */
261 protected function doGetAbandonedCount() {
262 return 0; // not implemented
263 }
264
265 /**
266 * Push a single jobs into the queue.
267 * This does not require $wgJobClasses to be set for the given job type.
268 * Outside callers should use JobQueueGroup::push() instead of this function.
269 *
270 * @param $jobs Job|Array
271 * @param $flags integer Bitfield (supports JobQueue::QOS_ATOMIC)
272 * @return bool Returns false on failure
273 * @throws MWException
274 */
275 final public function push( $jobs, $flags = 0 ) {
276 return $this->batchPush( is_array( $jobs ) ? $jobs : array( $jobs ), $flags );
277 }
278
279 /**
280 * Push a batch of 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 array $jobs List of Jobs
285 * @param $flags integer Bitfield (supports JobQueue::QOS_ATOMIC)
286 * @return bool Returns false on failure
287 * @throws MWException
288 */
289 final public function batchPush( array $jobs, $flags = 0 ) {
290 if ( !count( $jobs ) ) {
291 return true; // nothing to do
292 }
293
294 foreach ( $jobs as $job ) {
295 if ( $job->getType() !== $this->type ) {
296 throw new MWException(
297 "Got '{$job->getType()}' job; expected a '{$this->type}' job." );
298 } elseif ( $job->getReleaseTimestamp() && !$this->checkDelay ) {
299 throw new MWException(
300 "Got delayed '{$job->getType()}' job; delays are not supported." );
301 }
302 }
303
304 wfProfileIn( __METHOD__ );
305 $ok = $this->doBatchPush( $jobs, $flags );
306 wfProfileOut( __METHOD__ );
307 return $ok;
308 }
309
310 /**
311 * @see JobQueue::batchPush()
312 * @return bool
313 */
314 abstract protected function doBatchPush( array $jobs, $flags );
315
316 /**
317 * Pop a job off of the queue.
318 * This requires $wgJobClasses to be set for the given job type.
319 * Outside callers should use JobQueueGroup::pop() instead of this function.
320 *
321 * @return Job|bool Returns false if there are no jobs
322 * @throws MWException
323 */
324 final public function pop() {
325 global $wgJobClasses;
326
327 if ( $this->wiki !== wfWikiID() ) {
328 throw new MWException( "Cannot pop '{$this->type}' job off foreign wiki queue." );
329 } elseif ( !isset( $wgJobClasses[$this->type] ) ) {
330 // Do not pop jobs if there is no class for the queue type
331 throw new MWException( "Unrecognized job type '{$this->type}'." );
332 }
333
334 wfProfileIn( __METHOD__ );
335 $job = $this->doPop();
336 wfProfileOut( __METHOD__ );
337
338 // Flag this job as an old duplicate based on its "root" job...
339 try {
340 if ( $job && $this->isRootJobOldDuplicate( $job ) ) {
341 wfIncrStats( 'job-pop-duplicate' );
342 $job = DuplicateJob::newFromJob( $job ); // convert to a no-op
343 }
344 } catch ( MWException $e ) {} // don't lose jobs over this
345
346 return $job;
347 }
348
349 /**
350 * @see JobQueue::pop()
351 * @return Job
352 */
353 abstract protected function doPop();
354
355 /**
356 * Acknowledge that a job was completed.
357 *
358 * This does nothing for certain queue classes or if "claimTTL" is not set.
359 * Outside callers should use JobQueueGroup::ack() instead of this function.
360 *
361 * @param $job Job
362 * @return bool
363 * @throws MWException
364 */
365 final public function ack( Job $job ) {
366 if ( $job->getType() !== $this->type ) {
367 throw new MWException( "Got '{$job->getType()}' job; expected '{$this->type}'." );
368 }
369 wfProfileIn( __METHOD__ );
370 $ok = $this->doAck( $job );
371 wfProfileOut( __METHOD__ );
372 return $ok;
373 }
374
375 /**
376 * @see JobQueue::ack()
377 * @return bool
378 */
379 abstract protected function doAck( Job $job );
380
381 /**
382 * Register the "root job" of a given job into the queue for de-duplication.
383 * This should only be called right *after* all the new jobs have been inserted.
384 * This is used to turn older, duplicate, job entries into no-ops. The root job
385 * information will remain in the registry until it simply falls out of cache.
386 *
387 * This requires that $job has two special fields in the "params" array:
388 * - rootJobSignature : hash (e.g. SHA1) that identifies the task
389 * - rootJobTimestamp : TS_MW timestamp of this instance of the task
390 *
391 * A "root job" is a conceptual job that consist of potentially many smaller jobs
392 * that are actually inserted into the queue. For example, "refreshLinks" jobs are
393 * spawned when a template is edited. One can think of the task as "update links
394 * of pages that use template X" and an instance of that task as a "root job".
395 * However, what actually goes into the queue are potentially many refreshLinks2 jobs.
396 * Since these jobs include things like page ID ranges and DB master positions, and morph
397 * into smaller refreshLinks2 jobs recursively, simple duplicate detection (like job_sha1)
398 * for individual jobs being identical is not useful.
399 *
400 * In the case of "refreshLinks", if these jobs are still in the queue when the template
401 * is edited again, we want all of these old refreshLinks jobs for that template to become
402 * no-ops. This can greatly reduce server load, since refreshLinks jobs involves parsing.
403 * Essentially, the new batch of jobs belong to a new "root job" and the older ones to a
404 * previous "root job" for the same task of "update links of pages that use template X".
405 *
406 * This does nothing for certain queue classes.
407 *
408 * @param $job Job
409 * @return bool
410 * @throws MWException
411 */
412 final public function deduplicateRootJob( Job $job ) {
413 if ( $job->getType() !== $this->type ) {
414 throw new MWException( "Got '{$job->getType()}' job; expected '{$this->type}'." );
415 }
416 wfProfileIn( __METHOD__ );
417 $ok = $this->doDeduplicateRootJob( $job );
418 wfProfileOut( __METHOD__ );
419 return $ok;
420 }
421
422 /**
423 * @see JobQueue::deduplicateRootJob()
424 * @param $job Job
425 * @return bool
426 */
427 protected function doDeduplicateRootJob( Job $job ) {
428 global $wgMemc;
429
430 $params = $job->getParams();
431 if ( !isset( $params['rootJobSignature'] ) ) {
432 throw new MWException( "Cannot register root job; missing 'rootJobSignature'." );
433 } elseif ( !isset( $params['rootJobTimestamp'] ) ) {
434 throw new MWException( "Cannot register root job; missing 'rootJobTimestamp'." );
435 }
436 $key = $this->getRootJobCacheKey( $params['rootJobSignature'] );
437 // Callers should call batchInsert() and then this function so that if the insert
438 // fails, the de-duplication registration will be aborted. Since the insert is
439 // deferred till "transaction idle", do the same here, so that the ordering is
440 // maintained. Having only the de-duplication registration succeed would cause
441 // jobs to become no-ops without any actual jobs that made them redundant.
442 $timestamp = $wgMemc->get( $key ); // current last timestamp of this job
443 if ( $timestamp && $timestamp >= $params['rootJobTimestamp'] ) {
444 return true; // a newer version of this root job was enqueued
445 }
446
447 // Update the timestamp of the last root job started at the location...
448 return $wgMemc->set( $key, $params['rootJobTimestamp'], JobQueueDB::ROOTJOB_TTL );
449 }
450
451 /**
452 * Check if the "root" job of a given job has been superseded by a newer one
453 *
454 * @param $job Job
455 * @return bool
456 * @throws MWException
457 */
458 final protected function isRootJobOldDuplicate( Job $job ) {
459 if ( $job->getType() !== $this->type ) {
460 throw new MWException( "Got '{$job->getType()}' job; expected '{$this->type}'." );
461 }
462 wfProfileIn( __METHOD__ );
463 $isDuplicate = $this->doIsRootJobOldDuplicate( $job );
464 wfProfileOut( __METHOD__ );
465 return $isDuplicate;
466 }
467
468 /**
469 * @see JobQueue::isRootJobOldDuplicate()
470 * @param Job $job
471 * @return bool
472 */
473 protected function doIsRootJobOldDuplicate( Job $job ) {
474 global $wgMemc;
475
476 $params = $job->getParams();
477 if ( !isset( $params['rootJobSignature'] ) ) {
478 return false; // job has no de-deplication info
479 } elseif ( !isset( $params['rootJobTimestamp'] ) ) {
480 trigger_error( "Cannot check root job; missing 'rootJobTimestamp'." );
481 return false;
482 }
483
484 // Get the last time this root job was enqueued
485 $timestamp = $wgMemc->get( $this->getRootJobCacheKey( $params['rootJobSignature'] ) );
486
487 // Check if a new root job was started at the location after this one's...
488 return ( $timestamp && $timestamp > $params['rootJobTimestamp'] );
489 }
490
491 /**
492 * @param string $signature Hash identifier of the root job
493 * @return string
494 */
495 protected function getRootJobCacheKey( $signature ) {
496 list( $db, $prefix ) = wfSplitWikiID( $this->wiki );
497 return wfForeignMemcKey( $db, $prefix, 'jobqueue', $this->type, 'rootjob', $signature );
498 }
499
500 /**
501 * Wait for any slaves or backup servers to catch up.
502 *
503 * This does nothing for certain queue classes.
504 *
505 * @return void
506 * @throws MWException
507 */
508 final public function waitForBackups() {
509 wfProfileIn( __METHOD__ );
510 $this->doWaitForBackups();
511 wfProfileOut( __METHOD__ );
512 }
513
514 /**
515 * @see JobQueue::waitForBackups()
516 * @return void
517 */
518 protected function doWaitForBackups() {}
519
520 /**
521 * Return a map of task names to task definition maps.
522 * A "task" is a fast periodic queue maintenance action.
523 * Mutually exclusive tasks must implement their own locking in the callback.
524 *
525 * Each task value is an associative array with:
526 * - name : the name of the task
527 * - callback : a PHP callable that performs the task
528 * - period : the period in seconds corresponding to the task frequency
529 *
530 * @return Array
531 */
532 final public function getPeriodicTasks() {
533 $tasks = $this->doGetPeriodicTasks();
534 foreach ( $tasks as $name => &$def ) {
535 $def['name'] = $name;
536 }
537 return $tasks;
538 }
539
540 /**
541 * @see JobQueue::getPeriodicTasks()
542 * @return Array
543 */
544 protected function doGetPeriodicTasks() {
545 return array();
546 }
547
548 /**
549 * Clear any process and persistent caches
550 *
551 * @return void
552 */
553 final public function flushCaches() {
554 wfProfileIn( __METHOD__ );
555 $this->doFlushCaches();
556 wfProfileOut( __METHOD__ );
557 }
558
559 /**
560 * @see JobQueue::flushCaches()
561 * @return void
562 */
563 protected function doFlushCaches() {}
564
565 /**
566 * Get an iterator to traverse over all available jobs in this queue.
567 * This does not include jobs that are currently acquired or delayed.
568 * This should only be called on a queue that is no longer being popped.
569 *
570 * @return Iterator|Traversable|Array
571 * @throws MWException
572 */
573 abstract public function getAllQueuedJobs();
574
575 /**
576 * Get an iterator to traverse over all delayed jobs in this queue.
577 * This should only be called on a queue that is no longer being popped.
578 *
579 * @return Iterator|Traversable|Array
580 * @throws MWException
581 * @since 1.22
582 */
583 public function getAllDelayedJobs() {
584 return array(); // not implemented
585 }
586
587 /**
588 * Namespace the queue with a key to isolate it for testing
589 *
590 * @param $key string
591 * @return void
592 * @throws MWException
593 */
594 public function setTestingPrefix( $key ) {
595 throw new MWException( "Queue namespacing not supported for this queue type." );
596 }
597 }