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.
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.
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
21 * @defgroup JobQueue JobQueue
25 * Class to both describe a background job and handle jobs.
42 /*-------------------------------------------------------------------------
44 *------------------------------------------------------------------------*/
48 * @return boolean success
50 abstract function run();
52 /*-------------------------------------------------------------------------
54 *------------------------------------------------------------------------*/
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
65 static function pop_type( $type ) {
66 wfProfilein( __METHOD__
);
68 $dbw = wfGetDB( DB_MASTER
);
70 $dbw->begin( __METHOD__
);
72 $row = $dbw->selectRow(
75 array( 'job_cmd' => $type ),
77 array( 'LIMIT' => 1, 'FOR UPDATE' )
80 if ( $row === false ) {
81 $dbw->commit( __METHOD__
);
82 wfProfileOut( __METHOD__
);
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__
);
91 if ( $affected == 0 ) {
92 wfProfileOut( __METHOD__
);
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
),
103 $job->removeDuplicates();
105 wfProfileOut( __METHOD__
);
110 * Pop a job off the front of the queue
112 * @param $offset Integer: Number of jobs to skip
113 * @return Job or false if there's no jobs
115 static function pop( $offset = 0 ) {
116 global $wgJobTypesExcludedFromDefaultQueue;
117 wfProfileIn( __METHOD__
);
119 $dbr = wfGetDB( DB_SLAVE
);
121 /* Get a job from the slave, start with an offset,
122 scan full set afterwards, avoid hitting purged rows
124 NB: If random fetch previously was used, offset
125 will always be ahead of few entries
127 $conditions = array();
128 if ( count( $wgJobTypesExcludedFromDefaultQueue ) != 0 ) {
129 foreach ( $wgJobTypesExcludedFromDefaultQueue as $cmdType ) {
130 $conditions[] = "job_cmd != " . $dbr->addQuotes( $cmdType );
133 $offset = intval( $offset );
134 $options = array( 'ORDER BY' => 'job_id', 'USE INDEX' => 'PRIMARY' );
136 $row = $dbr->selectRow( 'job', '*',
137 array_merge( $conditions, array( "job_id >= $offset" ) ),
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 :)
145 if ( $row === false ) {
146 if ( $offset != 0 ) {
147 $row = $dbr->selectRow( 'job', '*', $conditions, __METHOD__
, $options );
150 if ( $row === false ) {
151 wfProfileOut( __METHOD__
);
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__
);
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
) ) {
169 wfProfileOut( __METHOD__
);
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
178 wfProfileOut( __METHOD__
);
181 // Delete the random row
182 $dbw->delete( 'job', array( 'job_id' => $row->job_id
), __METHOD__
);
183 $affected = $dbw->affectedRows();
184 $dbw->commit( __METHOD__
);
187 // Random job gone before we exclusively deleted it
189 wfProfileOut( __METHOD__
);
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 );
201 if ( is_null( $title ) ) {
205 $job = Job
::factory( $row->job_cmd
, $title, Job
::extractBlob( $row->job_params
), $row->job_id
);
207 // Remove any duplicates it may have later in the queue
208 $job->removeDuplicates();
210 wfProfileOut( __METHOD__
);
215 * Create the appropriate object to handle a specific job
217 * @param $command String: Job command
218 * @param $title Title: Associated title
219 * @param $params Array: Job parameters
220 * @param $id Int: Job identifier
223 static function factory( $command, Title
$title, $params = false, $id = 0 ) {
224 global $wgJobClasses;
225 if( isset( $wgJobClasses[$command] ) ) {
226 $class = $wgJobClasses[$command];
227 return new $class( $title, $params, $id );
229 throw new MWException( "Invalid job command `{$command}`" );
236 static function makeBlob( $params ) {
237 if ( $params !== false ) {
238 return serialize( $params );
248 static function extractBlob( $blob ) {
249 if ( (string)$blob !== '' ) {
250 return unserialize( $blob );
257 * Batch-insert a group of jobs into the queue.
258 * This will be wrapped in a transaction with a forced commit.
260 * This may add duplicate at insert time, but they will be
261 * removed later on, when the first one is popped.
263 * @param $jobs array of Job objects
265 static function batchInsert( $jobs ) {
266 if ( !count( $jobs ) ) {
269 $dbw = wfGetDB( DB_MASTER
);
275 foreach ( $jobs as $job ) {
276 $rows[] = $job->insertFields();
277 if ( count( $rows ) >= 50 ) {
278 # Do a small transaction to avoid slave lag
279 $dbw->begin( __METHOD__
);
280 $dbw->insert( 'job', $rows, __METHOD__
, 'IGNORE' );
281 $dbw->commit( __METHOD__
);
285 if ( $rows ) { // last chunk
286 $dbw->begin( __METHOD__
);
287 $dbw->insert( 'job', $rows, __METHOD__
, 'IGNORE' );
288 $dbw->commit( __METHOD__
);
290 wfIncrStats( 'job-insert', count( $jobs ) );
294 * Insert a group of jobs into the queue.
296 * Same as batchInsert() but does not commit and can thus
297 * be rolled-back as part of a larger transaction. However,
298 * large batches of jobs can cause slave lag.
300 * @param $jobs array of Job objects
302 static function safeBatchInsert( $jobs ) {
303 if ( !count( $jobs ) ) {
306 $dbw = wfGetDB( DB_MASTER
);
308 foreach ( $jobs as $job ) {
309 $rows[] = $job->insertFields();
310 if ( count( $rows ) >= 500 ) {
311 $dbw->insert( 'job', $rows, __METHOD__
, 'IGNORE' );
315 if ( $rows ) { // last chunk
316 $dbw->insert( 'job', $rows, __METHOD__
, 'IGNORE' );
318 wfIncrStats( 'job-insert', count( $jobs ) );
321 /*-------------------------------------------------------------------------
322 * Non-static functions
323 *------------------------------------------------------------------------*/
328 * @param $params array
331 function __construct( $command, $title, $params = false, $id = 0 ) {
332 $this->command
= $command;
333 $this->title
= $title;
334 $this->params
= $params;
337 // A bit of premature generalisation
338 // Oh well, the whole class is premature generalisation really
339 $this->removeDuplicates
= true;
343 * Insert a single job into the queue.
344 * @return bool true on success
347 $fields = $this->insertFields();
349 $dbw = wfGetDB( DB_MASTER
);
351 if ( $this->removeDuplicates
) {
352 $res = $dbw->select( 'job', array( '1' ), $fields, __METHOD__
);
353 if ( $dbw->numRows( $res ) ) {
357 wfIncrStats( 'job-insert' );
358 return $dbw->insert( 'job', $fields, __METHOD__
);
364 protected function insertFields() {
365 $dbw = wfGetDB( DB_MASTER
);
367 'job_id' => $dbw->nextSequenceValue( 'job_job_id_seq' ),
368 'job_cmd' => $this->command
,
369 'job_namespace' => $this->title
->getNamespace(),
370 'job_title' => $this->title
->getDBkey(),
371 'job_timestamp' => $dbw->timestamp(),
372 'job_params' => Job
::makeBlob( $this->params
)
377 * Remove jobs in the job queue which are duplicates of this job.
378 * This is deadlock-prone and so starts its own transaction.
380 function removeDuplicates() {
381 if ( !$this->removeDuplicates
) {
385 $fields = $this->insertFields();
386 unset( $fields['job_id'] );
387 $dbw = wfGetDB( DB_MASTER
);
388 $dbw->begin( __METHOD__
);
389 $dbw->delete( 'job', $fields, __METHOD__
);
390 $affected = $dbw->affectedRows();
391 $dbw->commit( __METHOD__
);
393 wfIncrStats( 'job-dup-delete', $affected );
400 function toString() {
402 if ( $this->params
) {
403 foreach ( $this->params
as $key => $value ) {
404 if ( $paramString != '' ) {
407 $paramString .= "$key=$value";
411 if ( is_object( $this->title
) ) {
412 $s = "{$this->command} " . $this->title
->getPrefixedDBkey();
413 if ( $paramString !== '' ) {
414 $s .= ' ' . $paramString;
418 return "{$this->command} $paramString";
422 protected function setLastError( $error ) {
423 $this->error
= $error;
426 function getLastError() {