7f4300ca333ba6ba5ec2d0df501d3d4220f27a5e
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_ATTEMPTS
= 3; // integer; number of times to try a job
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 $dbr = $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 $key = $this->getCacheKey( 'acquiredcount' );
111 $count = $wgMemc->get( $key );
112 if ( is_int( $count ) ) {
116 $dbr = $this->getSlaveDB();
117 $count = (int)$dbr->selectField( 'job', 'COUNT(*)',
118 array( 'job_cmd' => $this->type
, "job_token !={$dbr->addQuotes('')}" ),
121 $wgMemc->set( $key, $count, self
::CACHE_TTL_SHORT
);
127 * @see JobQueue::doBatchPush()
130 * @throws DBError|Exception
133 protected function doBatchPush( array $jobs, $flags ) {
134 if ( count( $jobs ) ) {
135 list( $dbw, $scope ) = $this->getMasterDB();
137 $rowSet = array(); // (sha1 => job) map for jobs that are de-duplicated
138 $rowList = array(); // list of jobs for jobs that are are not de-duplicated
140 foreach ( $jobs as $job ) {
141 $row = $this->insertFields( $job );
142 if ( $job->ignoreDuplicates() ) {
143 $rowSet[$row['job_sha1']] = $row;
149 $atomic = ( $flags & self
::QoS_Atomic
);
150 $key = $this->getCacheKey( 'empty' );
151 $ttl = self
::CACHE_TTL_LONG
;
153 $dbw->onTransactionIdle(
154 function() use ( $dbw, $rowSet, $rowList, $atomic, $key, $ttl, $scope
159 $dbw->begin( __METHOD__
); // wrap all the job additions in one transaction
162 // Strip out any duplicate jobs that are already in the queue...
163 if ( count( $rowSet ) ) {
164 $res = $dbw->select( 'job', 'job_sha1',
166 // No job_type condition since it's part of the job_sha1 hash
167 'job_sha1' => array_keys( $rowSet ),
168 'job_token' => '' // unclaimed
172 foreach ( $res as $row ) {
173 wfDebug( "Job with hash '{$row->job_sha1}' is a duplicate." );
174 unset( $rowSet[$row->job_sha1
] ); // already enqueued
177 // Build the full list of job rows to insert
178 $rows = array_merge( $rowList, array_values( $rowSet ) );
179 // Insert the job rows in chunks to avoid slave lag...
180 foreach ( array_chunk( $rows, 50 ) as $rowBatch ) {
181 $dbw->insert( 'job', $rowBatch, __METHOD__
);
183 wfIncrStats( 'job-insert', count( $rows ) );
184 } catch ( DBError
$e ) {
186 $dbw->rollback( __METHOD__
);
191 $dbw->commit( __METHOD__
);
194 $wgMemc->set( $key, 'false', $ttl ); // queue is not empty
202 * @see JobQueue::doPop()
205 protected function doPop() {
208 if ( $wgMemc->get( $this->getCacheKey( 'empty' ) ) === 'true' ) {
209 return false; // queue is empty
212 list( $dbw, $scope ) = $this->getMasterDB();
213 $dbw->commit( __METHOD__
, 'flush' ); // flush existing transaction
215 $uuid = wfRandomString( 32 ); // pop attempt
216 $job = false; // job popped off
217 // Occasionally recycle jobs back into the queue that have been claimed too long
218 if ( mt_rand( 0, 99 ) == 0 ) {
219 $this->recycleStaleJobs();
221 do { // retry when our row is invalid or deleted as a duplicate
222 // Try to reserve a row in the DB...
223 if ( in_array( $this->order
, array( 'fifo', 'timestamp' ) ) ) {
224 $row = $this->claimOldest( $uuid );
225 } else { // random first
226 $rand = mt_rand( 0, self
::MAX_JOB_RANDOM
); // encourage concurrent UPDATEs
227 $gte = (bool)mt_rand( 0, 1 ); // find rows with rand before/after $rand
228 $row = $this->claimRandom( $uuid, $rand, $gte );
230 // Check if we found a row to reserve...
232 $wgMemc->set( $this->getCacheKey( 'empty' ), 'true', self
::CACHE_TTL_LONG
);
233 break; // nothing to do
235 wfIncrStats( 'job-pop' );
236 // Get the job object from the row...
237 $title = Title
::makeTitleSafe( $row->job_namespace
, $row->job_title
);
239 $dbw->delete( 'job', array( 'job_id' => $row->job_id
), __METHOD__
);
240 wfDebugLog( 'JobQueueDB', "Row has invalid title '{$row->job_title}'." );
241 continue; // try again
243 $job = Job
::factory( $row->job_cmd
, $title,
244 self
::extractBlob( $row->job_params
), $row->job_id
);
245 $job->id
= $row->job_id
; // XXX: work around broken subclasses
246 // Flag this job as an old duplicate based on its "root" job...
247 if ( $this->isRootJobOldDuplicate( $job ) ) {
248 wfIncrStats( 'job-duplicate' );
249 $job = DuplicateJob
::newFromJob( $job ); // convert to a no-op
258 * Reserve a row with a single UPDATE without holding row locks over RTTs...
260 * @param $uuid string 32 char hex string
261 * @param $rand integer Random unsigned integer (31 bits)
262 * @param $gte bool Search for job_random >= $random (otherwise job_random <= $random)
265 protected function claimRandom( $uuid, $rand, $gte ) {
268 list( $dbw, $scope ) = $this->getMasterDB();
269 // Check cache to see if the queue has <= OFFSET items
270 $tinyQueue = $wgMemc->get( $this->getCacheKey( 'small' ) );
272 $row = false; // the row acquired
273 $invertedDirection = false; // whether one job_random direction was already scanned
274 // This uses a replication safe method for acquiring jobs. One could use UPDATE+LIMIT
275 // instead, but that either uses ORDER BY (in which case it deadlocks in MySQL) or is
276 // not replication safe. Due to http://bugs.mysql.com/bug.php?id=6980, subqueries cannot
277 // be used here with MySQL.
279 if ( $tinyQueue ) { // queue has <= MAX_OFFSET rows
280 // For small queues, using OFFSET will overshoot and return no rows more often.
281 // Instead, this uses job_random to pick a row (possibly checking both directions).
282 $ineq = $gte ?
'>=' : '<=';
283 $dir = $gte ?
'ASC' : 'DESC';
284 $row = $dbw->selectRow( 'job', '*', // find a random job
286 'job_cmd' => $this->type
,
287 'job_token' => '', // unclaimed
288 "job_random {$ineq} {$dbw->addQuotes( $rand )}" ),
290 array( 'ORDER BY' => "job_random {$dir}" )
292 if ( !$row && !$invertedDirection ) {
294 $invertedDirection = true;
295 continue; // try the other direction
297 } else { // table *may* have >= MAX_OFFSET rows
298 // Bug 42614: "ORDER BY job_random" with a job_random inequality causes high CPU
299 // in MySQL if there are many rows for some reason. This uses a small OFFSET
300 // instead of job_random for reducing excess claim retries.
301 $row = $dbw->selectRow( 'job', '*', // find a random job
303 'job_cmd' => $this->type
,
304 'job_token' => '', // unclaimed
307 array( 'OFFSET' => mt_rand( 0, self
::MAX_OFFSET
) )
310 $tinyQueue = true; // we know the queue must have <= MAX_OFFSET rows
311 $wgMemc->set( $this->getCacheKey( 'small' ), 1, 30 );
312 continue; // use job_random
315 if ( $row ) { // claim the job
316 $dbw->update( 'job', // update by PK
318 'job_token' => $uuid,
319 'job_token_timestamp' => $dbw->timestamp(),
320 'job_attempts = job_attempts+1' ),
321 array( 'job_cmd' => $this->type
, 'job_id' => $row->job_id
, 'job_token' => '' ),
324 // This might get raced out by another runner when claiming the previously
325 // selected row. The use of job_random should minimize this problem, however.
326 if ( !$dbw->affectedRows() ) {
327 $row = false; // raced out
330 break; // nothing to do
338 * Reserve a row with a single UPDATE without holding row locks over RTTs...
340 * @param $uuid string 32 char hex string
343 protected function claimOldest( $uuid ) {
344 list( $dbw, $scope ) = $this->getMasterDB();
346 $row = false; // the row acquired
348 if ( $dbw->getType() === 'mysql' ) {
349 // Per http://bugs.mysql.com/bug.php?id=6980, we can't use subqueries on the
350 // same table being changed in an UPDATE query in MySQL (gives Error: 1093).
351 // Oracle and Postgre have no such limitation. However, MySQL offers an
352 // alternative here by supporting ORDER BY + LIMIT for UPDATE queries.
353 $dbw->query( "UPDATE {$dbw->tableName( 'job' )} " .
355 "job_token = {$dbw->addQuotes( $uuid ) }, " .
356 "job_token_timestamp = {$dbw->addQuotes( $dbw->timestamp() )}, " .
357 "job_attempts = job_attempts+1 " .
359 "job_cmd = {$dbw->addQuotes( $this->type )} " .
360 "AND job_token = {$dbw->addQuotes( '' )} " .
361 ") ORDER BY job_id ASC LIMIT 1",
365 // Use a subquery to find the job, within an UPDATE to claim it.
366 // This uses as much of the DB wrapper functions as possible.
369 'job_token' => $uuid,
370 'job_token_timestamp' => $dbw->timestamp(),
371 'job_attempts = job_attempts+1' ),
372 array( 'job_id = (' .
373 $dbw->selectSQLText( 'job', 'job_id',
374 array( 'job_cmd' => $this->type
, 'job_token' => '' ),
376 array( 'ORDER BY' => 'job_id ASC', 'LIMIT' => 1 ) ) .
382 // Fetch any row that we just reserved...
383 if ( $dbw->affectedRows() ) {
384 $row = $dbw->selectRow( 'job', '*',
385 array( 'job_cmd' => $this->type
, 'job_token' => $uuid ), __METHOD__
387 if ( !$row ) { // raced out by duplicate job removal
388 wfDebugLog( 'JobQueueDB', "Row deleted as duplicate by another process." );
391 break; // nothing to do
399 * Recycle or destroy any jobs that have been claimed for too long
401 * @return integer Number of jobs recycled/deleted
403 protected function recycleStaleJobs() {
405 list( $dbw, $scope ) = $this->getMasterDB();
406 $count = 0; // affected rows
408 if ( !$dbw->lock( "jobqueue-recycle-{$this->type}", __METHOD__
, 1 ) ) {
409 return $count; // already in progress
412 // Remove claims on jobs acquired for too long if enabled...
413 if ( $this->claimTTL
> 0 ) {
414 $claimCutoff = $dbw->timestamp( $now - $this->claimTTL
);
415 // Get the IDs of jobs that have be claimed but not finished after too long.
416 // These jobs can be recycled into the queue by expiring the claim. Selecting
417 // the IDs first means that the UPDATE can be done by primary key (less deadlocks).
418 $res = $dbw->select( 'job', 'job_id',
420 'job_cmd' => $this->type
,
421 "job_token != {$dbw->addQuotes( '' )}", // was acquired
422 "job_token_timestamp < {$dbw->addQuotes( $claimCutoff )}", // stale
423 "job_attempts < {$dbw->addQuotes( self::MAX_ATTEMPTS )}" ), // retries left
426 $ids = array_map( function( $o ) { return $o->job_id
; }, iterator_to_array( $res ) );
427 if ( count( $ids ) ) {
428 // Reset job_token for these jobs so that other runners will pick them up.
429 // Set the timestamp to the current time, as it is useful to now that the job
430 // was already tried before (the timestamp becomes the "released" time).
434 'job_token_timestamp' => $dbw->timestamp( $now ) ), // time of release
439 $count +
= $dbw->affectedRows();
443 // Just destroy any stale jobs...
444 $pruneCutoff = $dbw->timestamp( $now - self
::MAX_AGE_PRUNE
);
446 'job_cmd' => $this->type
,
447 "job_token != {$dbw->addQuotes( '' )}", // was acquired
448 "job_token_timestamp < {$dbw->addQuotes( $pruneCutoff )}" // stale
450 if ( $this->claimTTL
> 0 ) { // only prune jobs attempted too many times...
451 $conds[] = "job_attempts >= {$dbw->addQuotes( self::MAX_ATTEMPTS )}";
453 // Get the IDs of jobs that are considered stale and should be removed. Selecting
454 // the IDs first means that the UPDATE can be done by primary key (less deadlocks).
455 $res = $dbw->select( 'job', 'job_id', $conds, __METHOD__
);
456 $ids = array_map( function( $o ) { return $o->job_id
; }, iterator_to_array( $res ) );
457 if ( count( $ids ) ) {
458 $dbw->delete( 'job', array( 'job_id' => $ids ), __METHOD__
);
459 $count +
= $dbw->affectedRows();
462 $dbw->unlock( "jobqueue-recycle-{$this->type}", __METHOD__
);
468 * @see JobQueue::doAck()
470 * @throws MWException
473 protected function doAck( Job
$job ) {
474 if ( !$job->getId() ) {
475 throw new MWException( "Job of type '{$job->getType()}' has no ID." );
478 list( $dbw, $scope ) = $this->getMasterDB();
479 $dbw->commit( __METHOD__
, 'flush' ); // flush existing transaction
481 // Delete a row with a single DELETE without holding row locks over RTTs...
483 array( 'job_cmd' => $this->type
, 'job_id' => $job->getId() ), __METHOD__
);
489 * @see JobQueue::doDeduplicateRootJob()
491 * @throws MWException
494 protected function doDeduplicateRootJob( Job
$job ) {
495 $params = $job->getParams();
496 if ( !isset( $params['rootJobSignature'] ) ) {
497 throw new MWException( "Cannot register root job; missing 'rootJobSignature'." );
498 } elseif ( !isset( $params['rootJobTimestamp'] ) ) {
499 throw new MWException( "Cannot register root job; missing 'rootJobTimestamp'." );
501 $key = $this->getRootJobCacheKey( $params['rootJobSignature'] );
502 // Callers should call batchInsert() and then this function so that if the insert
503 // fails, the de-duplication registration will be aborted. Since the insert is
504 // deferred till "transaction idle", do the same here, so that the ordering is
505 // maintained. Having only the de-duplication registration succeed would cause
506 // jobs to become no-ops without any actual jobs that made them redundant.
507 list( $dbw, $scope ) = $this->getMasterDB();
508 $dbw->onTransactionIdle( function() use ( $params, $key, $scope ) {
511 $timestamp = $wgMemc->get( $key ); // current last timestamp of this job
512 if ( $timestamp && $timestamp >= $params['rootJobTimestamp'] ) {
513 return true; // a newer version of this root job was enqueued
516 // Update the timestamp of the last root job started at the location...
517 return $wgMemc->set( $key, $params['rootJobTimestamp'], 14*86400 ); // 2 weeks
524 * Check if the "root" job of a given job has been superseded by a newer one
529 protected function isRootJobOldDuplicate( Job
$job ) {
532 $params = $job->getParams();
533 if ( !isset( $params['rootJobSignature'] ) ) {
534 return false; // job has no de-deplication info
535 } elseif ( !isset( $params['rootJobTimestamp'] ) ) {
536 trigger_error( "Cannot check root job; missing 'rootJobTimestamp'." );
540 // Get the last time this root job was enqueued
541 $timestamp = $wgMemc->get( $this->getRootJobCacheKey( $params['rootJobSignature'] ) );
543 // Check if a new root job was started at the location after this one's...
544 return ( $timestamp && $timestamp > $params['rootJobTimestamp'] );
548 * @see JobQueue::doWaitForBackups()
551 protected function doWaitForBackups() {
556 * @return Array (DatabaseBase, ScopedCallback)
558 protected function getSlaveDB() {
559 return $this->getDB( DB_SLAVE
);
563 * @return Array (DatabaseBase, ScopedCallback)
565 protected function getMasterDB() {
566 return $this->getDB( DB_MASTER
);
570 * @param $index integer (DB_SLAVE/DB_MASTER)
571 * @return Array (DatabaseBase, ScopedCallback)
573 protected function getDB( $index ) {
574 $lb = ( $this->cluster
!== false )
575 ?
wfGetLBFactory()->getExternalLB( $this->cluster
, $this->wiki
)
576 : wfGetLB( $this->wiki
);
577 $conn = $lb->getConnection( $index );
580 new ScopedCallback( function() use ( $lb, $conn ) {
581 $lb->reuseConnection( $conn );
590 protected function insertFields( Job
$job ) {
591 list( $dbw, $scope ) = $this->getMasterDB();
593 // Fields that describe the nature of the job
594 'job_cmd' => $job->getType(),
595 'job_namespace' => $job->getTitle()->getNamespace(),
596 'job_title' => $job->getTitle()->getDBkey(),
597 'job_params' => self
::makeBlob( $job->getParams() ),
598 // Additional job metadata
599 'job_id' => $dbw->nextSequenceValue( 'job_job_id_seq' ),
600 'job_timestamp' => $dbw->timestamp(),
601 'job_sha1' => wfBaseConvert(
602 sha1( serialize( $job->getDeduplicationInfo() ) ),
605 'job_random' => mt_rand( 0, self
::MAX_JOB_RANDOM
)
612 private function getCacheKey( $property ) {
613 list( $db, $prefix ) = wfSplitWikiID( $this->wiki
);
614 return wfForeignMemcKey( $db, $prefix, 'jobqueue', $this->type
, $property );
618 * @param string $signature Hash identifier of the root job
621 private function getRootJobCacheKey( $signature ) {
622 list( $db, $prefix ) = wfSplitWikiID( $this->wiki
);
623 return wfForeignMemcKey( $db, $prefix, 'jobqueue', $this->type
, 'rootjob', $signature );
630 protected static function makeBlob( $params ) {
631 if ( $params !== false ) {
632 return serialize( $params );
642 protected static function extractBlob( $blob ) {
643 if ( (string)$blob !== '' ) {
644 return unserialize( $blob );