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 ROOTJOB_TTL
= 1209600; // integer; seconds to remember root jobs (14 days)
32 const CACHE_TTL_SHORT
= 30; // integer; seconds to cache info without re-validating
33 const CACHE_TTL_LONG
= 300; // integer; seconds to cache info that is kept up to date
34 const MAX_AGE_PRUNE
= 604800; // integer; seconds a job can live once claimed
35 const MAX_JOB_RANDOM
= 2147483647; // integer; 2^31 - 1, used for job_random
36 const MAX_OFFSET
= 255; // integer; maximum number of rows to skip
38 protected $cluster = false; // string; name of an external DB cluster
41 * Additional parameters include:
42 * - cluster : The name of an external cluster registered via LBFactory.
43 * If not specified, the primary DB cluster for the wiki will be used.
44 * This can be overridden with a custom cluster so that DB handles will
45 * be retrieved via LBFactory::getExternalLB() and getConnection().
46 * @param $params array
48 protected function __construct( array $params ) {
49 parent
::__construct( $params );
50 $this->cluster
= isset( $params['cluster'] ) ?
$params['cluster'] : false;
54 * @see JobQueue::doIsEmpty()
57 protected function doIsEmpty() {
60 $key = $this->getCacheKey( 'empty' );
62 $isEmpty = $wgMemc->get( $key );
63 if ( $isEmpty === 'true' ) {
65 } elseif ( $isEmpty === 'false' ) {
69 list( $dbr, $scope ) = $this->getSlaveDB();
70 $found = $dbr->selectField( // unclaimed job
71 'job', '1', array( 'job_cmd' => $this->type
, 'job_token' => '' ), __METHOD__
73 $wgMemc->add( $key, $found ?
'false' : 'true', self
::CACHE_TTL_LONG
);
79 * @see JobQueue::doGetSize()
82 protected function doGetSize() {
85 $key = $this->getCacheKey( 'size' );
87 $size = $wgMemc->get( $key );
88 if ( is_int( $size ) ) {
92 list( $dbr, $scope ) = $this->getSlaveDB();
93 $size = (int)$dbr->selectField( 'job', 'COUNT(*)',
94 array( 'job_cmd' => $this->type
, 'job_token' => '' ),
97 $wgMemc->set( $key, $size, self
::CACHE_TTL_SHORT
);
103 * @see JobQueue::doGetAcquiredCount()
106 protected function doGetAcquiredCount() {
109 if ( $this->claimTTL
<= 0 ) {
110 return 0; // no acknowledgements
113 $key = $this->getCacheKey( 'acquiredcount' );
115 $count = $wgMemc->get( $key );
116 if ( is_int( $count ) ) {
120 list( $dbr, $scope ) = $this->getSlaveDB();
121 $count = (int)$dbr->selectField( 'job', 'COUNT(*)',
122 array( 'job_cmd' => $this->type
, "job_token != {$dbr->addQuotes( '' )}" ),
125 $wgMemc->set( $key, $count, self
::CACHE_TTL_SHORT
);
131 * @see JobQueue::doBatchPush()
134 * @throws DBError|Exception
137 protected function doBatchPush( array $jobs, $flags ) {
138 if ( count( $jobs ) ) {
139 list( $dbw, $scope ) = $this->getMasterDB();
141 $rowSet = array(); // (sha1 => job) map for jobs that are de-duplicated
142 $rowList = array(); // list of jobs for jobs that are are not de-duplicated
144 foreach ( $jobs as $job ) {
145 $row = $this->insertFields( $job );
146 if ( $job->ignoreDuplicates() ) {
147 $rowSet[$row['job_sha1']] = $row;
153 $key = $this->getCacheKey( 'empty' );
154 $atomic = ( $flags & self
::QoS_Atomic
);
156 $dbw->onTransactionIdle(
157 function() use ( $dbw, $rowSet, $rowList, $atomic, $key, $scope
162 $dbw->begin( __METHOD__
); // wrap all the job additions in one transaction
165 // Strip out any duplicate jobs that are already in the queue...
166 if ( count( $rowSet ) ) {
167 $res = $dbw->select( 'job', 'job_sha1',
169 // No job_type condition since it's part of the job_sha1 hash
170 'job_sha1' => array_keys( $rowSet ),
171 'job_token' => '' // unclaimed
175 foreach ( $res as $row ) {
176 wfDebug( "Job with hash '{$row->job_sha1}' is a duplicate." );
177 unset( $rowSet[$row->job_sha1
] ); // already enqueued
180 // Build the full list of job rows to insert
181 $rows = array_merge( $rowList, array_values( $rowSet ) );
182 // Insert the job rows in chunks to avoid slave lag...
183 foreach ( array_chunk( $rows, 50 ) as $rowBatch ) {
184 $dbw->insert( 'job', $rowBatch, __METHOD__
);
186 wfIncrStats( 'job-insert', count( $rows ) );
187 wfIncrStats( 'job-insert-duplicate',
188 count( $rowSet ) +
count( $rowList ) - count( $rows ) );
189 } catch ( DBError
$e ) {
191 $dbw->rollback( __METHOD__
);
196 $dbw->commit( __METHOD__
);
199 $wgMemc->set( $key, 'false', JobQueueDB
::CACHE_TTL_LONG
);
207 * @see JobQueue::doPop()
210 protected function doPop() {
213 if ( $wgMemc->get( $this->getCacheKey( 'empty' ) ) === 'true' ) {
214 return false; // queue is empty
217 list( $dbw, $scope ) = $this->getMasterDB();
218 $dbw->commit( __METHOD__
, 'flush' ); // flush existing transaction
220 $uuid = wfRandomString( 32 ); // pop attempt
221 $job = false; // job popped off
222 do { // retry when our row is invalid or deleted as a duplicate
223 // Try to reserve a row in the DB...
224 if ( in_array( $this->order
, array( 'fifo', 'timestamp' ) ) ) {
225 $row = $this->claimOldest( $uuid );
226 } else { // random first
227 $rand = mt_rand( 0, self
::MAX_JOB_RANDOM
); // encourage concurrent UPDATEs
228 $gte = (bool)mt_rand( 0, 1 ); // find rows with rand before/after $rand
229 $row = $this->claimRandom( $uuid, $rand, $gte );
231 // Check if we found a row to reserve...
233 $wgMemc->set( $this->getCacheKey( 'empty' ), 'true', self
::CACHE_TTL_LONG
);
234 break; // nothing to do
236 wfIncrStats( 'job-pop' );
237 // Get the job object from the row...
238 $title = Title
::makeTitleSafe( $row->job_namespace
, $row->job_title
);
240 $dbw->delete( 'job', array( 'job_id' => $row->job_id
), __METHOD__
);
241 wfDebugLog( 'JobQueueDB', "Row has invalid title '{$row->job_title}'." );
242 continue; // try again
244 $job = Job
::factory( $row->job_cmd
, $title,
245 self
::extractBlob( $row->job_params
), $row->job_id
);
246 $job->id
= $row->job_id
; // XXX: work around broken subclasses
247 // Flag this job as an old duplicate based on its "root" job...
248 if ( $this->isRootJobOldDuplicate( $job ) ) {
249 wfIncrStats( 'job-pop-duplicate' );
250 $job = DuplicateJob
::newFromJob( $job ); // convert to a no-op
259 * Reserve a row with a single UPDATE without holding row locks over RTTs...
261 * @param $uuid string 32 char hex string
262 * @param $rand integer Random unsigned integer (31 bits)
263 * @param $gte bool Search for job_random >= $random (otherwise job_random <= $random)
266 protected function claimRandom( $uuid, $rand, $gte ) {
269 list( $dbw, $scope ) = $this->getMasterDB();
270 // Check cache to see if the queue has <= OFFSET items
271 $tinyQueue = $wgMemc->get( $this->getCacheKey( 'small' ) );
273 $row = false; // the row acquired
274 $invertedDirection = false; // whether one job_random direction was already scanned
275 // This uses a replication safe method for acquiring jobs. One could use UPDATE+LIMIT
276 // instead, but that either uses ORDER BY (in which case it deadlocks in MySQL) or is
277 // not replication safe. Due to http://bugs.mysql.com/bug.php?id=6980, subqueries cannot
278 // be used here with MySQL.
280 if ( $tinyQueue ) { // queue has <= MAX_OFFSET rows
281 // For small queues, using OFFSET will overshoot and return no rows more often.
282 // Instead, this uses job_random to pick a row (possibly checking both directions).
283 $ineq = $gte ?
'>=' : '<=';
284 $dir = $gte ?
'ASC' : 'DESC';
285 $row = $dbw->selectRow( 'job', '*', // find a random job
287 'job_cmd' => $this->type
,
288 'job_token' => '', // unclaimed
289 "job_random {$ineq} {$dbw->addQuotes( $rand )}" ),
291 array( 'ORDER BY' => "job_random {$dir}" )
293 if ( !$row && !$invertedDirection ) {
295 $invertedDirection = true;
296 continue; // try the other direction
298 } else { // table *may* have >= MAX_OFFSET rows
299 // Bug 42614: "ORDER BY job_random" with a job_random inequality causes high CPU
300 // in MySQL if there are many rows for some reason. This uses a small OFFSET
301 // instead of job_random for reducing excess claim retries.
302 $row = $dbw->selectRow( 'job', '*', // find a random job
304 'job_cmd' => $this->type
,
305 'job_token' => '', // unclaimed
308 array( 'OFFSET' => mt_rand( 0, self
::MAX_OFFSET
) )
311 $tinyQueue = true; // we know the queue must have <= MAX_OFFSET rows
312 $wgMemc->set( $this->getCacheKey( 'small' ), 1, 30 );
313 continue; // use job_random
316 if ( $row ) { // claim the job
317 $dbw->update( 'job', // update by PK
319 'job_token' => $uuid,
320 'job_token_timestamp' => $dbw->timestamp(),
321 'job_attempts = job_attempts+1' ),
322 array( 'job_cmd' => $this->type
, 'job_id' => $row->job_id
, 'job_token' => '' ),
325 // This might get raced out by another runner when claiming the previously
326 // selected row. The use of job_random should minimize this problem, however.
327 if ( !$dbw->affectedRows() ) {
328 $row = false; // raced out
331 break; // nothing to do
339 * Reserve a row with a single UPDATE without holding row locks over RTTs...
341 * @param $uuid string 32 char hex string
344 protected function claimOldest( $uuid ) {
345 list( $dbw, $scope ) = $this->getMasterDB();
347 $row = false; // the row acquired
349 if ( $dbw->getType() === 'mysql' ) {
350 // Per http://bugs.mysql.com/bug.php?id=6980, we can't use subqueries on the
351 // same table being changed in an UPDATE query in MySQL (gives Error: 1093).
352 // Oracle and Postgre have no such limitation. However, MySQL offers an
353 // alternative here by supporting ORDER BY + LIMIT for UPDATE queries.
354 $dbw->query( "UPDATE {$dbw->tableName( 'job' )} " .
356 "job_token = {$dbw->addQuotes( $uuid ) }, " .
357 "job_token_timestamp = {$dbw->addQuotes( $dbw->timestamp() )}, " .
358 "job_attempts = job_attempts+1 " .
360 "job_cmd = {$dbw->addQuotes( $this->type )} " .
361 "AND job_token = {$dbw->addQuotes( '' )} " .
362 ") ORDER BY job_id ASC LIMIT 1",
366 // Use a subquery to find the job, within an UPDATE to claim it.
367 // This uses as much of the DB wrapper functions as possible.
370 'job_token' => $uuid,
371 'job_token_timestamp' => $dbw->timestamp(),
372 'job_attempts = job_attempts+1' ),
373 array( 'job_id = (' .
374 $dbw->selectSQLText( 'job', 'job_id',
375 array( 'job_cmd' => $this->type
, 'job_token' => '' ),
377 array( 'ORDER BY' => 'job_id ASC', 'LIMIT' => 1 ) ) .
383 // Fetch any row that we just reserved...
384 if ( $dbw->affectedRows() ) {
385 $row = $dbw->selectRow( 'job', '*',
386 array( 'job_cmd' => $this->type
, 'job_token' => $uuid ), __METHOD__
388 if ( !$row ) { // raced out by duplicate job removal
389 wfDebugLog( 'JobQueueDB', "Row deleted as duplicate by another process." );
392 break; // nothing to do
400 * Recycle or destroy any jobs that have been claimed for too long
402 * @return integer Number of jobs recycled/deleted
404 public function recycleAndDeleteStaleJobs() {
408 list( $dbw, $scope ) = $this->getMasterDB();
409 $count = 0; // affected rows
411 if ( !$dbw->lock( "jobqueue-recycle-{$this->type}", __METHOD__
, 1 ) ) {
412 return $count; // already in progress
415 // Remove claims on jobs acquired for too long if enabled...
416 if ( $this->claimTTL
> 0 ) {
417 $claimCutoff = $dbw->timestamp( $now - $this->claimTTL
);
418 // Get the IDs of jobs that have be claimed but not finished after too long.
419 // These jobs can be recycled into the queue by expiring the claim. Selecting
420 // the IDs first means that the UPDATE can be done by primary key (less deadlocks).
421 $res = $dbw->select( 'job', 'job_id',
423 'job_cmd' => $this->type
,
424 "job_token != {$dbw->addQuotes( '' )}", // was acquired
425 "job_token_timestamp < {$dbw->addQuotes( $claimCutoff )}", // stale
426 "job_attempts < {$dbw->addQuotes( $this->maxTries )}" ), // retries left
429 $ids = array_map( function( $o ) { return $o->job_id
; }, iterator_to_array( $res ) );
430 if ( count( $ids ) ) {
431 // Reset job_token for these jobs so that other runners will pick them up.
432 // Set the timestamp to the current time, as it is useful to now that the job
433 // was already tried before (the timestamp becomes the "released" time).
437 'job_token_timestamp' => $dbw->timestamp( $now ) ), // time of release
442 $count +
= $dbw->affectedRows();
443 wfIncrStats( 'job-recycle', $dbw->affectedRows() );
444 $wgMemc->set( $this->getCacheKey( 'empty' ), 'false', self
::CACHE_TTL_LONG
);
448 // Just destroy any stale jobs...
449 $pruneCutoff = $dbw->timestamp( $now - self
::MAX_AGE_PRUNE
);
451 'job_cmd' => $this->type
,
452 "job_token != {$dbw->addQuotes( '' )}", // was acquired
453 "job_token_timestamp < {$dbw->addQuotes( $pruneCutoff )}" // stale
455 if ( $this->claimTTL
> 0 ) { // only prune jobs attempted too many times...
456 $conds[] = "job_attempts >= {$dbw->addQuotes( $this->maxTries )}";
458 // Get the IDs of jobs that are considered stale and should be removed. Selecting
459 // the IDs first means that the UPDATE can be done by primary key (less deadlocks).
460 $res = $dbw->select( 'job', 'job_id', $conds, __METHOD__
);
461 $ids = array_map( function( $o ) { return $o->job_id
; }, iterator_to_array( $res ) );
462 if ( count( $ids ) ) {
463 $dbw->delete( 'job', array( 'job_id' => $ids ), __METHOD__
);
464 $count +
= $dbw->affectedRows();
467 $dbw->unlock( "jobqueue-recycle-{$this->type}", __METHOD__
);
473 * @see JobQueue::doAck()
475 * @throws MWException
478 protected function doAck( Job
$job ) {
479 if ( !$job->getId() ) {
480 throw new MWException( "Job of type '{$job->getType()}' has no ID." );
483 list( $dbw, $scope ) = $this->getMasterDB();
484 $dbw->commit( __METHOD__
, 'flush' ); // flush existing transaction
486 // Delete a row with a single DELETE without holding row locks over RTTs...
488 array( 'job_cmd' => $this->type
, 'job_id' => $job->getId() ), __METHOD__
);
494 * @see JobQueue::doDeduplicateRootJob()
496 * @throws MWException
499 protected function doDeduplicateRootJob( Job
$job ) {
500 $params = $job->getParams();
501 if ( !isset( $params['rootJobSignature'] ) ) {
502 throw new MWException( "Cannot register root job; missing 'rootJobSignature'." );
503 } elseif ( !isset( $params['rootJobTimestamp'] ) ) {
504 throw new MWException( "Cannot register root job; missing 'rootJobTimestamp'." );
506 $key = $this->getRootJobCacheKey( $params['rootJobSignature'] );
507 // Callers should call batchInsert() and then this function so that if the insert
508 // fails, the de-duplication registration will be aborted. Since the insert is
509 // deferred till "transaction idle", do the same here, so that the ordering is
510 // maintained. Having only the de-duplication registration succeed would cause
511 // jobs to become no-ops without any actual jobs that made them redundant.
512 list( $dbw, $scope ) = $this->getMasterDB();
513 $dbw->onTransactionIdle( function() use ( $params, $key, $scope ) {
516 $timestamp = $wgMemc->get( $key ); // current last timestamp of this job
517 if ( $timestamp && $timestamp >= $params['rootJobTimestamp'] ) {
518 return true; // a newer version of this root job was enqueued
521 // Update the timestamp of the last root job started at the location...
522 return $wgMemc->set( $key, $params['rootJobTimestamp'], JobQueueDB
::ROOTJOB_TTL
);
529 * Check if the "root" job of a given job has been superseded by a newer one
534 protected function isRootJobOldDuplicate( Job
$job ) {
537 $params = $job->getParams();
538 if ( !isset( $params['rootJobSignature'] ) ) {
539 return false; // job has no de-deplication info
540 } elseif ( !isset( $params['rootJobTimestamp'] ) ) {
541 trigger_error( "Cannot check root job; missing 'rootJobTimestamp'." );
545 // Get the last time this root job was enqueued
546 $timestamp = $wgMemc->get( $this->getRootJobCacheKey( $params['rootJobSignature'] ) );
548 // Check if a new root job was started at the location after this one's...
549 return ( $timestamp && $timestamp > $params['rootJobTimestamp'] );
553 * @see JobQueue::doWaitForBackups()
556 protected function doWaitForBackups() {
563 protected function doGetPeriodicTasks() {
565 'recycleAndDeleteStaleJobs' => array(
566 'callback' => array( $this, 'recycleAndDeleteStaleJobs' ),
567 'period' => ceil( $this->claimTTL
/ 2 )
575 protected function doFlushCaches() {
578 foreach ( array( 'empty', 'size', 'acquiredcount' ) as $type ) {
579 $wgMemc->delete( $this->getCacheKey( $type ) );
584 * @return Array (DatabaseBase, ScopedCallback)
586 protected function getSlaveDB() {
587 return $this->getDB( DB_SLAVE
);
591 * @return Array (DatabaseBase, ScopedCallback)
593 protected function getMasterDB() {
594 return $this->getDB( DB_MASTER
);
598 * @param $index integer (DB_SLAVE/DB_MASTER)
599 * @return Array (DatabaseBase, ScopedCallback)
601 protected function getDB( $index ) {
602 $lb = ( $this->cluster
!== false )
603 ?
wfGetLBFactory()->getExternalLB( $this->cluster
, $this->wiki
)
604 : wfGetLB( $this->wiki
);
605 $conn = $lb->getConnection( $index, array(), $this->wiki
);
608 new ScopedCallback( function() use ( $lb, $conn ) {
609 $lb->reuseConnection( $conn );
618 protected function insertFields( Job
$job ) {
619 list( $dbw, $scope ) = $this->getMasterDB();
621 // Fields that describe the nature of the job
622 'job_cmd' => $job->getType(),
623 'job_namespace' => $job->getTitle()->getNamespace(),
624 'job_title' => $job->getTitle()->getDBkey(),
625 'job_params' => self
::makeBlob( $job->getParams() ),
626 // Additional job metadata
627 'job_id' => $dbw->nextSequenceValue( 'job_job_id_seq' ),
628 'job_timestamp' => $dbw->timestamp(),
629 'job_sha1' => wfBaseConvert(
630 sha1( serialize( $job->getDeduplicationInfo() ) ),
633 'job_random' => mt_rand( 0, self
::MAX_JOB_RANDOM
)
640 private function getCacheKey( $property ) {
641 list( $db, $prefix ) = wfSplitWikiID( $this->wiki
);
642 return wfForeignMemcKey( $db, $prefix, 'jobqueue', $this->type
, $property );
646 * @param string $signature Hash identifier of the root job
649 private function getRootJobCacheKey( $signature ) {
650 list( $db, $prefix ) = wfSplitWikiID( $this->wiki
);
651 return wfForeignMemcKey( $db, $prefix, 'jobqueue', $this->type
, 'rootjob', $signature );
658 protected static function makeBlob( $params ) {
659 if ( $params !== false ) {
660 return serialize( $params );
670 protected static function extractBlob( $blob ) {
671 if ( (string)$blob !== '' ) {
672 return unserialize( $blob );