Improve the shell cgroup feature
[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
37 const QoS_Atomic = 1; // integer; "all-or-nothing" job insertions
38
39 const MAX_ATTEMPTS = 3; // integer; number of times to try a job
40
41 /**
42 * @param $params array
43 */
44 protected function __construct( array $params ) {
45 $this->wiki = $params['wiki'];
46 $this->type = $params['type'];
47 $this->order = isset( $params['order'] ) ? $params['order'] : 'random';
48 $this->claimTTL = isset( $params['claimTTL'] ) ? $params['claimTTL'] : 0;
49 }
50
51 /**
52 * Get a job queue object of the specified type.
53 * $params includes:
54 * - class : What job class to use (determines job type)
55 * - wiki : wiki ID of the wiki the jobs are for (defaults to current wiki)
56 * - type : The name of the job types this queue handles
57 * - order : Order that pop() selects jobs, one of "fifo", "timestamp" or "random".
58 * If "fifo" is used, the queue will effectively be FIFO. Note that
59 * job completion will not appear to be exactly FIFO if there are multiple
60 * job runners since jobs can take different times to finish once popped.
61 * If "timestamp" is used, the queue will at least be loosely ordered
62 * by timestamp, allowing for some jobs to be popped off out of order.
63 * If "random" is used, pop() will pick jobs in random order. This might be
64 * useful for improving concurrency depending on the queue storage medium.
65 * - claimTTL : If supported, the queue will recycle jobs that have been popped
66 * but not acknowledged as completed after this many seconds. Recycling
67 * of jobs simple means re-inserting them into the queue. Jobs can be
68 * attempted up to three times before being discarded.
69 *
70 * Queue classes should throw an exception if they do not support the options given.
71 *
72 * @param $params array
73 * @return JobQueue
74 * @throws MWException
75 */
76 final public static function factory( array $params ) {
77 $class = $params['class'];
78 if ( !MWInit::classExists( $class ) ) {
79 throw new MWException( "Invalid job queue class '$class'." );
80 }
81 $obj = new $class( $params );
82 if ( !( $obj instanceof self ) ) {
83 throw new MWException( "Class '$class' is not a " . __CLASS__ . " class." );
84 }
85 return $obj;
86 }
87
88 /**
89 * @return string Wiki ID
90 */
91 final public function getWiki() {
92 return $this->wiki;
93 }
94
95 /**
96 * @return string Job type that this queue handles
97 */
98 final public function getType() {
99 return $this->type;
100 }
101
102 /**
103 * Quickly check if the queue is empty (has no available jobs).
104 * Queue classes should use caching if they are any slower without memcached.
105 *
106 * @return bool
107 * @throws MWException
108 */
109 final public function isEmpty() {
110 wfProfileIn( __METHOD__ );
111 $res = $this->doIsEmpty();
112 wfProfileOut( __METHOD__ );
113 return $res;
114 }
115
116 /**
117 * @see JobQueue::isEmpty()
118 * @return bool
119 */
120 abstract protected function doIsEmpty();
121
122 /**
123 * Get the number of available jobs in the queue.
124 * Queue classes should use caching if they are any slower without memcached.
125 *
126 * @return integer
127 * @throws MWException
128 */
129 final public function getSize() {
130 wfProfileIn( __METHOD__ );
131 $res = $this->doGetSize();
132 wfProfileOut( __METHOD__ );
133 return $res;
134 }
135
136 /**
137 * @see JobQueue::getSize()
138 * @return integer
139 */
140 abstract protected function doGetSize();
141
142 /**
143 * Get the number of acquired jobs (these are temporarily out of the queue).
144 * Queue classes should use caching if they are any slower without memcached.
145 *
146 * @return integer
147 * @throws MWException
148 */
149 final public function getAcquiredCount() {
150 wfProfileIn( __METHOD__ );
151 $res = $this->doGetAcquiredCount();
152 wfProfileOut( __METHOD__ );
153 return $res;
154 }
155
156 /**
157 * @see JobQueue::getAcquiredCount()
158 * @return integer
159 */
160 abstract protected function doGetAcquiredCount();
161
162 /**
163 * Push a single jobs into the queue.
164 * This does not require $wgJobClasses to be set for the given job type.
165 *
166 * @param $jobs Job|Array
167 * @param $flags integer Bitfield (supports JobQueue::QoS_Atomic)
168 * @return bool Returns false on failure
169 * @throws MWException
170 */
171 final public function push( $jobs, $flags = 0 ) {
172 $jobs = is_array( $jobs ) ? $jobs : array( $jobs );
173
174 return $this->batchPush( $jobs, $flags );
175 }
176
177 /**
178 * Push a batch of jobs into the queue.
179 * This does not require $wgJobClasses to be set for the given job type.
180 *
181 * @param $jobs array List of Jobs
182 * @param $flags integer Bitfield (supports JobQueue::QoS_Atomic)
183 * @return bool Returns false on failure
184 * @throws MWException
185 */
186 final public function batchPush( array $jobs, $flags = 0 ) {
187 foreach ( $jobs as $job ) {
188 if ( $job->getType() !== $this->type ) {
189 throw new MWException( "Got '{$job->getType()}' job; expected '{$this->type}'." );
190 }
191 }
192 wfProfileIn( __METHOD__ );
193 $ok = $this->doBatchPush( $jobs, $flags );
194 wfProfileOut( __METHOD__ );
195 return $ok;
196 }
197
198 /**
199 * @see JobQueue::batchPush()
200 * @return bool
201 */
202 abstract protected function doBatchPush( array $jobs, $flags );
203
204 /**
205 * Pop a job off of the queue.
206 * This requires $wgJobClasses to be set for the given job type.
207 *
208 * @return Job|bool Returns false on failure
209 * @throws MWException
210 */
211 final public function pop() {
212 global $wgJobClasses;
213
214 if ( $this->wiki !== wfWikiID() ) {
215 throw new MWException( "Cannot pop '{$this->type}' job off foreign wiki queue." );
216 } elseif ( !isset( $wgJobClasses[$this->type] ) ) {
217 // Do not pop jobs if there is no class for the queue type
218 throw new MWException( "Unrecognized job type '{$this->type}'." );
219 }
220
221 wfProfileIn( __METHOD__ );
222 $job = $this->doPop();
223 wfProfileOut( __METHOD__ );
224 return $job;
225 }
226
227 /**
228 * @see JobQueue::pop()
229 * @return Job
230 */
231 abstract protected function doPop();
232
233 /**
234 * Acknowledge that a job was completed.
235 *
236 * This does nothing for certain queue classes or if "claimTTL" is not set.
237 *
238 * @param $job Job
239 * @return bool
240 * @throws MWException
241 */
242 final public function ack( Job $job ) {
243 if ( $job->getType() !== $this->type ) {
244 throw new MWException( "Got '{$job->getType()}' job; expected '{$this->type}'." );
245 }
246 wfProfileIn( __METHOD__ );
247 $ok = $this->doAck( $job );
248 wfProfileOut( __METHOD__ );
249 return $ok;
250 }
251
252 /**
253 * @see JobQueue::ack()
254 * @return bool
255 */
256 abstract protected function doAck( Job $job );
257
258 /**
259 * Register the "root job" of a given job into the queue for de-duplication.
260 * This should only be called right *after* all the new jobs have been inserted.
261 * This is used to turn older, duplicate, job entries into no-ops. The root job
262 * information will remain in the registry until it simply falls out of cache.
263 *
264 * This requires that $job has two special fields in the "params" array:
265 * - rootJobSignature : hash (e.g. SHA1) that identifies the task
266 * - rootJobTimestamp : TS_MW timestamp of this instance of the task
267 *
268 * A "root job" is a conceptual job that consist of potentially many smaller jobs
269 * that are actually inserted into the queue. For example, "refreshLinks" jobs are
270 * spawned when a template is edited. One can think of the task as "update links
271 * of pages that use template X" and an instance of that task as a "root job".
272 * However, what actually goes into the queue are potentially many refreshLinks2 jobs.
273 * Since these jobs include things like page ID ranges and DB master positions, and morph
274 * into smaller refreshLinks2 jobs recursively, simple duplicate detection (like job_sha1)
275 * for individual jobs being identical is not useful.
276 *
277 * In the case of "refreshLinks", if these jobs are still in the queue when the template
278 * is edited again, we want all of these old refreshLinks jobs for that template to become
279 * no-ops. This can greatly reduce server load, since refreshLinks jobs involves parsing.
280 * Essentially, the new batch of jobs belong to a new "root job" and the older ones to a
281 * previous "root job" for the same task of "update links of pages that use template X".
282 *
283 * This does nothing for certain queue classes.
284 *
285 * @param $job Job
286 * @return bool
287 * @throws MWException
288 */
289 final public function deduplicateRootJob( Job $job ) {
290 if ( $job->getType() !== $this->type ) {
291 throw new MWException( "Got '{$job->getType()}' job; expected '{$this->type}'." );
292 }
293 wfProfileIn( __METHOD__ );
294 $ok = $this->doDeduplicateRootJob( $job );
295 wfProfileOut( __METHOD__ );
296 return $ok;
297 }
298
299 /**
300 * @see JobQueue::deduplicateRootJob()
301 * @param $job Job
302 * @return bool
303 */
304 protected function doDeduplicateRootJob( Job $job ) {
305 return true;
306 }
307
308 /**
309 * Wait for any slaves or backup servers to catch up.
310 *
311 * This does nothing for certain queue classes.
312 *
313 * @return void
314 * @throws MWException
315 */
316 final public function waitForBackups() {
317 wfProfileIn( __METHOD__ );
318 $this->doWaitForBackups();
319 wfProfileOut( __METHOD__ );
320 }
321
322 /**
323 * @see JobQueue::waitForBackups()
324 * @return void
325 */
326 protected function doWaitForBackups() {}
327 }