Merge "Don't check namespace in SpecialWantedtemplates"
[lhc/web/wiklou.git] / includes / jobqueue / Job.php
1 <?php
2 /**
3 * Job queue task 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
24 /**
25 * Class to both describe a background job and handle jobs.
26 * The queue aspects of this class are now deprecated.
27 * Using the class to push jobs onto queues is deprecated (use JobSpecification).
28 *
29 * @ingroup JobQueue
30 */
31 abstract class Job implements IJobSpecification {
32 /** @var string */
33 public $command;
34
35 /** @var array Array of job parameters */
36 public $params;
37
38 /** @var array Additional queue metadata */
39 public $metadata = array();
40
41 /** @var Title */
42 protected $title;
43
44 /** @var bool Expensive jobs may set this to true */
45 protected $removeDuplicates;
46
47 /** @var string Text for error that occurred last */
48 protected $error;
49
50 /**
51 * Run the job
52 * @return bool Success
53 */
54 abstract public function run();
55
56 /**
57 * Create the appropriate object to handle a specific job
58 *
59 * @param string $command Job command
60 * @param Title $title Associated title
61 * @param array $params Job parameters
62 * @throws MWException
63 * @return Job
64 */
65 public static function factory( $command, Title $title, $params = array() ) {
66 global $wgJobClasses;
67 if ( isset( $wgJobClasses[$command] ) ) {
68 $class = $wgJobClasses[$command];
69
70 return new $class( $title, $params );
71 }
72 throw new MWException( "Invalid job command `{$command}`" );
73 }
74
75 /**
76 * @param string $command
77 * @param Title $title
78 * @param array|bool $params Can not be === true
79 */
80 public function __construct( $command, $title, $params = false ) {
81 $this->command = $command;
82 $this->title = $title;
83 $this->params = is_array( $params ) ? $params : array(); // sanity
84
85 // expensive jobs may set this to true
86 $this->removeDuplicates = false;
87 }
88
89 /**
90 * Batch-insert a group of jobs into the queue.
91 * This will be wrapped in a transaction with a forced commit.
92 *
93 * This may add duplicate at insert time, but they will be
94 * removed later on, when the first one is popped.
95 *
96 * @param Job[] $jobs Array of Job objects
97 * @return bool
98 * @deprecated since 1.21
99 */
100 public static function batchInsert( $jobs ) {
101 wfDeprecated( __METHOD__, '1.21' );
102 JobQueueGroup::singleton()->push( $jobs );
103 return true;
104 }
105
106 /**
107 * @return string
108 */
109 public function getType() {
110 return $this->command;
111 }
112
113 /**
114 * @return Title
115 */
116 public function getTitle() {
117 return $this->title;
118 }
119
120 /**
121 * @return array
122 */
123 public function getParams() {
124 return $this->params;
125 }
126
127 /**
128 * @return int|null UNIX timestamp to delay running this job until, otherwise null
129 * @since 1.22
130 */
131 public function getReleaseTimestamp() {
132 return isset( $this->params['jobReleaseTimestamp'] )
133 ? wfTimestampOrNull( TS_UNIX, $this->params['jobReleaseTimestamp'] )
134 : null;
135 }
136
137 /**
138 * @return int|null UNIX timestamp of when the job was queued, or null
139 * @since 1.26
140 */
141 public function getQueuedTimestamp() {
142 return isset( $this->metadata['timestamp'] )
143 ? wfTimestampOrNull( TS_UNIX, $this->metadata['timestamp'] )
144 : null;
145 }
146
147 /**
148 * @return int|null UNIX timestamp of when the job was runnable, or null
149 * @since 1.26
150 */
151 public function getReadyTimestamp() {
152 return $this->getReleaseTimestamp() ?: $this->getQueuedTimestamp();
153 }
154
155 /**
156 * Whether the queue should reject insertion of this job if a duplicate exists
157 *
158 * This can be used to avoid duplicated effort or combined with delayed jobs to
159 * coalesce updates into larger batches. Claimed jobs are never treated as
160 * duplicates of new jobs, and some queues may allow a few duplicates due to
161 * network partitions and fail-over. Thus, additional locking is needed to
162 * enforce mutual exclusion if this is really needed.
163 *
164 * @return bool
165 */
166 public function ignoreDuplicates() {
167 return $this->removeDuplicates;
168 }
169
170 /**
171 * @return bool Whether this job can be retried on failure by job runners
172 * @since 1.21
173 */
174 public function allowRetries() {
175 return true;
176 }
177
178 /**
179 * @return int Number of actually "work items" handled in this job
180 * @see $wgJobBackoffThrottling
181 * @since 1.23
182 */
183 public function workItemCount() {
184 return 1;
185 }
186
187 /**
188 * Subclasses may need to override this to make duplication detection work.
189 * The resulting map conveys everything that makes the job unique. This is
190 * only checked if ignoreDuplicates() returns true, meaning that duplicate
191 * jobs are supposed to be ignored.
192 *
193 * @return array Map of key/values
194 * @since 1.21
195 */
196 public function getDeduplicationInfo() {
197 $info = array(
198 'type' => $this->getType(),
199 'namespace' => $this->getTitle()->getNamespace(),
200 'title' => $this->getTitle()->getDBkey(),
201 'params' => $this->getParams()
202 );
203 if ( is_array( $info['params'] ) ) {
204 // Identical jobs with different "root" jobs should count as duplicates
205 unset( $info['params']['rootJobSignature'] );
206 unset( $info['params']['rootJobTimestamp'] );
207 // Likewise for jobs with different delay times
208 unset( $info['params']['jobReleaseTimestamp'] );
209 // Queues pack and hash this array, so normalize the order
210 ksort( $info['params'] );
211 }
212
213 return $info;
214 }
215
216 /**
217 * Get "root job" parameters for a task
218 *
219 * This is used to no-op redundant jobs, including child jobs of jobs,
220 * as long as the children inherit the root job parameters. When a job
221 * with root job parameters and "rootJobIsSelf" set is pushed, the
222 * deduplicateRootJob() method is automatically called on it. If the
223 * root job is only virtual and not actually pushed (e.g. the sub-jobs
224 * are inserted directly), then call deduplicateRootJob() directly.
225 *
226 * @see JobQueue::deduplicateRootJob()
227 *
228 * @param string $key A key that identifies the task
229 * @return array Map of:
230 * - rootJobIsSelf : true
231 * - rootJobSignature : hash (e.g. SHA1) that identifies the task
232 * - rootJobTimestamp : TS_MW timestamp of this instance of the task
233 * @since 1.21
234 */
235 public static function newRootJobParams( $key ) {
236 return array(
237 'rootJobIsSelf' => true,
238 'rootJobSignature' => sha1( $key ),
239 'rootJobTimestamp' => wfTimestampNow()
240 );
241 }
242
243 /**
244 * @see JobQueue::deduplicateRootJob()
245 * @return array
246 * @since 1.21
247 */
248 public function getRootJobParams() {
249 return array(
250 'rootJobSignature' => isset( $this->params['rootJobSignature'] )
251 ? $this->params['rootJobSignature']
252 : null,
253 'rootJobTimestamp' => isset( $this->params['rootJobTimestamp'] )
254 ? $this->params['rootJobTimestamp']
255 : null
256 );
257 }
258
259 /**
260 * @see JobQueue::deduplicateRootJob()
261 * @return bool
262 * @since 1.22
263 */
264 public function hasRootJobParams() {
265 return isset( $this->params['rootJobSignature'] )
266 && isset( $this->params['rootJobTimestamp'] );
267 }
268
269 /**
270 * @see JobQueue::deduplicateRootJob()
271 * @return bool Whether this is job is a root job
272 */
273 public function isRootJob() {
274 return $this->hasRootJobParams() && !empty( $this->params['rootJobIsSelf'] );
275 }
276
277 /**
278 * Insert a single job into the queue.
279 * @return bool True on success
280 * @deprecated since 1.21
281 */
282 public function insert() {
283 JobQueueGroup::singleton()->push( $this );
284 return true;
285 }
286
287 /**
288 * @return string
289 */
290 public function toString() {
291 $truncFunc = function ( $value ) {
292 $value = (string)$value;
293 if ( mb_strlen( $value ) > 1024 ) {
294 $value = "string(" . mb_strlen( $value ) . ")";
295 }
296 return $value;
297 };
298
299 $paramString = '';
300 if ( $this->params ) {
301 foreach ( $this->params as $key => $value ) {
302 if ( $paramString != '' ) {
303 $paramString .= ' ';
304 }
305 if ( is_array( $value ) ) {
306 $filteredValue = array();
307 foreach ( $value as $k => $v ) {
308 if ( is_scalar( $v ) ) {
309 $filteredValue[$k] = $truncFunc( $v );
310 } else {
311 $filteredValue = null;
312 break;
313 }
314 }
315 if ( $filteredValue && count( $filteredValue ) < 10 ) {
316 $value = FormatJson::encode( $filteredValue );
317 } else {
318 $value = "array(" . count( $value ) . ")";
319 }
320 } elseif ( is_object( $value ) && !method_exists( $value, '__toString' ) ) {
321 $value = "object(" . get_class( $value ) . ")";
322 }
323
324 $paramString .= "$key={$truncFunc( $value )}";
325 }
326 }
327
328 $metaString = '';
329 foreach ( $this->metadata as $key => $value ) {
330 if ( is_scalar( $value ) && mb_strlen( $value ) < 1024 ) {
331 $metaString .= ( $metaString ? ",$key=$value" : "$key=$value" );
332 }
333 }
334
335 $s = $this->command;
336 if ( is_object( $this->title ) ) {
337 $s .= " {$this->title->getPrefixedDBkey()}";
338 }
339 if ( $paramString != '' ) {
340 $s .= " $paramString";
341 }
342 if ( $metaString != '' ) {
343 $s .= " ($metaString)";
344 }
345
346 return $s;
347 }
348
349 protected function setLastError( $error ) {
350 $this->error = $error;
351 }
352
353 public function getLastError() {
354 return $this->error;
355 }
356 }