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_SHORT
= 30; // integer; seconds to cache info without re-validating
32 const CACHE_TTL_LONG
= 300; // integer; seconds to cache info that is kept up to date
33 const MAX_AGE_PRUNE
= 604800; // integer; seconds a job can live once claimed
34 const MAX_JOB_RANDOM
= 2147483647; // integer; 2^31 - 1, used for job_random
35 const MAX_OFFSET
= 255; // integer; maximum number of rows to skip
37 protected $cluster = false; // string; name of an external DB cluster
40 * Additional parameters include:
41 * - cluster : The name of an external cluster registered via LBFactory.
42 * If not specified, the primary DB cluster for the wiki will be used.
43 * This can be overridden with a custom cluster so that DB handles will
44 * be retrieved via LBFactory::getExternalLB() and getConnection().
45 * @param $params array
47 protected function __construct( array $params ) {
48 parent
::__construct( $params );
49 $this->cluster
= isset( $params['cluster'] ) ?
$params['cluster'] : false;
52 protected function supportedOrders() {
53 return array( 'random', 'timestamp', 'fifo' );
56 protected function optimalOrder() {
61 * @see JobQueue::doIsEmpty()
64 protected function doIsEmpty() {
67 $key = $this->getCacheKey( 'empty' );
69 $isEmpty = $wgMemc->get( $key );
70 if ( $isEmpty === 'true' ) {
72 } elseif ( $isEmpty === 'false' ) {
76 list( $dbr, $scope ) = $this->getSlaveDB();
77 $found = $dbr->selectField( // unclaimed job
78 'job', '1', array( 'job_cmd' => $this->type
, 'job_token' => '' ), __METHOD__
80 $wgMemc->add( $key, $found ?
'false' : 'true', self
::CACHE_TTL_LONG
);
86 * @see JobQueue::doGetSize()
89 protected function doGetSize() {
92 $key = $this->getCacheKey( 'size' );
94 $size = $wgMemc->get( $key );
95 if ( is_int( $size ) ) {
99 list( $dbr, $scope ) = $this->getSlaveDB();
100 $size = (int)$dbr->selectField( 'job', 'COUNT(*)',
101 array( 'job_cmd' => $this->type
, 'job_token' => '' ),
104 $wgMemc->set( $key, $size, self
::CACHE_TTL_SHORT
);
110 * @see JobQueue::doGetAcquiredCount()
113 protected function doGetAcquiredCount() {
116 if ( $this->claimTTL
<= 0 ) {
117 return 0; // no acknowledgements
120 $key = $this->getCacheKey( 'acquiredcount' );
122 $count = $wgMemc->get( $key );
123 if ( is_int( $count ) ) {
127 list( $dbr, $scope ) = $this->getSlaveDB();
128 $count = (int)$dbr->selectField( 'job', 'COUNT(*)',
129 array( 'job_cmd' => $this->type
, "job_token != {$dbr->addQuotes( '' )}" ),
132 $wgMemc->set( $key, $count, self
::CACHE_TTL_SHORT
);
138 * @see JobQueue::doBatchPush()
141 * @throws DBError|Exception
144 protected function doBatchPush( array $jobs, $flags ) {
145 if ( count( $jobs ) ) {
146 list( $dbw, $scope ) = $this->getMasterDB();
148 $rowSet = array(); // (sha1 => job) map for jobs that are de-duplicated
149 $rowList = array(); // list of jobs for jobs that are are not de-duplicated
151 foreach ( $jobs as $job ) {
152 $row = $this->insertFields( $job );
153 if ( $job->ignoreDuplicates() ) {
154 $rowSet[$row['job_sha1']] = $row;
160 $key = $this->getCacheKey( 'empty' );
161 $atomic = ( $flags & self
::QoS_Atomic
);
163 $dbw->onTransactionIdle(
164 function() use ( $dbw, $rowSet, $rowList, $atomic, $key, $scope
169 $dbw->begin( __METHOD__
); // wrap all the job additions in one transaction
172 // Strip out any duplicate jobs that are already in the queue...
173 if ( count( $rowSet ) ) {
174 $res = $dbw->select( 'job', 'job_sha1',
176 // No job_type condition since it's part of the job_sha1 hash
177 'job_sha1' => array_keys( $rowSet ),
178 'job_token' => '' // unclaimed
182 foreach ( $res as $row ) {
183 wfDebug( "Job with hash '{$row->job_sha1}' is a duplicate." );
184 unset( $rowSet[$row->job_sha1
] ); // already enqueued
187 // Build the full list of job rows to insert
188 $rows = array_merge( $rowList, array_values( $rowSet ) );
189 // Insert the job rows in chunks to avoid slave lag...
190 foreach ( array_chunk( $rows, 50 ) as $rowBatch ) {
191 $dbw->insert( 'job', $rowBatch, __METHOD__
);
193 wfIncrStats( 'job-insert', count( $rows ) );
194 wfIncrStats( 'job-insert-duplicate',
195 count( $rowSet ) +
count( $rowList ) - count( $rows ) );
196 } catch ( DBError
$e ) {
198 $dbw->rollback( __METHOD__
);
203 $dbw->commit( __METHOD__
);
206 $wgMemc->set( $key, 'false', JobQueueDB
::CACHE_TTL_LONG
);
214 * @see JobQueue::doPop()
217 protected function doPop() {
220 if ( $wgMemc->get( $this->getCacheKey( 'empty' ) ) === 'true' ) {
221 return false; // queue is empty
224 list( $dbw, $scope ) = $this->getMasterDB();
225 $dbw->commit( __METHOD__
, 'flush' ); // flush existing transaction
227 $uuid = wfRandomString( 32 ); // pop attempt
228 $job = false; // job popped off
229 do { // retry when our row is invalid or deleted as a duplicate
230 // Try to reserve a row in the DB...
231 if ( in_array( $this->order
, array( 'fifo', 'timestamp' ) ) ) {
232 $row = $this->claimOldest( $uuid );
233 } else { // random first
234 $rand = mt_rand( 0, self
::MAX_JOB_RANDOM
); // encourage concurrent UPDATEs
235 $gte = (bool)mt_rand( 0, 1 ); // find rows with rand before/after $rand
236 $row = $this->claimRandom( $uuid, $rand, $gte );
238 // Check if we found a row to reserve...
240 $wgMemc->set( $this->getCacheKey( 'empty' ), 'true', self
::CACHE_TTL_LONG
);
241 break; // nothing to do
243 wfIncrStats( 'job-pop' );
244 // Get the job object from the row...
245 $title = Title
::makeTitleSafe( $row->job_namespace
, $row->job_title
);
247 $dbw->delete( 'job', array( 'job_id' => $row->job_id
), __METHOD__
);
248 wfDebugLog( 'JobQueueDB', "Row has invalid title '{$row->job_title}'." );
249 continue; // try again
251 $job = Job
::factory( $row->job_cmd
, $title,
252 self
::extractBlob( $row->job_params
), $row->job_id
);
253 $job->id
= $row->job_id
; // XXX: work around broken subclasses
261 * Reserve a row with a single UPDATE without holding row locks over RTTs...
263 * @param string $uuid 32 char hex string
264 * @param $rand integer Random unsigned integer (31 bits)
265 * @param bool $gte Search for job_random >= $random (otherwise job_random <= $random)
268 protected function claimRandom( $uuid, $rand, $gte ) {
271 list( $dbw, $scope ) = $this->getMasterDB();
272 // Check cache to see if the queue has <= OFFSET items
273 $tinyQueue = $wgMemc->get( $this->getCacheKey( 'small' ) );
275 $row = false; // the row acquired
276 $invertedDirection = false; // whether one job_random direction was already scanned
277 // This uses a replication safe method for acquiring jobs. One could use UPDATE+LIMIT
278 // instead, but that either uses ORDER BY (in which case it deadlocks in MySQL) or is
279 // not replication safe. Due to http://bugs.mysql.com/bug.php?id=6980, subqueries cannot
280 // be used here with MySQL.
282 if ( $tinyQueue ) { // queue has <= MAX_OFFSET rows
283 // For small queues, using OFFSET will overshoot and return no rows more often.
284 // Instead, this uses job_random to pick a row (possibly checking both directions).
285 $ineq = $gte ?
'>=' : '<=';
286 $dir = $gte ?
'ASC' : 'DESC';
287 $row = $dbw->selectRow( 'job', '*', // find a random job
289 'job_cmd' => $this->type
,
290 'job_token' => '', // unclaimed
291 "job_random {$ineq} {$dbw->addQuotes( $rand )}" ),
293 array( 'ORDER BY' => "job_random {$dir}" )
295 if ( !$row && !$invertedDirection ) {
297 $invertedDirection = true;
298 continue; // try the other direction
300 } else { // table *may* have >= MAX_OFFSET rows
301 // Bug 42614: "ORDER BY job_random" with a job_random inequality causes high CPU
302 // in MySQL if there are many rows for some reason. This uses a small OFFSET
303 // instead of job_random for reducing excess claim retries.
304 $row = $dbw->selectRow( 'job', '*', // find a random job
306 'job_cmd' => $this->type
,
307 'job_token' => '', // unclaimed
310 array( 'OFFSET' => mt_rand( 0, self
::MAX_OFFSET
) )
313 $tinyQueue = true; // we know the queue must have <= MAX_OFFSET rows
314 $wgMemc->set( $this->getCacheKey( 'small' ), 1, 30 );
315 continue; // use job_random
318 if ( $row ) { // claim the job
319 $dbw->update( 'job', // update by PK
321 'job_token' => $uuid,
322 'job_token_timestamp' => $dbw->timestamp(),
323 'job_attempts = job_attempts+1' ),
324 array( 'job_cmd' => $this->type
, 'job_id' => $row->job_id
, 'job_token' => '' ),
327 // This might get raced out by another runner when claiming the previously
328 // selected row. The use of job_random should minimize this problem, however.
329 if ( !$dbw->affectedRows() ) {
330 $row = false; // raced out
333 break; // nothing to do
341 * Reserve a row with a single UPDATE without holding row locks over RTTs...
343 * @param string $uuid 32 char hex string
346 protected function claimOldest( $uuid ) {
347 list( $dbw, $scope ) = $this->getMasterDB();
349 $row = false; // the row acquired
351 if ( $dbw->getType() === 'mysql' ) {
352 // Per http://bugs.mysql.com/bug.php?id=6980, we can't use subqueries on the
353 // same table being changed in an UPDATE query in MySQL (gives Error: 1093).
354 // Oracle and Postgre have no such limitation. However, MySQL offers an
355 // alternative here by supporting ORDER BY + LIMIT for UPDATE queries.
356 $dbw->query( "UPDATE {$dbw->tableName( 'job' )} " .
358 "job_token = {$dbw->addQuotes( $uuid ) }, " .
359 "job_token_timestamp = {$dbw->addQuotes( $dbw->timestamp() )}, " .
360 "job_attempts = job_attempts+1 " .
362 "job_cmd = {$dbw->addQuotes( $this->type )} " .
363 "AND job_token = {$dbw->addQuotes( '' )} " .
364 ") ORDER BY job_id ASC LIMIT 1",
368 // Use a subquery to find the job, within an UPDATE to claim it.
369 // This uses as much of the DB wrapper functions as possible.
372 'job_token' => $uuid,
373 'job_token_timestamp' => $dbw->timestamp(),
374 'job_attempts = job_attempts+1' ),
375 array( 'job_id = (' .
376 $dbw->selectSQLText( 'job', 'job_id',
377 array( 'job_cmd' => $this->type
, 'job_token' => '' ),
379 array( 'ORDER BY' => 'job_id ASC', 'LIMIT' => 1 ) ) .
385 // Fetch any row that we just reserved...
386 if ( $dbw->affectedRows() ) {
387 $row = $dbw->selectRow( 'job', '*',
388 array( 'job_cmd' => $this->type
, 'job_token' => $uuid ), __METHOD__
390 if ( !$row ) { // raced out by duplicate job removal
391 wfDebugLog( 'JobQueueDB', "Row deleted as duplicate by another process." );
394 break; // nothing to do
402 * Recycle or destroy any jobs that have been claimed for too long
404 * @return integer Number of jobs recycled/deleted
406 public function recycleAndDeleteStaleJobs() {
410 list( $dbw, $scope ) = $this->getMasterDB();
411 $count = 0; // affected rows
413 if ( !$dbw->lock( "jobqueue-recycle-{$this->type}", __METHOD__
, 1 ) ) {
414 return $count; // already in progress
417 // Remove claims on jobs acquired for too long if enabled...
418 if ( $this->claimTTL
> 0 ) {
419 $claimCutoff = $dbw->timestamp( $now - $this->claimTTL
);
420 // Get the IDs of jobs that have be claimed but not finished after too long.
421 // These jobs can be recycled into the queue by expiring the claim. Selecting
422 // the IDs first means that the UPDATE can be done by primary key (less deadlocks).
423 $res = $dbw->select( 'job', 'job_id',
425 'job_cmd' => $this->type
,
426 "job_token != {$dbw->addQuotes( '' )}", // was acquired
427 "job_token_timestamp < {$dbw->addQuotes( $claimCutoff )}", // stale
428 "job_attempts < {$dbw->addQuotes( $this->maxTries )}" ), // retries left
431 $ids = array_map( function( $o ) { return $o->job_id
; }, iterator_to_array( $res ) );
432 if ( count( $ids ) ) {
433 // Reset job_token for these jobs so that other runners will pick them up.
434 // Set the timestamp to the current time, as it is useful to now that the job
435 // was already tried before (the timestamp becomes the "released" time).
439 'job_token_timestamp' => $dbw->timestamp( $now ) ), // time of release
444 $count +
= $dbw->affectedRows();
445 wfIncrStats( 'job-recycle', $dbw->affectedRows() );
446 $wgMemc->set( $this->getCacheKey( 'empty' ), 'false', self
::CACHE_TTL_LONG
);
450 // Just destroy any stale jobs...
451 $pruneCutoff = $dbw->timestamp( $now - self
::MAX_AGE_PRUNE
);
453 'job_cmd' => $this->type
,
454 "job_token != {$dbw->addQuotes( '' )}", // was acquired
455 "job_token_timestamp < {$dbw->addQuotes( $pruneCutoff )}" // stale
457 if ( $this->claimTTL
> 0 ) { // only prune jobs attempted too many times...
458 $conds[] = "job_attempts >= {$dbw->addQuotes( $this->maxTries )}";
460 // Get the IDs of jobs that are considered stale and should be removed. Selecting
461 // the IDs first means that the UPDATE can be done by primary key (less deadlocks).
462 $res = $dbw->select( 'job', 'job_id', $conds, __METHOD__
);
463 $ids = array_map( function( $o ) { return $o->job_id
; }, iterator_to_array( $res ) );
464 if ( count( $ids ) ) {
465 $dbw->delete( 'job', array( 'job_id' => $ids ), __METHOD__
);
466 $count +
= $dbw->affectedRows();
469 $dbw->unlock( "jobqueue-recycle-{$this->type}", __METHOD__
);
475 * @see JobQueue::doAck()
477 * @throws MWException
480 protected function doAck( Job
$job ) {
481 if ( !$job->getId() ) {
482 throw new MWException( "Job of type '{$job->getType()}' has no ID." );
485 list( $dbw, $scope ) = $this->getMasterDB();
486 $dbw->commit( __METHOD__
, 'flush' ); // flush existing transaction
488 // Delete a row with a single DELETE without holding row locks over RTTs...
490 array( 'job_cmd' => $this->type
, 'job_id' => $job->getId() ), __METHOD__
);
496 * @see JobQueue::doDeduplicateRootJob()
498 * @throws MWException
501 protected function doDeduplicateRootJob( Job
$job ) {
502 $params = $job->getParams();
503 if ( !isset( $params['rootJobSignature'] ) ) {
504 throw new MWException( "Cannot register root job; missing 'rootJobSignature'." );
505 } elseif ( !isset( $params['rootJobTimestamp'] ) ) {
506 throw new MWException( "Cannot register root job; missing 'rootJobTimestamp'." );
508 $key = $this->getRootJobCacheKey( $params['rootJobSignature'] );
509 // Callers should call batchInsert() and then this function so that if the insert
510 // fails, the de-duplication registration will be aborted. Since the insert is
511 // deferred till "transaction idle", do the same here, so that the ordering is
512 // maintained. Having only the de-duplication registration succeed would cause
513 // jobs to become no-ops without any actual jobs that made them redundant.
514 list( $dbw, $scope ) = $this->getMasterDB();
515 $dbw->onTransactionIdle( function() use ( $params, $key, $scope ) {
518 $timestamp = $wgMemc->get( $key ); // current last timestamp of this job
519 if ( $timestamp && $timestamp >= $params['rootJobTimestamp'] ) {
520 return true; // a newer version of this root job was enqueued
523 // Update the timestamp of the last root job started at the location...
524 return $wgMemc->set( $key, $params['rootJobTimestamp'], JobQueueDB
::ROOTJOB_TTL
);
531 * @see JobQueue::doWaitForBackups()
534 protected function doWaitForBackups() {
541 protected function doGetPeriodicTasks() {
543 'recycleAndDeleteStaleJobs' => array(
544 'callback' => array( $this, 'recycleAndDeleteStaleJobs' ),
545 'period' => ceil( $this->claimTTL
/ 2 )
553 protected function doFlushCaches() {
556 foreach ( array( 'empty', 'size', 'acquiredcount' ) as $type ) {
557 $wgMemc->delete( $this->getCacheKey( $type ) );
562 * @see JobQueue::getAllQueuedJobs()
565 public function getAllQueuedJobs() {
566 list( $dbr, $scope ) = $this->getSlaveDB();
567 return new MappedIterator(
568 $dbr->select( 'job', '*', array( 'job_cmd' => $this->getType(), 'job_token' => '' ) ),
569 function( $row ) use ( $scope ) {
572 Title
::makeTitle( $row->job_namespace
, $row->job_title
),
573 strlen( $row->job_params
) ?
unserialize( $row->job_params
) : false,
576 $job->id
= $row->job_id
; // XXX: work around broken subclasses
583 * @return Array (DatabaseBase, ScopedCallback)
585 protected function getSlaveDB() {
586 return $this->getDB( DB_SLAVE
);
590 * @return Array (DatabaseBase, ScopedCallback)
592 protected function getMasterDB() {
593 return $this->getDB( DB_MASTER
);
597 * @param $index integer (DB_SLAVE/DB_MASTER)
598 * @return Array (DatabaseBase, ScopedCallback)
600 protected function getDB( $index ) {
601 $lb = ( $this->cluster
!== false )
602 ?
wfGetLBFactory()->getExternalLB( $this->cluster
, $this->wiki
)
603 : wfGetLB( $this->wiki
);
604 $conn = $lb->getConnection( $index, array(), $this->wiki
);
607 new ScopedCallback( function() use ( $lb, $conn ) {
608 $lb->reuseConnection( $conn );
617 protected function insertFields( Job
$job ) {
618 list( $dbw, $scope ) = $this->getMasterDB();
620 // Fields that describe the nature of the job
621 'job_cmd' => $job->getType(),
622 'job_namespace' => $job->getTitle()->getNamespace(),
623 'job_title' => $job->getTitle()->getDBkey(),
624 'job_params' => self
::makeBlob( $job->getParams() ),
625 // Additional job metadata
626 'job_id' => $dbw->nextSequenceValue( 'job_job_id_seq' ),
627 'job_timestamp' => $dbw->timestamp(),
628 'job_sha1' => wfBaseConvert(
629 sha1( serialize( $job->getDeduplicationInfo() ) ),
632 'job_random' => mt_rand( 0, self
::MAX_JOB_RANDOM
)
639 private function getCacheKey( $property ) {
640 list( $db, $prefix ) = wfSplitWikiID( $this->wiki
);
641 return wfForeignMemcKey( $db, $prefix, 'jobqueue', $this->type
, $property );
648 protected static function makeBlob( $params ) {
649 if ( $params !== false ) {
650 return serialize( $params );
660 protected static function extractBlob( $blob ) {
661 if ( (string)$blob !== '' ) {
662 return unserialize( $blob );