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
);
61 * @see JobQueue::doBatchPush()
64 * @throws DBError|Exception
67 protected function doBatchPush( array $jobs, $flags ) {
68 if ( count( $jobs ) ) {
69 $dbw = $this->getMasterDB();
71 $rowSet = array(); // (sha1 => job) map for jobs that are de-duplicated
72 $rowList = array(); // list of jobs for jobs that are are not de-duplicated
74 foreach ( $jobs as $job ) {
75 $row = $this->insertFields( $job );
76 if ( $job->ignoreDuplicates() ) {
77 $rowSet[$row['job_sha1']] = $row;
83 $atomic = ( $flags & self
::QoS_Atomic
);
84 $key = $this->getEmptinessCacheKey();
85 $ttl = self
::CACHE_TTL
;
87 $dbw->onTransactionIdle(
88 function() use ( $dbw, $rowSet, $rowList, $atomic, $key, $ttl
93 $dbw->begin( __METHOD__
); // wrap all the job additions in one transaction
96 // Strip out any duplicate jobs that are already in the queue...
97 if ( count( $rowSet ) ) {
98 $res = $dbw->select( 'job', 'job_sha1',
100 // No job_type condition since it's part of the job_sha1 hash
101 'job_sha1' => array_keys( $rowSet ),
102 'job_token' => '' // unclaimed
106 foreach ( $res as $row ) {
107 wfDebug( "Job with hash '{$row->job_sha1}' is a duplicate." );
108 unset( $rowSet[$row->job_sha1
] ); // already enqueued
111 // Build the full list of job rows to insert
112 $rows = array_merge( $rowList, array_values( $rowSet ) );
113 // Insert the job rows in chunks to avoid slave lag...
114 foreach ( array_chunk( $rows, 50 ) as $rowBatch ) {
115 $dbw->insert( 'job', $rowBatch, __METHOD__
);
117 } catch ( DBError
$e ) {
119 $dbw->rollback( __METHOD__
);
124 $dbw->commit( __METHOD__
);
127 $wgMemc->set( $key, 'false', $ttl ); // queue is not empty
135 * @see JobQueue::doPop()
138 protected function doPop() {
141 if ( $wgMemc->get( $this->getEmptinessCacheKey() ) === 'true' ) {
142 return false; // queue is empty
145 $dbw = $this->getMasterDB();
146 $dbw->commit( __METHOD__
, 'flush' ); // flush existing transaction
148 $uuid = wfRandomString( 32 ); // pop attempt
149 $job = false; // job popped off
150 // Occasionally recycle jobs back into the queue that have been claimed too long
151 if ( mt_rand( 0, 99 ) == 0 ) {
152 $this->recycleStaleJobs();
154 do { // retry when our row is invalid or deleted as a duplicate
155 // Try to reserve a row in the DB...
156 if ( in_array( $this->order
, array( 'fifo', 'timestamp' ) ) ) {
157 $row = $this->claimOldest( $uuid );
158 } else { // random first
159 $rand = mt_rand( 0, self
::MAX_JOB_RANDOM
); // encourage concurrent UPDATEs
160 $gte = (bool)mt_rand( 0, 1 ); // find rows with rand before/after $rand
161 $row = $this->claimRandom( $uuid, $rand, $gte );
162 if ( !$row ) { // need to try the other direction
163 $row = $this->claimRandom( $uuid, $rand, !$gte );
166 // Check if we found a row to reserve...
168 $wgMemc->set( $this->getEmptinessCacheKey(), 'true', self
::CACHE_TTL
);
169 break; // nothing to do
171 // Get the job object from the row...
172 $title = Title
::makeTitleSafe( $row->job_namespace
, $row->job_title
);
174 $dbw->delete( 'job', array( 'job_id' => $row->job_id
), __METHOD__
);
175 wfIncrStats( 'job-pop' );
176 wfDebugLog( 'JobQueueDB', "Row has invalid title '{$row->job_title}'." );
177 continue; // try again
179 $job = Job
::factory( $row->job_cmd
, $title,
180 self
::extractBlob( $row->job_params
), $row->job_id
);
181 $job->id
= $row->job_id
; // XXX: work around broken subclasses
182 // Flag this job as an old duplicate based on its "root" job...
183 if ( $this->isRootJobOldDuplicate( $job ) ) {
184 $job = DuplicateJob
::newFromJob( $job ); // convert to a no-op
193 * Reserve a row with a single UPDATE without holding row locks over RTTs...
195 * @param $uuid string 32 char hex string
196 * @param $rand integer Random unsigned integer (31 bits)
197 * @param $gte bool Search for job_random >= $random (otherwise job_random <= $random)
200 protected function claimRandom( $uuid, $rand, $gte ) {
201 $dbw = $this->getMasterDB();
202 $dir = $gte ?
'ASC' : 'DESC';
203 $ineq = $gte ?
'>=' : '<=';
205 $row = false; // the row acquired
206 // This uses a replication safe method for acquiring jobs. One could use UPDATE+LIMIT
207 // instead, but that either uses ORDER BY (in which case it deadlocks in MySQL) or is
208 // not replication safe. Due to http://bugs.mysql.com/bug.php?id=6980, subqueries cannot
209 // be used here with MySQL.
211 $row = $dbw->selectRow( 'job', '*', // find a random job
213 'job_cmd' => $this->type
,
215 "job_random {$ineq} {$dbw->addQuotes( $rand )}" ),
217 array( 'ORDER BY' => "job_random {$dir}" )
219 if ( $row ) { // claim the job
220 $dbw->update( 'job', // update by PK
222 'job_token' => $uuid,
223 'job_token_timestamp' => $dbw->timestamp(),
224 'job_attempts = job_attempts+1' ),
225 array( 'job_cmd' => $this->type
, 'job_id' => $row->job_id
, 'job_token' => '' ),
228 // This might get raced out by another runner when claiming the previously
229 // selected row. The use of job_random should minimize this problem, however.
230 if ( !$dbw->affectedRows() ) {
231 $row = false; // raced out
234 break; // nothing to do
242 * Reserve a row with a single UPDATE without holding row locks over RTTs...
244 * @param $uuid string 32 char hex string
247 protected function claimOldest( $uuid ) {
248 $dbw = $this->getMasterDB();
250 $row = false; // the row acquired
252 if ( $dbw->getType() === 'mysql' ) {
253 // Per http://bugs.mysql.com/bug.php?id=6980, we can't use subqueries on the
254 // same table being changed in an UPDATE query in MySQL (gives Error: 1093).
255 // Oracle and Postgre have no such limitation. However, MySQL offers an
256 // alternative here by supporting ORDER BY + LIMIT for UPDATE queries.
257 $dbw->query( "UPDATE {$dbw->tableName( 'job' )} " .
259 "job_token = {$dbw->addQuotes( $uuid ) }, " .
260 "job_token_timestamp = {$dbw->addQuotes( $dbw->timestamp() )}, " .
261 "job_attempts = job_attempts+1 " .
263 "job_cmd = {$dbw->addQuotes( $this->type )} " .
264 "AND job_token = {$dbw->addQuotes( '' )} " .
265 ") ORDER BY job_id ASC LIMIT 1",
269 // Use a subquery to find the job, within an UPDATE to claim it.
270 // This uses as much of the DB wrapper functions as possible.
273 'job_token' => $uuid,
274 'job_token_timestamp' => $dbw->timestamp(),
275 'job_attempts = job_attempts+1' ),
276 array( 'job_id = (' .
277 $dbw->selectSQLText( 'job', 'job_id',
278 array( 'job_cmd' => $this->type
, 'job_token' => '' ),
280 array( 'ORDER BY' => 'job_id ASC', 'LIMIT' => 1 ) ) .
286 // Fetch any row that we just reserved...
287 if ( $dbw->affectedRows() ) {
288 $row = $dbw->selectRow( 'job', '*',
289 array( 'job_cmd' => $this->type
, 'job_token' => $uuid ), __METHOD__
291 if ( !$row ) { // raced out by duplicate job removal
292 wfDebugLog( 'JobQueueDB', "Row deleted as duplicate by another process." );
295 break; // nothing to do
303 * Recycle or destroy any jobs that have been claimed for too long
305 * @return integer Number of jobs recycled/deleted
307 protected function recycleStaleJobs() {
309 $dbw = $this->getMasterDB();
310 $count = 0; // affected rows
312 if ( !$dbw->lock( "jobqueue-recycle-{$this->type}", __METHOD__
, 1 ) ) {
313 return $count; // already in progress
316 // Remove claims on jobs acquired for too long if enabled...
317 if ( $this->claimTTL
> 0 ) {
318 $claimCutoff = $dbw->timestamp( $now - $this->claimTTL
);
319 // Get the IDs of jobs that have be claimed but not finished after too long.
320 // These jobs can be recycled into the queue by expiring the claim. Selecting
321 // the IDs first means that the UPDATE can be done by primary key (less deadlocks).
322 $res = $dbw->select( 'job', 'job_id',
324 'job_cmd' => $this->type
,
325 "job_token != {$dbw->addQuotes( '' )}", // was acquired
326 "job_token_timestamp < {$dbw->addQuotes( $claimCutoff )}", // stale
327 "job_attempts < {$dbw->addQuotes( self::MAX_ATTEMPTS )}" ), // retries left
330 $ids = array_map( function( $o ) { return $o->job_id
; }, iterator_to_array( $res ) );
331 if ( count( $ids ) ) {
332 // Reset job_token for these jobs so that other runners will pick them up.
333 // Set the timestamp to the current time, as it is useful to now that the job
334 // was already tried before (the timestamp becomes the "released" time).
338 'job_token_timestamp' => $dbw->timestamp( $now ) ), // time of release
343 $count +
= $dbw->affectedRows();
347 // Just destroy any stale jobs...
348 $pruneCutoff = $dbw->timestamp( $now - self
::MAX_AGE_PRUNE
);
350 'job_cmd' => $this->type
,
351 "job_token != {$dbw->addQuotes( '' )}", // was acquired
352 "job_token_timestamp < {$dbw->addQuotes( $pruneCutoff )}" // stale
354 if ( $this->claimTTL
> 0 ) { // only prune jobs attempted too many times...
355 $conds[] = "job_attempts >= {$dbw->addQuotes( self::MAX_ATTEMPTS )}";
357 // Get the IDs of jobs that are considered stale and should be removed. Selecting
358 // the IDs first means that the UPDATE can be done by primary key (less deadlocks).
359 $res = $dbw->select( 'job', 'job_id', $conds, __METHOD__
);
360 $ids = array_map( function( $o ) { return $o->job_id
; }, iterator_to_array( $res ) );
361 if ( count( $ids ) ) {
362 $dbw->delete( 'job', array( 'job_id' => $ids ), __METHOD__
);
363 $count +
= $dbw->affectedRows();
366 $dbw->unlock( "jobqueue-recycle-{$this->type}", __METHOD__
);
372 * @see JobQueue::doAck()
374 * @throws MWException
377 protected function doAck( Job
$job ) {
378 if ( !$job->getId() ) {
379 throw new MWException( "Job of type '{$job->getType()}' has no ID." );
382 $dbw = $this->getMasterDB();
383 $dbw->commit( __METHOD__
, 'flush' ); // flush existing transaction
385 // Delete a row with a single DELETE without holding row locks over RTTs...
387 array( 'job_cmd' => $this->type
, 'job_id' => $job->getId() ), __METHOD__
);
393 * @see JobQueue::doDeduplicateRootJob()
395 * @throws MWException
398 protected function doDeduplicateRootJob( Job
$job ) {
399 $params = $job->getParams();
400 if ( !isset( $params['rootJobSignature'] ) ) {
401 throw new MWException( "Cannot register root job; missing 'rootJobSignature'." );
402 } elseif ( !isset( $params['rootJobTimestamp'] ) ) {
403 throw new MWException( "Cannot register root job; missing 'rootJobTimestamp'." );
405 $key = $this->getRootJobCacheKey( $params['rootJobSignature'] );
406 // Callers should call batchInsert() and then this function so that if the insert
407 // fails, the de-duplication registration will be aborted. Since the insert is
408 // deferred till "transaction idle", do that same here, so that the ordering is
409 // maintained. Having only the de-duplication registration succeed would cause
410 // jobs to become no-ops without any actual jobs that made them redundant.
411 $this->getMasterDB()->onTransactionIdle( function() use ( $params, $key ) {
414 $timestamp = $wgMemc->get( $key ); // current last timestamp of this job
415 if ( $timestamp && $timestamp >= $params['rootJobTimestamp'] ) {
416 return true; // a newer version of this root job was enqueued
419 // Update the timestamp of the last root job started at the location...
420 return $wgMemc->set( $key, $params['rootJobTimestamp'], 14*86400 ); // 2 weeks
427 * Check if the "root" job of a given job has been superseded by a newer one
432 protected function isRootJobOldDuplicate( Job
$job ) {
435 $params = $job->getParams();
436 if ( !isset( $params['rootJobSignature'] ) ) {
437 return false; // job has no de-deplication info
438 } elseif ( !isset( $params['rootJobTimestamp'] ) ) {
439 trigger_error( "Cannot check root job; missing 'rootJobTimestamp'." );
443 // Get the last time this root job was enqueued
444 $timestamp = $wgMemc->get( $this->getRootJobCacheKey( $params['rootJobSignature'] ) );
446 // Check if a new root job was started at the location after this one's...
447 return ( $timestamp && $timestamp > $params['rootJobTimestamp'] );
451 * @see JobQueue::doWaitForBackups()
454 protected function doWaitForBackups() {
459 * @return DatabaseBase
461 protected function getSlaveDB() {
462 return wfGetDB( DB_SLAVE
, array(), $this->wiki
);
466 * @return DatabaseBase
468 protected function getMasterDB() {
469 return wfGetDB( DB_MASTER
, array(), $this->wiki
);
476 protected function insertFields( Job
$job ) {
477 $dbw = $this->getMasterDB();
479 // Fields that describe the nature of the job
480 'job_cmd' => $job->getType(),
481 'job_namespace' => $job->getTitle()->getNamespace(),
482 'job_title' => $job->getTitle()->getDBkey(),
483 'job_params' => self
::makeBlob( $job->getParams() ),
484 // Additional job metadata
485 'job_id' => $dbw->nextSequenceValue( 'job_job_id_seq' ),
486 'job_timestamp' => $dbw->timestamp(),
487 'job_sha1' => wfBaseConvert(
488 sha1( serialize( $job->getDeduplicationInfo() ) ),
491 'job_random' => mt_rand( 0, self
::MAX_JOB_RANDOM
)
498 private function getEmptinessCacheKey() {
499 list( $db, $prefix ) = wfSplitWikiID( $this->wiki
);
500 return wfForeignMemcKey( $db, $prefix, 'jobqueue', $this->type
, 'isempty' );
504 * @param string $signature Hash identifier of the root job
507 private function getRootJobCacheKey( $signature ) {
508 list( $db, $prefix ) = wfSplitWikiID( $this->wiki
);
509 return wfForeignMemcKey( $db, $prefix, 'jobqueue', $this->type
, 'rootjob', $signature );
516 protected static function makeBlob( $params ) {
517 if ( $params !== false ) {
518 return serialize( $params );
528 protected static function extractBlob( $blob ) {
529 if ( (string)$blob !== '' ) {
530 return unserialize( $blob );