3 * Database-backed job queue code.
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 * @author Aaron Schulz
25 * Class to handle job queues stored in the DB
30 class JobQueueDB
extends JobQueue
{
31 const CACHE_TTL
= 300; // integer; seconds to cache queue information
32 const MAX_AGE_PRUNE
= 604800; // integer; seconds a job can live once claimed
33 const MAX_ATTEMPTS
= 3; // integer; number of times to try a job
34 const MAX_JOB_RANDOM
= 2147483647; // integer; 2^31 - 1, used for job_random
37 * @see JobQueue::doIsEmpty()
40 protected function doIsEmpty() {
43 $key = $this->getEmptinessCacheKey();
45 $isEmpty = $wgMemc->get( $key );
46 if ( $isEmpty === 'true' ) {
48 } elseif ( $isEmpty === 'false' ) {
52 $found = $this->getSlaveDB()->selectField(
53 'job', '1', array( 'job_cmd' => $this->type
), __METHOD__
56 $wgMemc->add( $key, $found ?
'false' : 'true', self
::CACHE_TTL
);
60 * @see JobQueue::doBatchPush()
63 protected function doBatchPush( array $jobs, $flags ) {
64 if ( count( $jobs ) ) {
65 $dbw = $this->getMasterDB();
68 foreach ( $jobs as $job ) {
69 $rows[] = $this->insertFields( $job );
71 $atomic = ( $flags & self
::QoS_Atomic
);
72 $key = $this->getEmptinessCacheKey();
73 $ttl = self
::CACHE_TTL
;
75 $dbw->onTransactionIdle( function() use ( $dbw, $rows, $atomic, $key, $ttl ) {
78 $autoTrx = $dbw->getFlag( DBO_TRX
); // automatic begin() enabled?
80 $dbw->begin(); // wrap all the job additions in one transaction
82 $dbw->clearFlag( DBO_TRX
); // make each query its own transaction
85 foreach ( array_chunk( $rows, 50 ) as $rowBatch ) { // avoid slave lag
86 $dbw->insert( 'job', $rowBatch, __METHOD__
);
88 } catch ( DBError
$e ) {
92 $dbw->setFlag( $autoTrx ? DBO_TRX
: 0 ); // restore automatic begin()
99 $dbw->setFlag( $autoTrx ? DBO_TRX
: 0 ); // restore automatic begin()
102 $wgMemc->set( $key, 'false', $ttl ); // queue is not empty
110 * @see JobQueue::doPop()
113 protected function doPop() {
116 if ( $wgMemc->get( $this->getEmptinessCacheKey() ) === 'true' ) {
117 return false; // queue is empty
120 $dbw = $this->getMasterDB();
121 $dbw->commit( __METHOD__
, 'flush' ); // flush existing transaction
123 $uuid = wfRandomString( 32 ); // pop attempt
124 $job = false; // job popped off
125 $autoTrx = $dbw->getFlag( DBO_TRX
); // automatic begin() enabled?
126 $dbw->clearFlag( DBO_TRX
); // make each query its own transaction
128 // Occasionally recycle jobs back into the queue that have been claimed too long
129 if ( mt_rand( 0, 99 ) == 0 ) {
130 $this->recycleStaleJobs();
132 do { // retry when our row is invalid or deleted as a duplicate
133 // Try to reserve a row in the DB...
134 if ( in_array( $this->order
, array( 'fifo', 'timestamp' ) ) ) {
135 $row = $this->claimOldest( $uuid );
136 } else { // random first
137 $rand = mt_rand( 0, self
::MAX_JOB_RANDOM
); // encourage concurrent UPDATEs
138 $gte = (bool)mt_rand( 0, 1 ); // find rows with rand before/after $rand
139 $row = $this->claimRandom( $uuid, $rand, $gte );
140 if ( !$row ) { // need to try the other direction
141 $row = $this->claimRandom( $uuid, $rand, !$gte );
144 // Check if we found a row to reserve...
146 $wgMemc->set( $this->getEmptinessCacheKey(), 'true', self
::CACHE_TTL
);
147 break; // nothing to do
149 // Get the job object from the row...
150 $title = Title
::makeTitleSafe( $row->job_namespace
, $row->job_title
);
152 $dbw->delete( 'job', array( 'job_id' => $row->job_id
), __METHOD__
);
153 wfIncrStats( 'job-pop' );
154 wfDebugLog( 'JobQueueDB', "Row has invalid title '{$row->job_title}'." );
155 continue; // try again
157 $job = Job
::factory( $row->job_cmd
, $title,
158 self
::extractBlob( $row->job_params
), $row->job_id
);
159 // Delete any *other* duplicate jobs in the queue...
160 if ( $job->ignoreDuplicates() && strlen( $row->job_sha1
) ) {
162 array( 'job_sha1' => $row->job_sha1
,
163 "job_id != {$dbw->addQuotes( $row->job_id )}" ),
166 wfIncrStats( 'job-pop', $dbw->affectedRows() );
170 } catch ( DBError
$e ) {
171 $dbw->setFlag( $autoTrx ? DBO_TRX
: 0 ); // restore automatic begin()
174 $dbw->setFlag( $autoTrx ? DBO_TRX
: 0 ); // restore automatic begin()
180 * Reserve a row with a single UPDATE without holding row locks over RTTs...
182 * @param $uuid string 32 char hex string
183 * @param $rand integer Random unsigned integer (31 bits)
184 * @param $gte bool Search for job_random >= $random (otherwise job_random <= $random)
187 protected function claimRandom( $uuid, $rand, $gte ) {
188 $dbw = $this->getMasterDB();
189 $dir = $gte ?
'ASC' : 'DESC';
190 $ineq = $gte ?
'>=' : '<=';
192 $row = false; // the row acquired
193 // This uses a replication safe method for acquiring jobs. One could use UPDATE+LIMIT
194 // instead, but that either uses ORDER BY (in which case it deadlocks in MySQL) or is
195 // not replication safe. Due to http://bugs.mysql.com/bug.php?id=6980, subqueries cannot
196 // be used here with MySQL.
198 $row = $dbw->selectRow( 'job', '*', // find a random job
200 'job_cmd' => $this->type
,
202 "job_random {$ineq} {$dbw->addQuotes( $rand )}" ),
204 array( 'ORDER BY' => "job_random {$dir}" )
206 if ( $row ) { // claim the job
207 $dbw->update( 'job', // update by PK
209 'job_token' => $uuid,
210 'job_token_timestamp' => $dbw->timestamp(),
211 'job_attempts = job_attempts+1' ),
212 array( 'job_cmd' => $this->type
, 'job_id' => $row->job_id
, 'job_token' => '' ),
215 // This might get raced out by another runner when claiming the previously
216 // selected row. The use of job_random should minimize this problem, however.
217 if ( !$dbw->affectedRows() ) {
218 $row = false; // raced out
221 break; // nothing to do
229 * Reserve a row with a single UPDATE without holding row locks over RTTs...
231 * @param $uuid string 32 char hex string
234 protected function claimOldest( $uuid ) {
235 $dbw = $this->getMasterDB();
237 $row = false; // the row acquired
239 if ( $dbw->getType() === 'mysql' ) {
240 // Per http://bugs.mysql.com/bug.php?id=6980, we can't use subqueries on the
241 // same table being changed in an UPDATE query in MySQL (gives Error: 1093).
242 // Oracle and Postgre have no such limitation. However, MySQL offers an
243 // alternative here by supporting ORDER BY + LIMIT for UPDATE queries.
244 $dbw->query( "UPDATE {$dbw->tableName( 'job' )} " .
246 "job_token = {$dbw->addQuotes( $uuid ) }, " .
247 "job_token_timestamp = {$dbw->addQuotes( $dbw->timestamp() )}, " .
248 "job_attempts = job_attempts+1 " .
250 "job_cmd = {$dbw->addQuotes( $this->type )} " .
251 "AND job_token = {$dbw->addQuotes( '' )} " .
252 ") ORDER BY job_id ASC LIMIT 1",
256 // Use a subquery to find the job, within an UPDATE to claim it.
257 // This uses as much of the DB wrapper functions as possible.
260 'job_token' => $uuid,
261 'job_token_timestamp' => $dbw->timestamp(),
262 'job_attempts = job_attempts+1' ),
263 array( 'job_id = (' .
264 $dbw->selectSQLText( 'job', 'job_id',
265 array( 'job_cmd' => $this->type
, 'job_token' => '' ),
267 array( 'ORDER BY' => 'job_id ASC', 'LIMIT' => 1 ) ) .
273 // Fetch any row that we just reserved...
274 if ( $dbw->affectedRows() ) {
275 $row = $dbw->selectRow( 'job', '*',
276 array( 'job_cmd' => $this->type
, 'job_token' => $uuid ), __METHOD__
278 if ( !$row ) { // raced out by duplicate job removal
279 wfDebugLog( 'JobQueueDB', "Row deleted as duplicate by another process." );
282 break; // nothing to do
290 * Recycle or destroy any jobs that have been claimed for too long
292 * @return integer Number of jobs recycled/deleted
294 protected function recycleStaleJobs() {
296 $dbw = $this->getMasterDB();
297 $count = 0; // affected rows
299 if ( $this->claimTTL
> 0 ) { // re-try stale jobs...
300 $claimCutoff = $dbw->timestamp( $now - $this->claimTTL
);
301 // Reset job_token for these jobs so that other runners will pick them up.
302 // Set the timestamp to the current time, as it is useful to now that the job
303 // was already tried before.
307 'job_token_timestamp' => $dbw->timestamp( $now ) ), // time of release
309 'job_cmd' => $this->type
,
310 "job_token != {$dbw->addQuotes( '' )}", // was acquired
311 "job_token_timestamp < {$dbw->addQuotes( $claimCutoff )}", // stale
312 "job_attempts < {$dbw->addQuotes( self::MAX_ATTEMPTS )}" ),
315 $count +
= $dbw->affectedRows();
318 // Just destroy stale jobs...
319 $pruneCutoff = $dbw->timestamp( $now - self
::MAX_AGE_PRUNE
);
321 'job_cmd' => $this->type
,
322 "job_token != {$dbw->addQuotes( '' )}", // was acquired
323 "job_token_timestamp < {$dbw->addQuotes( $pruneCutoff )}" // stale
325 if ( $this->claimTTL
> 0 ) { // only prune jobs attempted too many times...
326 $conds[] = "job_attempts >= {$dbw->addQuotes( self::MAX_ATTEMPTS )}";
328 $dbw->delete( 'job', $conds, __METHOD__
);
329 $count +
= $dbw->affectedRows();
335 * @see JobQueue::doAck()
338 protected function doAck( Job
$job ) {
339 $dbw = $this->getMasterDB();
340 $dbw->commit( __METHOD__
, 'flush' ); // flush existing transaction
342 $autoTrx = $dbw->getFlag( DBO_TRX
); // automatic begin() enabled?
343 $dbw->clearFlag( DBO_TRX
); // make each query its own transaction
345 // Delete a row with a single DELETE without holding row locks over RTTs...
346 $dbw->delete( 'job', array( 'job_cmd' => $this->type
, 'job_id' => $job->getId() ) );
347 } catch ( Exception
$e ) {
348 $dbw->setFlag( $autoTrx ? DBO_TRX
: 0 ); // restore automatic begin()
351 $dbw->setFlag( $autoTrx ? DBO_TRX
: 0 ); // restore automatic begin()
357 * @see JobQueue::doWaitForBackups()
360 protected function doWaitForBackups() {
365 * @return DatabaseBase
367 protected function getSlaveDB() {
368 return wfGetDB( DB_SLAVE
, array(), $this->wiki
);
372 * @return DatabaseBase
374 protected function getMasterDB() {
375 return wfGetDB( DB_MASTER
, array(), $this->wiki
);
382 protected function insertFields( Job
$job ) {
383 // Rows that describe the nature of the job
385 'job_cmd' => $job->getType(),
386 'job_namespace' => $job->getTitle()->getNamespace(),
387 'job_title' => $job->getTitle()->getDBkey(),
388 'job_params' => self
::makeBlob( $job->getParams() ),
390 // Additional job metadata
391 $dbw = $this->getMasterDB();
393 'job_id' => $dbw->nextSequenceValue( 'job_job_id_seq' ),
394 'job_timestamp' => $dbw->timestamp(),
395 'job_sha1' => wfBaseConvert( sha1( serialize( $descFields ) ), 16, 36, 32 ),
396 'job_random' => mt_rand( 0, self
::MAX_JOB_RANDOM
)
398 return ( $descFields +
$metaFields );
404 private function getEmptinessCacheKey() {
405 list( $db, $prefix ) = wfSplitWikiID( $this->wiki
);
406 return wfForeignMemcKey( $db, $prefix, 'jobqueue', $this->type
, 'isempty' );
413 protected static function makeBlob( $params ) {
414 if ( $params !== false ) {
415 return serialize( $params );
425 protected static function extractBlob( $blob ) {
426 if ( (string)$blob !== '' ) {
427 return unserialize( $blob );