Merge "Memcached PHP client improvements"
[lhc/web/wiklou.git] / includes / job / Job.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 wfProfileIn( __METHOD__ );
117
118 $dbr = wfGetDB( DB_SLAVE );
119
120 /* Get a job from the slave, start with an offset,
121 scan full set afterwards, avoid hitting purged rows
122
123 NB: If random fetch previously was used, offset
124 will always be ahead of few entries
125 */
126
127 $conditions = self::defaultQueueConditions();
128
129 $offset = intval( $offset );
130 $options = array( 'ORDER BY' => 'job_id', 'USE INDEX' => 'PRIMARY' );
131
132 $row = $dbr->selectRow( 'job', '*',
133 array_merge( $conditions, array( "job_id >= $offset" ) ),
134 __METHOD__,
135 $options
136 );
137
138 // Refetching without offset is needed as some of job IDs could have had delayed commits
139 // and have lower IDs than jobs already executed, blame concurrency :)
140 //
141 if ( $row === false ) {
142 if ( $offset != 0 ) {
143 $row = $dbr->selectRow( 'job', '*', $conditions, __METHOD__, $options );
144 }
145
146 if ( $row === false ) {
147 wfProfileOut( __METHOD__ );
148 return false;
149 }
150 }
151
152 // Try to delete it from the master
153 $dbw = wfGetDB( DB_MASTER );
154 $dbw->delete( 'job', array( 'job_id' => $row->job_id ), __METHOD__ );
155 $affected = $dbw->affectedRows();
156 $dbw->commit( __METHOD__ );
157
158 if ( !$affected ) {
159 // Failed, someone else beat us to it
160 // Try getting a random row
161 $row = $dbw->selectRow( 'job', array( 'MIN(job_id) as minjob',
162 'MAX(job_id) as maxjob' ), '1=1', __METHOD__ );
163 if ( $row === false || is_null( $row->minjob ) || is_null( $row->maxjob ) ) {
164 // No jobs to get
165 wfProfileOut( __METHOD__ );
166 return false;
167 }
168 // Get the random row
169 $row = $dbw->selectRow( 'job', '*',
170 'job_id >= ' . mt_rand( $row->minjob, $row->maxjob ), __METHOD__ );
171 if ( $row === false ) {
172 // Random job gone before we got the chance to select it
173 // Give up
174 wfProfileOut( __METHOD__ );
175 return false;
176 }
177 // Delete the random row
178 $dbw->delete( 'job', array( 'job_id' => $row->job_id ), __METHOD__ );
179 $affected = $dbw->affectedRows();
180 $dbw->commit( __METHOD__ );
181
182 if ( !$affected ) {
183 // Random job gone before we exclusively deleted it
184 // Give up
185 wfProfileOut( __METHOD__ );
186 return false;
187 }
188 }
189
190 // If execution got to here, there's a row in $row that has been deleted from the database
191 // by this thread. Hence the concurrent pop was successful.
192 wfIncrStats( 'job-pop' );
193 $namespace = $row->job_namespace;
194 $dbkey = $row->job_title;
195 $title = Title::makeTitleSafe( $namespace, $dbkey );
196
197 if ( is_null( $title ) ) {
198 wfProfileOut( __METHOD__ );
199 return false;
200 }
201
202 $job = Job::factory( $row->job_cmd, $title, Job::extractBlob( $row->job_params ), $row->job_id );
203
204 // Remove any duplicates it may have later in the queue
205 $job->removeDuplicates();
206
207 wfProfileOut( __METHOD__ );
208 return $job;
209 }
210
211 /**
212 * Create the appropriate object to handle a specific job
213 *
214 * @param $command String: Job command
215 * @param $title Title: Associated title
216 * @param $params Array|bool: Job parameters
217 * @param $id Int: Job identifier
218 * @throws MWException
219 * @return Job
220 */
221 static function factory( $command, Title $title, $params = false, $id = 0 ) {
222 global $wgJobClasses;
223 if( isset( $wgJobClasses[$command] ) ) {
224 $class = $wgJobClasses[$command];
225 return new $class( $title, $params, $id );
226 }
227 throw new MWException( "Invalid job command `{$command}`" );
228 }
229
230 /**
231 * @param $params
232 * @return string
233 */
234 static function makeBlob( $params ) {
235 if ( $params !== false ) {
236 return serialize( $params );
237 } else {
238 return '';
239 }
240 }
241
242 /**
243 * @param $blob
244 * @return bool|mixed
245 */
246 static function extractBlob( $blob ) {
247 if ( (string)$blob !== '' ) {
248 return unserialize( $blob );
249 } else {
250 return false;
251 }
252 }
253
254 /**
255 * Batch-insert a group of jobs into the queue.
256 * This will be wrapped in a transaction with a forced commit.
257 *
258 * This may add duplicate at insert time, but they will be
259 * removed later on, when the first one is popped.
260 *
261 * @param $jobs array of Job objects
262 */
263 static function batchInsert( $jobs ) {
264 if ( !count( $jobs ) ) {
265 return;
266 }
267 $dbw = wfGetDB( DB_MASTER );
268 $rows = array();
269
270 /**
271 * @var $job Job
272 */
273 foreach ( $jobs as $job ) {
274 $rows[] = $job->insertFields();
275 if ( count( $rows ) >= 50 ) {
276 # Do a small transaction to avoid slave lag
277 $dbw->begin( __METHOD__ );
278 $dbw->insert( 'job', $rows, __METHOD__, 'IGNORE' );
279 $dbw->commit( __METHOD__ );
280 $rows = array();
281 }
282 }
283 if ( $rows ) { // last chunk
284 $dbw->begin( __METHOD__ );
285 $dbw->insert( 'job', $rows, __METHOD__, 'IGNORE' );
286 $dbw->commit( __METHOD__ );
287 }
288 wfIncrStats( 'job-insert', count( $jobs ) );
289 }
290
291 /**
292 * Insert a group of jobs into the queue.
293 *
294 * Same as batchInsert() but does not commit and can thus
295 * be rolled-back as part of a larger transaction. However,
296 * large batches of jobs can cause slave lag.
297 *
298 * @param $jobs array of Job objects
299 */
300 static function safeBatchInsert( $jobs ) {
301 if ( !count( $jobs ) ) {
302 return;
303 }
304 $dbw = wfGetDB( DB_MASTER );
305 $rows = array();
306 foreach ( $jobs as $job ) {
307 $rows[] = $job->insertFields();
308 if ( count( $rows ) >= 500 ) {
309 $dbw->insert( 'job', $rows, __METHOD__, 'IGNORE' );
310 $rows = array();
311 }
312 }
313 if ( $rows ) { // last chunk
314 $dbw->insert( 'job', $rows, __METHOD__, 'IGNORE' );
315 }
316 wfIncrStats( 'job-insert', count( $jobs ) );
317 }
318
319
320 /**
321 * SQL conditions to apply on most JobQueue queries
322 *
323 * Whenever we exclude jobs types from the default queue, we want to make
324 * sure that queries to the job queue actually ignore them.
325 *
326 * @return array SQL conditions suitable for Database:: methods
327 */
328 static function defaultQueueConditions( ) {
329 global $wgJobTypesExcludedFromDefaultQueue;
330 $conditions = array();
331 if ( count( $wgJobTypesExcludedFromDefaultQueue ) > 0 ) {
332 $dbr = wfGetDB( DB_SLAVE );
333 foreach ( $wgJobTypesExcludedFromDefaultQueue as $cmdType ) {
334 $conditions[] = "job_cmd != " . $dbr->addQuotes( $cmdType );
335 }
336 }
337 return $conditions;
338 }
339
340 /*-------------------------------------------------------------------------
341 * Non-static functions
342 *------------------------------------------------------------------------*/
343
344 /**
345 * @param $command
346 * @param $title
347 * @param $params array|bool
348 * @param $id int
349 */
350 function __construct( $command, $title, $params = false, $id = 0 ) {
351 $this->command = $command;
352 $this->title = $title;
353 $this->params = $params;
354 $this->id = $id;
355
356 // A bit of premature generalisation
357 // Oh well, the whole class is premature generalisation really
358 $this->removeDuplicates = true;
359 }
360
361 /**
362 * Insert a single job into the queue.
363 * @return bool true on success
364 */
365 function insert() {
366 $fields = $this->insertFields();
367
368 $dbw = wfGetDB( DB_MASTER );
369
370 if ( $this->removeDuplicates ) {
371 $res = $dbw->select( 'job', array( '1' ), $fields, __METHOD__ );
372 if ( $dbw->numRows( $res ) ) {
373 return true;
374 }
375 }
376 wfIncrStats( 'job-insert' );
377 return $dbw->insert( 'job', $fields, __METHOD__ );
378 }
379
380 /**
381 * @return array
382 */
383 protected function insertFields() {
384 $dbw = wfGetDB( DB_MASTER );
385 return array(
386 'job_id' => $dbw->nextSequenceValue( 'job_job_id_seq' ),
387 'job_cmd' => $this->command,
388 'job_namespace' => $this->title->getNamespace(),
389 'job_title' => $this->title->getDBkey(),
390 'job_timestamp' => $dbw->timestamp(),
391 'job_params' => Job::makeBlob( $this->params )
392 );
393 }
394
395 /**
396 * Remove jobs in the job queue which are duplicates of this job.
397 * This is deadlock-prone and so starts its own transaction.
398 */
399 function removeDuplicates() {
400 if ( !$this->removeDuplicates ) {
401 return;
402 }
403
404 $fields = $this->insertFields();
405 unset( $fields['job_id'] );
406 $dbw = wfGetDB( DB_MASTER );
407 $dbw->begin( __METHOD__ );
408 $dbw->delete( 'job', $fields, __METHOD__ );
409 $affected = $dbw->affectedRows();
410 $dbw->commit( __METHOD__ );
411 if ( $affected ) {
412 wfIncrStats( 'job-dup-delete', $affected );
413 }
414 }
415
416 /**
417 * @return string
418 */
419 function toString() {
420 $paramString = '';
421 if ( $this->params ) {
422 foreach ( $this->params as $key => $value ) {
423 if ( $paramString != '' ) {
424 $paramString .= ' ';
425 }
426 $paramString .= "$key=$value";
427 }
428 }
429
430 if ( is_object( $this->title ) ) {
431 $s = "{$this->command} " . $this->title->getPrefixedDBkey();
432 if ( $paramString !== '' ) {
433 $s .= ' ' . $paramString;
434 }
435 return $s;
436 } else {
437 return "{$this->command} $paramString";
438 }
439 }
440
441 protected function setLastError( $error ) {
442 $this->error = $error;
443 }
444
445 function getLastError() {
446 return $this->error;
447 }
448 }