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( __METHOD__
); // 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 ) {
90 $dbw->rollback( __METHOD__
);
92 $dbw->setFlag( $autoTrx ? DBO_TRX
: 0 ); // restore automatic begin()
97 $dbw->commit( __METHOD__
);
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() );
168 // Flag this job as an old duplicate based on its "root" job...
169 if ( $this->isRootJobOldDuplicate( $job ) ) {
170 $job = DuplicateJob
::newFromJob( $job ); // convert to a no-op
174 } catch ( DBError
$e ) {
175 $dbw->setFlag( $autoTrx ? DBO_TRX
: 0 ); // restore automatic begin()
178 $dbw->setFlag( $autoTrx ? DBO_TRX
: 0 ); // restore automatic begin()
184 * Reserve a row with a single UPDATE without holding row locks over RTTs...
186 * @param $uuid string 32 char hex string
187 * @param $rand integer Random unsigned integer (31 bits)
188 * @param $gte bool Search for job_random >= $random (otherwise job_random <= $random)
191 protected function claimRandom( $uuid, $rand, $gte ) {
192 $dbw = $this->getMasterDB();
193 $dir = $gte ?
'ASC' : 'DESC';
194 $ineq = $gte ?
'>=' : '<=';
196 $row = false; // the row acquired
197 // This uses a replication safe method for acquiring jobs. One could use UPDATE+LIMIT
198 // instead, but that either uses ORDER BY (in which case it deadlocks in MySQL) or is
199 // not replication safe. Due to http://bugs.mysql.com/bug.php?id=6980, subqueries cannot
200 // be used here with MySQL.
202 $row = $dbw->selectRow( 'job', '*', // find a random job
204 'job_cmd' => $this->type
,
206 "job_random {$ineq} {$dbw->addQuotes( $rand )}" ),
208 array( 'ORDER BY' => "job_random {$dir}" )
210 if ( $row ) { // claim the job
211 $dbw->update( 'job', // update by PK
213 'job_token' => $uuid,
214 'job_token_timestamp' => $dbw->timestamp(),
215 'job_attempts = job_attempts+1' ),
216 array( 'job_cmd' => $this->type
, 'job_id' => $row->job_id
, 'job_token' => '' ),
219 // This might get raced out by another runner when claiming the previously
220 // selected row. The use of job_random should minimize this problem, however.
221 if ( !$dbw->affectedRows() ) {
222 $row = false; // raced out
225 break; // nothing to do
233 * Reserve a row with a single UPDATE without holding row locks over RTTs...
235 * @param $uuid string 32 char hex string
238 protected function claimOldest( $uuid ) {
239 $dbw = $this->getMasterDB();
241 $row = false; // the row acquired
243 if ( $dbw->getType() === 'mysql' ) {
244 // Per http://bugs.mysql.com/bug.php?id=6980, we can't use subqueries on the
245 // same table being changed in an UPDATE query in MySQL (gives Error: 1093).
246 // Oracle and Postgre have no such limitation. However, MySQL offers an
247 // alternative here by supporting ORDER BY + LIMIT for UPDATE queries.
248 $dbw->query( "UPDATE {$dbw->tableName( 'job' )} " .
250 "job_token = {$dbw->addQuotes( $uuid ) }, " .
251 "job_token_timestamp = {$dbw->addQuotes( $dbw->timestamp() )}, " .
252 "job_attempts = job_attempts+1 " .
254 "job_cmd = {$dbw->addQuotes( $this->type )} " .
255 "AND job_token = {$dbw->addQuotes( '' )} " .
256 ") ORDER BY job_id ASC LIMIT 1",
260 // Use a subquery to find the job, within an UPDATE to claim it.
261 // This uses as much of the DB wrapper functions as possible.
264 'job_token' => $uuid,
265 'job_token_timestamp' => $dbw->timestamp(),
266 'job_attempts = job_attempts+1' ),
267 array( 'job_id = (' .
268 $dbw->selectSQLText( 'job', 'job_id',
269 array( 'job_cmd' => $this->type
, 'job_token' => '' ),
271 array( 'ORDER BY' => 'job_id ASC', 'LIMIT' => 1 ) ) .
277 // Fetch any row that we just reserved...
278 if ( $dbw->affectedRows() ) {
279 $row = $dbw->selectRow( 'job', '*',
280 array( 'job_cmd' => $this->type
, 'job_token' => $uuid ), __METHOD__
282 if ( !$row ) { // raced out by duplicate job removal
283 wfDebugLog( 'JobQueueDB', "Row deleted as duplicate by another process." );
286 break; // nothing to do
294 * Recycle or destroy any jobs that have been claimed for too long
296 * @return integer Number of jobs recycled/deleted
298 protected function recycleStaleJobs() {
300 $dbw = $this->getMasterDB();
301 $count = 0; // affected rows
303 if ( $this->claimTTL
> 0 ) { // re-try stale jobs...
304 $claimCutoff = $dbw->timestamp( $now - $this->claimTTL
);
305 // Reset job_token for these jobs so that other runners will pick them up.
306 // Set the timestamp to the current time, as it is useful to now that the job
307 // was already tried before.
311 'job_token_timestamp' => $dbw->timestamp( $now ) ), // time of release
313 'job_cmd' => $this->type
,
314 "job_token != {$dbw->addQuotes( '' )}", // was acquired
315 "job_token_timestamp < {$dbw->addQuotes( $claimCutoff )}", // stale
316 "job_attempts < {$dbw->addQuotes( self::MAX_ATTEMPTS )}" ),
319 $count +
= $dbw->affectedRows();
322 // Just destroy stale jobs...
323 $pruneCutoff = $dbw->timestamp( $now - self
::MAX_AGE_PRUNE
);
325 'job_cmd' => $this->type
,
326 "job_token != {$dbw->addQuotes( '' )}", // was acquired
327 "job_token_timestamp < {$dbw->addQuotes( $pruneCutoff )}" // stale
329 if ( $this->claimTTL
> 0 ) { // only prune jobs attempted too many times...
330 $conds[] = "job_attempts >= {$dbw->addQuotes( self::MAX_ATTEMPTS )}";
332 $dbw->delete( 'job', $conds, __METHOD__
);
333 $count +
= $dbw->affectedRows();
339 * @see JobQueue::doAck()
342 protected function doAck( Job
$job ) {
343 $dbw = $this->getMasterDB();
344 $dbw->commit( __METHOD__
, 'flush' ); // flush existing transaction
346 $autoTrx = $dbw->getFlag( DBO_TRX
); // automatic begin() enabled?
347 $dbw->clearFlag( DBO_TRX
); // make each query its own transaction
349 // Delete a row with a single DELETE without holding row locks over RTTs...
350 $dbw->delete( 'job', array( 'job_cmd' => $this->type
, 'job_id' => $job->getId() ) );
351 } catch ( Exception
$e ) {
352 $dbw->setFlag( $autoTrx ? DBO_TRX
: 0 ); // restore automatic begin()
355 $dbw->setFlag( $autoTrx ? DBO_TRX
: 0 ); // restore automatic begin()
361 * @see JobQueue::doDeduplicateRootJob()
364 protected function doDeduplicateRootJob( Job
$job ) {
365 $params = $job->getParams();
366 if ( !isset( $params['rootJobSignature'] ) ) {
367 throw new MWException( "Cannot register root job; missing 'rootJobSignature'." );
368 } elseif ( !isset( $params['rootJobTimestamp'] ) ) {
369 throw new MWException( "Cannot register root job; missing 'rootJobTimestamp'." );
371 $key = $this->getRootJobCacheKey( $params['rootJobSignature'] );
372 // Callers should call batchInsert() and then this function so that if the insert
373 // fails, the de-duplication registration will be aborted. Since the insert is
374 // deferred till "transaction idle", do that same here, so that the ordering is
375 // maintained. Having only the de-duplication registration succeed would cause
376 // jobs to become no-ops without any actual jobs that made them redundant.
377 $this->getMasterDB()->onTransactionIdle( function() use ( $params, $key ) {
380 $timestamp = $wgMemc->get( $key ); // current last timestamp of this job
381 if ( $timestamp && $timestamp >= $params['rootJobTimestamp'] ) {
382 return true; // a newer version of this root job was enqueued
385 // Update the timestamp of the last root job started at the location...
386 return $wgMemc->set( $key, $params['rootJobTimestamp'], 14*86400 ); // 2 weeks
393 * Check if the "root" job of a given job has been superseded by a newer one
398 protected function isRootJobOldDuplicate( Job
$job ) {
401 $params = $job->getParams();
402 if ( !isset( $params['rootJobSignature'] ) ) {
403 return false; // job has no de-deplication info
404 } elseif ( !isset( $params['rootJobTimestamp'] ) ) {
405 trigger_error( "Cannot check root job; missing 'rootJobTimestamp'." );
409 // Get the last time this root job was enqueued
410 $timestamp = $wgMemc->get( $this->getRootJobCacheKey( $params['rootJobSignature'] ) );
412 // Check if a new root job was started at the location after this one's...
413 return ( $timestamp && $timestamp > $params['rootJobTimestamp'] );
417 * @see JobQueue::doWaitForBackups()
420 protected function doWaitForBackups() {
425 * @return DatabaseBase
427 protected function getSlaveDB() {
428 return wfGetDB( DB_SLAVE
, array(), $this->wiki
);
432 * @return DatabaseBase
434 protected function getMasterDB() {
435 return wfGetDB( DB_MASTER
, array(), $this->wiki
);
442 protected function insertFields( Job
$job ) {
443 $dbw = $this->getMasterDB();
445 // Fields that describe the nature of the job
446 'job_cmd' => $job->getType(),
447 'job_namespace' => $job->getTitle()->getNamespace(),
448 'job_title' => $job->getTitle()->getDBkey(),
449 'job_params' => self
::makeBlob( $job->getParams() ),
450 // Additional job metadata
451 'job_id' => $dbw->nextSequenceValue( 'job_job_id_seq' ),
452 'job_timestamp' => $dbw->timestamp(),
453 'job_sha1' => wfBaseConvert(
454 sha1( serialize( $job->getDeduplicationInfo() ) ),
457 'job_random' => mt_rand( 0, self
::MAX_JOB_RANDOM
)
464 private function getEmptinessCacheKey() {
465 list( $db, $prefix ) = wfSplitWikiID( $this->wiki
);
466 return wfForeignMemcKey( $db, $prefix, 'jobqueue', $this->type
, 'isempty' );
470 * @param string $signature Hash identifier of the root job
473 private function getRootJobCacheKey( $signature ) {
474 list( $db, $prefix ) = wfSplitWikiID( $this->wiki
);
475 return wfForeignMemcKey( $db, $prefix, 'jobqueue', $this->type
, 'rootjob', $signature );
482 protected static function makeBlob( $params ) {
483 if ( $params !== false ) {
484 return serialize( $params );
494 protected static function extractBlob( $blob ) {
495 if ( (string)$blob !== '' ) {
496 return unserialize( $blob );