Merge "wfProfileOut() for new return added in c6396 (c4e407c)"
[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 */
23
24 /**
25 * Class to both describe a background job and handle jobs.
26 *
27 * @ingroup JobQueue
28 */
29 abstract class Job {
30
31 /**
32 * @var Title
33 */
34 var $title;
35
36 var $command,
37 $params,
38 $id,
39 $removeDuplicates,
40 $error;
41
42 /*-------------------------------------------------------------------------
43 * Abstract functions
44 *------------------------------------------------------------------------*/
45
46 /**
47 * Run the job
48 * @return boolean success
49 */
50 abstract function run();
51
52 /*-------------------------------------------------------------------------
53 * Static functions
54 *------------------------------------------------------------------------*/
55
56 /**
57 * Pop a job of a certain type. This tries less hard than pop() to
58 * actually find a job; it may be adversely affected by concurrent job
59 * runners.
60 *
61 * @param $type string
62 *
63 * @return Job
64 */
65 static function pop_type( $type ) {
66 wfProfilein( __METHOD__ );
67
68 $dbw = wfGetDB( DB_MASTER );
69
70 $dbw->begin( __METHOD__ );
71
72 $row = $dbw->selectRow(
73 'job',
74 '*',
75 array( 'job_cmd' => $type ),
76 __METHOD__,
77 array( 'LIMIT' => 1, 'FOR UPDATE' )
78 );
79
80 if ( $row === false ) {
81 $dbw->commit( __METHOD__ );
82 wfProfileOut( __METHOD__ );
83 return false;
84 }
85
86 /* Ensure we "own" this row */
87 $dbw->delete( 'job', array( 'job_id' => $row->job_id ), __METHOD__ );
88 $affected = $dbw->affectedRows();
89 $dbw->commit( __METHOD__ );
90
91 if ( $affected == 0 ) {
92 wfProfileOut( __METHOD__ );
93 return false;
94 }
95
96 wfIncrStats( 'job-pop' );
97 $namespace = $row->job_namespace;
98 $dbkey = $row->job_title;
99 $title = Title::makeTitleSafe( $namespace, $dbkey );
100 $job = Job::factory( $row->job_cmd, $title, Job::extractBlob( $row->job_params ),
101 $row->job_id );
102
103 $job->removeDuplicates();
104
105 wfProfileOut( __METHOD__ );
106 return $job;
107 }
108
109 /**
110 * Pop a job off the front of the queue
111 *
112 * @param $offset Integer: Number of jobs to skip
113 * @return Job or false if there's no jobs
114 */
115 static function pop( $offset = 0 ) {
116 global $wgJobTypesExcludedFromDefaultQueue;
117 wfProfileIn( __METHOD__ );
118
119 $dbr = wfGetDB( DB_SLAVE );
120
121 /* Get a job from the slave, start with an offset,
122 scan full set afterwards, avoid hitting purged rows
123
124 NB: If random fetch previously was used, offset
125 will always be ahead of few entries
126 */
127 $conditions = array();
128 if ( count( $wgJobTypesExcludedFromDefaultQueue ) != 0 ) {
129 foreach ( $wgJobTypesExcludedFromDefaultQueue as $cmdType ) {
130 $conditions[] = "job_cmd != " . $dbr->addQuotes( $cmdType );
131 }
132 }
133 $offset = intval( $offset );
134 $options = array( 'ORDER BY' => 'job_id', 'USE INDEX' => 'PRIMARY' );
135
136 $row = $dbr->selectRow( 'job', '*',
137 array_merge( $conditions, array( "job_id >= $offset" ) ),
138 __METHOD__,
139 $options
140 );
141
142 // Refetching without offset is needed as some of job IDs could have had delayed commits
143 // and have lower IDs than jobs already executed, blame concurrency :)
144 //
145 if ( $row === false ) {
146 if ( $offset != 0 ) {
147 $row = $dbr->selectRow( 'job', '*', $conditions, __METHOD__, $options );
148 }
149
150 if ( $row === false ) {
151 wfProfileOut( __METHOD__ );
152 return false;
153 }
154 }
155
156 // Try to delete it from the master
157 $dbw = wfGetDB( DB_MASTER );
158 $dbw->delete( 'job', array( 'job_id' => $row->job_id ), __METHOD__ );
159 $affected = $dbw->affectedRows();
160 $dbw->commit( __METHOD__ );
161
162 if ( !$affected ) {
163 // Failed, someone else beat us to it
164 // Try getting a random row
165 $row = $dbw->selectRow( 'job', array( 'MIN(job_id) as minjob',
166 'MAX(job_id) as maxjob' ), '1=1', __METHOD__ );
167 if ( $row === false || is_null( $row->minjob ) || is_null( $row->maxjob ) ) {
168 // No jobs to get
169 wfProfileOut( __METHOD__ );
170 return false;
171 }
172 // Get the random row
173 $row = $dbw->selectRow( 'job', '*',
174 'job_id >= ' . mt_rand( $row->minjob, $row->maxjob ), __METHOD__ );
175 if ( $row === false ) {
176 // Random job gone before we got the chance to select it
177 // Give up
178 wfProfileOut( __METHOD__ );
179 return false;
180 }
181 // Delete the random row
182 $dbw->delete( 'job', array( 'job_id' => $row->job_id ), __METHOD__ );
183 $affected = $dbw->affectedRows();
184 $dbw->commit( __METHOD__ );
185
186 if ( !$affected ) {
187 // Random job gone before we exclusively deleted it
188 // Give up
189 wfProfileOut( __METHOD__ );
190 return false;
191 }
192 }
193
194 // If execution got to here, there's a row in $row that has been deleted from the database
195 // by this thread. Hence the concurrent pop was successful.
196 wfIncrStats( 'job-pop' );
197 $namespace = $row->job_namespace;
198 $dbkey = $row->job_title;
199 $title = Title::makeTitleSafe( $namespace, $dbkey );
200
201 if ( is_null( $title ) ) {
202 wfProfileOut( __METHOD__ );
203 return false;
204 }
205
206 $job = Job::factory( $row->job_cmd, $title, Job::extractBlob( $row->job_params ), $row->job_id );
207
208 // Remove any duplicates it may have later in the queue
209 $job->removeDuplicates();
210
211 wfProfileOut( __METHOD__ );
212 return $job;
213 }
214
215 /**
216 * Create the appropriate object to handle a specific job
217 *
218 * @param $command String: Job command
219 * @param $title Title: Associated title
220 * @param $params Array: Job parameters
221 * @param $id Int: Job identifier
222 * @return Job
223 */
224 static function factory( $command, Title $title, $params = false, $id = 0 ) {
225 global $wgJobClasses;
226 if( isset( $wgJobClasses[$command] ) ) {
227 $class = $wgJobClasses[$command];
228 return new $class( $title, $params, $id );
229 }
230 throw new MWException( "Invalid job command `{$command}`" );
231 }
232
233 /**
234 * @param $params
235 * @return string
236 */
237 static function makeBlob( $params ) {
238 if ( $params !== false ) {
239 return serialize( $params );
240 } else {
241 return '';
242 }
243 }
244
245 /**
246 * @param $blob
247 * @return bool|mixed
248 */
249 static function extractBlob( $blob ) {
250 if ( (string)$blob !== '' ) {
251 return unserialize( $blob );
252 } else {
253 return false;
254 }
255 }
256
257 /**
258 * Batch-insert a group of jobs into the queue.
259 * This will be wrapped in a transaction with a forced commit.
260 *
261 * This may add duplicate at insert time, but they will be
262 * removed later on, when the first one is popped.
263 *
264 * @param $jobs array of Job objects
265 */
266 static function batchInsert( $jobs ) {
267 if ( !count( $jobs ) ) {
268 return;
269 }
270 $dbw = wfGetDB( DB_MASTER );
271 $rows = array();
272
273 /**
274 * @var $job Job
275 */
276 foreach ( $jobs as $job ) {
277 $rows[] = $job->insertFields();
278 if ( count( $rows ) >= 50 ) {
279 # Do a small transaction to avoid slave lag
280 $dbw->begin( __METHOD__ );
281 $dbw->insert( 'job', $rows, __METHOD__, 'IGNORE' );
282 $dbw->commit( __METHOD__ );
283 $rows = array();
284 }
285 }
286 if ( $rows ) { // last chunk
287 $dbw->begin( __METHOD__ );
288 $dbw->insert( 'job', $rows, __METHOD__, 'IGNORE' );
289 $dbw->commit( __METHOD__ );
290 }
291 wfIncrStats( 'job-insert', count( $jobs ) );
292 }
293
294 /**
295 * Insert a group of jobs into the queue.
296 *
297 * Same as batchInsert() but does not commit and can thus
298 * be rolled-back as part of a larger transaction. However,
299 * large batches of jobs can cause slave lag.
300 *
301 * @param $jobs array of Job objects
302 */
303 static function safeBatchInsert( $jobs ) {
304 if ( !count( $jobs ) ) {
305 return;
306 }
307 $dbw = wfGetDB( DB_MASTER );
308 $rows = array();
309 foreach ( $jobs as $job ) {
310 $rows[] = $job->insertFields();
311 if ( count( $rows ) >= 500 ) {
312 $dbw->insert( 'job', $rows, __METHOD__, 'IGNORE' );
313 $rows = array();
314 }
315 }
316 if ( $rows ) { // last chunk
317 $dbw->insert( 'job', $rows, __METHOD__, 'IGNORE' );
318 }
319 wfIncrStats( 'job-insert', count( $jobs ) );
320 }
321
322 /*-------------------------------------------------------------------------
323 * Non-static functions
324 *------------------------------------------------------------------------*/
325
326 /**
327 * @param $command
328 * @param $title
329 * @param $params array
330 * @param int $id
331 */
332 function __construct( $command, $title, $params = false, $id = 0 ) {
333 $this->command = $command;
334 $this->title = $title;
335 $this->params = $params;
336 $this->id = $id;
337
338 // A bit of premature generalisation
339 // Oh well, the whole class is premature generalisation really
340 $this->removeDuplicates = true;
341 }
342
343 /**
344 * Insert a single job into the queue.
345 * @return bool true on success
346 */
347 function insert() {
348 $fields = $this->insertFields();
349
350 $dbw = wfGetDB( DB_MASTER );
351
352 if ( $this->removeDuplicates ) {
353 $res = $dbw->select( 'job', array( '1' ), $fields, __METHOD__ );
354 if ( $dbw->numRows( $res ) ) {
355 return true;
356 }
357 }
358 wfIncrStats( 'job-insert' );
359 return $dbw->insert( 'job', $fields, __METHOD__ );
360 }
361
362 /**
363 * @return array
364 */
365 protected function insertFields() {
366 $dbw = wfGetDB( DB_MASTER );
367 return array(
368 'job_id' => $dbw->nextSequenceValue( 'job_job_id_seq' ),
369 'job_cmd' => $this->command,
370 'job_namespace' => $this->title->getNamespace(),
371 'job_title' => $this->title->getDBkey(),
372 'job_timestamp' => $dbw->timestamp(),
373 'job_params' => Job::makeBlob( $this->params )
374 );
375 }
376
377 /**
378 * Remove jobs in the job queue which are duplicates of this job.
379 * This is deadlock-prone and so starts its own transaction.
380 */
381 function removeDuplicates() {
382 if ( !$this->removeDuplicates ) {
383 return;
384 }
385
386 $fields = $this->insertFields();
387 unset( $fields['job_id'] );
388 $dbw = wfGetDB( DB_MASTER );
389 $dbw->begin( __METHOD__ );
390 $dbw->delete( 'job', $fields, __METHOD__ );
391 $affected = $dbw->affectedRows();
392 $dbw->commit( __METHOD__ );
393 if ( $affected ) {
394 wfIncrStats( 'job-dup-delete', $affected );
395 }
396 }
397
398 /**
399 * @return string
400 */
401 function toString() {
402 $paramString = '';
403 if ( $this->params ) {
404 foreach ( $this->params as $key => $value ) {
405 if ( $paramString != '' ) {
406 $paramString .= ' ';
407 }
408 $paramString .= "$key=$value";
409 }
410 }
411
412 if ( is_object( $this->title ) ) {
413 $s = "{$this->command} " . $this->title->getPrefixedDBkey();
414 if ( $paramString !== '' ) {
415 $s .= ' ' . $paramString;
416 }
417 return $s;
418 } else {
419 return "{$this->command} $paramString";
420 }
421 }
422
423 protected function setLastError( $error ) {
424 $this->error = $error;
425 }
426
427 function getLastError() {
428 return $this->error;
429 }
430 }