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
22 use Wikimedia\Rdbms\IDatabase
;
23 use Wikimedia\Rdbms\Database
;
24 use Wikimedia\Rdbms\DBConnectionError
;
25 use Wikimedia\Rdbms\DBError
;
26 use MediaWiki\MediaWikiServices
;
27 use Wikimedia\ScopedCallback
;
30 * Class to handle job queues stored in the DB
35 class JobQueueDB
extends JobQueue
{
36 const CACHE_TTL_SHORT
= 30; // integer; seconds to cache info without re-validating
37 const MAX_AGE_PRUNE
= 604800; // integer; seconds a job can live once claimed
38 const MAX_JOB_RANDOM
= 2147483647; // integer; 2^31 - 1, used for job_random
39 const MAX_OFFSET
= 255; // integer; maximum number of rows to skip
41 /** @var WANObjectCache */
43 /** @var IDatabase|DBError|null */
46 /** @var array|null Server configuration array */
48 /** @var string|null Name of an external DB cluster or null for the local DB cluster */
52 * Additional parameters include:
53 * - server : Server configuration array for Database::factory. Overrides "cluster".
54 * - cluster : The name of an external cluster registered via LBFactory.
55 * If not specified, the primary DB cluster for the wiki will be used.
56 * This can be overridden with a custom cluster so that DB handles will
57 * be retrieved via LBFactory::getExternalLB() and getConnection().
58 * @param array $params
60 protected function __construct( array $params ) {
61 parent
::__construct( $params );
63 if ( isset( $params['server'] ) ) {
64 $this->server
= $params['server'];
65 } elseif ( isset( $params['cluster'] ) && is_string( $params['cluster'] ) ) {
66 $this->cluster
= $params['cluster'];
69 $this->cache
= MediaWikiServices
::getInstance()->getMainWANObjectCache();
72 protected function supportedOrders() {
73 return [ 'random', 'timestamp', 'fifo' ];
76 protected function optimalOrder() {
81 * @see JobQueue::doIsEmpty()
84 protected function doIsEmpty() {
85 $dbr = $this->getReplicaDB();
86 /** @noinspection PhpUnusedLocalVariableInspection */
87 $scope = $this->getScopedNoTrxFlag( $dbr );
89 $found = $dbr->selectField( // unclaimed job
90 'job', '1', [ 'job_cmd' => $this->type
, 'job_token' => '' ], __METHOD__
92 } catch ( DBError
$e ) {
93 $this->throwDBException( $e );
100 * @see JobQueue::doGetSize()
103 protected function doGetSize() {
104 $key = $this->getCacheKey( 'size' );
106 $size = $this->cache
->get( $key );
107 if ( is_int( $size ) ) {
111 $dbr = $this->getReplicaDB();
112 /** @noinspection PhpUnusedLocalVariableInspection */
113 $scope = $this->getScopedNoTrxFlag( $dbr );
115 $size = (int)$dbr->selectField( 'job', 'COUNT(*)',
116 [ 'job_cmd' => $this->type
, 'job_token' => '' ],
119 } catch ( DBError
$e ) {
120 $this->throwDBException( $e );
122 $this->cache
->set( $key, $size, self
::CACHE_TTL_SHORT
);
128 * @see JobQueue::doGetAcquiredCount()
131 protected function doGetAcquiredCount() {
132 if ( $this->claimTTL
<= 0 ) {
133 return 0; // no acknowledgements
136 $key = $this->getCacheKey( 'acquiredcount' );
138 $count = $this->cache
->get( $key );
139 if ( is_int( $count ) ) {
143 $dbr = $this->getReplicaDB();
144 /** @noinspection PhpUnusedLocalVariableInspection */
145 $scope = $this->getScopedNoTrxFlag( $dbr );
147 $count = (int)$dbr->selectField( 'job', 'COUNT(*)',
148 [ 'job_cmd' => $this->type
, "job_token != {$dbr->addQuotes( '' )}" ],
151 } catch ( DBError
$e ) {
152 $this->throwDBException( $e );
154 $this->cache
->set( $key, $count, self
::CACHE_TTL_SHORT
);
160 * @see JobQueue::doGetAbandonedCount()
162 * @throws MWException
164 protected function doGetAbandonedCount() {
165 if ( $this->claimTTL
<= 0 ) {
166 return 0; // no acknowledgements
169 $key = $this->getCacheKey( 'abandonedcount' );
171 $count = $this->cache
->get( $key );
172 if ( is_int( $count ) ) {
176 $dbr = $this->getReplicaDB();
177 /** @noinspection PhpUnusedLocalVariableInspection */
178 $scope = $this->getScopedNoTrxFlag( $dbr );
180 $count = (int)$dbr->selectField( 'job', 'COUNT(*)',
182 'job_cmd' => $this->type
,
183 "job_token != {$dbr->addQuotes( '' )}",
184 "job_attempts >= " . $dbr->addQuotes( $this->maxTries
)
188 } catch ( DBError
$e ) {
189 $this->throwDBException( $e );
192 $this->cache
->set( $key, $count, self
::CACHE_TTL_SHORT
);
198 * @see JobQueue::doBatchPush()
199 * @param IJobSpecification[] $jobs
201 * @throws DBError|Exception
204 protected function doBatchPush( array $jobs, $flags ) {
205 $dbw = $this->getMasterDB();
206 /** @noinspection PhpUnusedLocalVariableInspection */
207 $scope = $this->getScopedNoTrxFlag( $dbw );
208 // In general, there will be two cases here:
209 // a) sqlite; DB connection is probably a regular round-aware handle.
210 // If the connection is busy with a transaction, then defer the job writes
211 // until right before the main round commit step. Any errors that bubble
212 // up will rollback the main commit round.
213 // b) mysql/postgres; DB connection is generally a separate CONN_TRX_AUTOCOMMIT handle.
214 // No transaction is active nor will be started by writes, so enqueue the jobs
215 // now so that any errors will show up immediately as the interface expects. Any
216 // errors that bubble up will rollback the main commit round.
218 $dbw->onTransactionPreCommitOrIdle(
219 function ( IDatabase
$dbw ) use ( $jobs, $flags, $fname ) {
220 $this->doBatchPushInternal( $dbw, $jobs, $flags, $fname );
227 * This function should *not* be called outside of JobQueueDB
229 * @suppress SecurityCheck-SQLInjection Bug in phan-taint-check handling bulk inserts
230 * @param IDatabase $dbw
231 * @param IJobSpecification[] $jobs
233 * @param string $method
237 public function doBatchPushInternal( IDatabase
$dbw, array $jobs, $flags, $method ) {
238 if ( $jobs === [] ) {
242 $rowSet = []; // (sha1 => job) map for jobs that are de-duplicated
243 $rowList = []; // list of jobs for jobs that are not de-duplicated
244 foreach ( $jobs as $job ) {
245 $row = $this->insertFields( $job, $dbw );
246 if ( $job->ignoreDuplicates() ) {
247 $rowSet[$row['job_sha1']] = $row;
253 if ( $flags & self
::QOS_ATOMIC
) {
254 $dbw->startAtomic( $method ); // wrap all the job additions in one transaction
257 // Strip out any duplicate jobs that are already in the queue...
258 if ( count( $rowSet ) ) {
259 $res = $dbw->select( 'job', 'job_sha1',
261 // No job_type condition since it's part of the job_sha1 hash
262 'job_sha1' => array_keys( $rowSet ),
263 'job_token' => '' // unclaimed
267 foreach ( $res as $row ) {
268 wfDebug( "Job with hash '{$row->job_sha1}' is a duplicate.\n" );
269 unset( $rowSet[$row->job_sha1
] ); // already enqueued
272 // Build the full list of job rows to insert
273 $rows = array_merge( $rowList, array_values( $rowSet ) );
274 // Insert the job rows in chunks to avoid replica DB lag...
275 foreach ( array_chunk( $rows, 50 ) as $rowBatch ) {
276 $dbw->insert( 'job', $rowBatch, $method );
278 JobQueue
::incrStats( 'inserts', $this->type
, count( $rows ) );
279 JobQueue
::incrStats( 'dupe_inserts', $this->type
,
280 count( $rowSet ) +
count( $rowList ) - count( $rows )
282 } catch ( DBError
$e ) {
283 $this->throwDBException( $e );
285 if ( $flags & self
::QOS_ATOMIC
) {
286 $dbw->endAtomic( $method );
291 * @see JobQueue::doPop()
294 protected function doPop() {
295 $dbw = $this->getMasterDB();
296 /** @noinspection PhpUnusedLocalVariableInspection */
297 $scope = $this->getScopedNoTrxFlag( $dbw );
299 $job = false; // job popped off
301 $uuid = wfRandomString( 32 ); // pop attempt
302 do { // retry when our row is invalid or deleted as a duplicate
303 // Try to reserve a row in the DB...
304 if ( in_array( $this->order
, [ 'fifo', 'timestamp' ] ) ) {
305 $row = $this->claimOldest( $uuid );
306 } else { // random first
307 $rand = mt_rand( 0, self
::MAX_JOB_RANDOM
); // encourage concurrent UPDATEs
308 $gte = (bool)mt_rand( 0, 1 ); // find rows with rand before/after $rand
309 $row = $this->claimRandom( $uuid, $rand, $gte );
311 // Check if we found a row to reserve...
313 break; // nothing to do
315 JobQueue
::incrStats( 'pops', $this->type
);
316 // Get the job object from the row...
317 $title = Title
::makeTitle( $row->job_namespace
, $row->job_title
);
318 $job = Job
::factory( $row->job_cmd
, $title,
319 self
::extractBlob( $row->job_params
) );
320 $job->metadata
['id'] = $row->job_id
;
321 $job->metadata
['timestamp'] = $row->job_timestamp
;
325 if ( !$job ||
mt_rand( 0, 9 ) == 0 ) {
326 // Handled jobs that need to be recycled/deleted;
327 // any recycled jobs will be picked up next attempt
328 $this->recycleAndDeleteStaleJobs();
330 } catch ( DBError
$e ) {
331 $this->throwDBException( $e );
338 * Reserve a row with a single UPDATE without holding row locks over RTTs...
340 * @param string $uuid 32 char hex string
341 * @param int $rand Random unsigned integer (31 bits)
342 * @param bool $gte Search for job_random >= $random (otherwise job_random <= $random)
343 * @return stdClass|bool Row|false
345 protected function claimRandom( $uuid, $rand, $gte ) {
346 $dbw = $this->getMasterDB();
347 /** @noinspection PhpUnusedLocalVariableInspection */
348 $scope = $this->getScopedNoTrxFlag( $dbw );
349 // Check cache to see if the queue has <= OFFSET items
350 $tinyQueue = $this->cache
->get( $this->getCacheKey( 'small' ) );
352 $row = false; // the row acquired
353 $invertedDirection = false; // whether one job_random direction was already scanned
354 // This uses a replication safe method for acquiring jobs. One could use UPDATE+LIMIT
355 // instead, but that either uses ORDER BY (in which case it deadlocks in MySQL) or is
356 // not replication safe. Due to https://bugs.mysql.com/bug.php?id=6980, subqueries cannot
357 // be used here with MySQL.
359 if ( $tinyQueue ) { // queue has <= MAX_OFFSET rows
360 // For small queues, using OFFSET will overshoot and return no rows more often.
361 // Instead, this uses job_random to pick a row (possibly checking both directions).
362 $ineq = $gte ?
'>=' : '<=';
363 $dir = $gte ?
'ASC' : 'DESC';
364 $row = $dbw->selectRow( 'job', self
::selectFields(), // find a random job
366 'job_cmd' => $this->type
,
367 'job_token' => '', // unclaimed
368 "job_random {$ineq} {$dbw->addQuotes( $rand )}" ],
370 [ 'ORDER BY' => "job_random {$dir}" ]
372 if ( !$row && !$invertedDirection ) {
374 $invertedDirection = true;
375 continue; // try the other direction
377 } else { // table *may* have >= MAX_OFFSET rows
378 // T44614: "ORDER BY job_random" with a job_random inequality causes high CPU
379 // in MySQL if there are many rows for some reason. This uses a small OFFSET
380 // instead of job_random for reducing excess claim retries.
381 $row = $dbw->selectRow( 'job', self
::selectFields(), // find a random job
383 'job_cmd' => $this->type
,
384 'job_token' => '', // unclaimed
387 [ 'OFFSET' => mt_rand( 0, self
::MAX_OFFSET
) ]
390 $tinyQueue = true; // we know the queue must have <= MAX_OFFSET rows
391 $this->cache
->set( $this->getCacheKey( 'small' ), 1, 30 );
392 continue; // use job_random
396 if ( $row ) { // claim the job
397 $dbw->update( 'job', // update by PK
399 'job_token' => $uuid,
400 'job_token_timestamp' => $dbw->timestamp(),
401 'job_attempts = job_attempts+1' ],
402 [ 'job_cmd' => $this->type
, 'job_id' => $row->job_id
, 'job_token' => '' ],
405 // This might get raced out by another runner when claiming the previously
406 // selected row. The use of job_random should minimize this problem, however.
407 if ( !$dbw->affectedRows() ) {
408 $row = false; // raced out
411 break; // nothing to do
419 * Reserve a row with a single UPDATE without holding row locks over RTTs...
421 * @param string $uuid 32 char hex string
422 * @return stdClass|bool Row|false
424 protected function claimOldest( $uuid ) {
425 $dbw = $this->getMasterDB();
426 /** @noinspection PhpUnusedLocalVariableInspection */
427 $scope = $this->getScopedNoTrxFlag( $dbw );
429 $row = false; // the row acquired
431 if ( $dbw->getType() === 'mysql' ) {
432 // Per https://bugs.mysql.com/bug.php?id=6980, we can't use subqueries on the
433 // same table being changed in an UPDATE query in MySQL (gives Error: 1093).
434 // Oracle and Postgre have no such limitation. However, MySQL offers an
435 // alternative here by supporting ORDER BY + LIMIT for UPDATE queries.
436 $dbw->query( "UPDATE {$dbw->tableName( 'job' )} " .
438 "job_token = {$dbw->addQuotes( $uuid ) }, " .
439 "job_token_timestamp = {$dbw->addQuotes( $dbw->timestamp() )}, " .
440 "job_attempts = job_attempts+1 " .
442 "job_cmd = {$dbw->addQuotes( $this->type )} " .
443 "AND job_token = {$dbw->addQuotes( '' )} " .
444 ") ORDER BY job_id ASC LIMIT 1",
448 // Use a subquery to find the job, within an UPDATE to claim it.
449 // This uses as much of the DB wrapper functions as possible.
452 'job_token' => $uuid,
453 'job_token_timestamp' => $dbw->timestamp(),
454 'job_attempts = job_attempts+1' ],
456 $dbw->selectSQLText( 'job', 'job_id',
457 [ 'job_cmd' => $this->type
, 'job_token' => '' ],
459 [ 'ORDER BY' => 'job_id ASC', 'LIMIT' => 1 ] ) .
465 // Fetch any row that we just reserved...
466 if ( $dbw->affectedRows() ) {
467 $row = $dbw->selectRow( 'job', self
::selectFields(),
468 [ 'job_cmd' => $this->type
, 'job_token' => $uuid ], __METHOD__
470 if ( !$row ) { // raced out by duplicate job removal
471 wfDebug( "Row deleted as duplicate by another process.\n" );
474 break; // nothing to do
482 * @see JobQueue::doAck()
484 * @throws MWException
486 protected function doAck( Job
$job ) {
487 if ( !isset( $job->metadata
['id'] ) ) {
488 throw new MWException( "Job of type '{$job->getType()}' has no ID." );
491 $dbw = $this->getMasterDB();
492 /** @noinspection PhpUnusedLocalVariableInspection */
493 $scope = $this->getScopedNoTrxFlag( $dbw );
495 // Delete a row with a single DELETE without holding row locks over RTTs...
497 [ 'job_cmd' => $this->type
, 'job_id' => $job->metadata
['id'] ], __METHOD__
);
499 JobQueue
::incrStats( 'acks', $this->type
);
500 } catch ( DBError
$e ) {
501 $this->throwDBException( $e );
506 * @see JobQueue::doDeduplicateRootJob()
507 * @param IJobSpecification $job
508 * @throws MWException
511 protected function doDeduplicateRootJob( IJobSpecification
$job ) {
512 $params = $job->getParams();
513 if ( !isset( $params['rootJobSignature'] ) ) {
514 throw new MWException( "Cannot register root job; missing 'rootJobSignature'." );
515 } elseif ( !isset( $params['rootJobTimestamp'] ) ) {
516 throw new MWException( "Cannot register root job; missing 'rootJobTimestamp'." );
518 $key = $this->getRootJobCacheKey( $params['rootJobSignature'] );
519 // Callers should call JobQueueGroup::push() before this method so that if the insert
520 // fails, the de-duplication registration will be aborted. Since the insert is
521 // deferred till "transaction idle", do the same here, so that the ordering is
522 // maintained. Having only the de-duplication registration succeed would cause
523 // jobs to become no-ops without any actual jobs that made them redundant.
524 $dbw = $this->getMasterDB();
525 /** @noinspection PhpUnusedLocalVariableInspection */
526 $scope = $this->getScopedNoTrxFlag( $dbw );
528 $cache = $this->dupCache
;
529 $dbw->onTransactionCommitOrIdle(
530 function () use ( $cache, $params, $key ) {
531 $timestamp = $cache->get( $key ); // current last timestamp of this job
532 if ( $timestamp && $timestamp >= $params['rootJobTimestamp'] ) {
533 return true; // a newer version of this root job was enqueued
536 // Update the timestamp of the last root job started at the location...
537 return $cache->set( $key, $params['rootJobTimestamp'], JobQueueDB
::ROOTJOB_TTL
);
546 * @see JobQueue::doDelete()
549 protected function doDelete() {
550 $dbw = $this->getMasterDB();
551 /** @noinspection PhpUnusedLocalVariableInspection */
552 $scope = $this->getScopedNoTrxFlag( $dbw );
554 $dbw->delete( 'job', [ 'job_cmd' => $this->type
] );
555 } catch ( DBError
$e ) {
556 $this->throwDBException( $e );
563 * @see JobQueue::doWaitForBackups()
566 protected function doWaitForBackups() {
567 if ( $this->server
) {
568 return; // not using LBFactory instance
571 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
572 $lbFactory->waitForReplication( [
573 'domain' => $this->domain
,
574 'cluster' => is_string( $this->cluster
) ?
$this->cluster
: false
581 protected function doFlushCaches() {
582 foreach ( [ 'size', 'acquiredcount' ] as $type ) {
583 $this->cache
->delete( $this->getCacheKey( $type ) );
588 * @see JobQueue::getAllQueuedJobs()
591 public function getAllQueuedJobs() {
592 return $this->getJobIterator( [ 'job_cmd' => $this->getType(), 'job_token' => '' ] );
596 * @see JobQueue::getAllAcquiredJobs()
599 public function getAllAcquiredJobs() {
600 return $this->getJobIterator( [ 'job_cmd' => $this->getType(), "job_token > ''" ] );
604 * @param array $conds Query conditions
607 protected function getJobIterator( array $conds ) {
608 $dbr = $this->getReplicaDB();
609 /** @noinspection PhpUnusedLocalVariableInspection */
610 $scope = $this->getScopedNoTrxFlag( $dbr );
612 return new MappedIterator(
613 $dbr->select( 'job', self
::selectFields(), $conds ),
617 Title
::makeTitle( $row->job_namespace
, $row->job_title
),
618 strlen( $row->job_params
) ?
unserialize( $row->job_params
) : []
620 $job->metadata
['id'] = $row->job_id
;
621 $job->metadata
['timestamp'] = $row->job_timestamp
;
626 } catch ( DBError
$e ) {
627 $this->throwDBException( $e );
631 public function getCoalesceLocationInternal() {
632 if ( $this->server
) {
633 return null; // not using the LBFactory instance
636 return is_string( $this->cluster
)
637 ?
"DBCluster:{$this->cluster}:{$this->domain}"
638 : "LBFactory:{$this->domain}";
641 protected function doGetSiblingQueuesWithJobs( array $types ) {
642 $dbr = $this->getReplicaDB();
643 /** @noinspection PhpUnusedLocalVariableInspection */
644 $scope = $this->getScopedNoTrxFlag( $dbr );
645 // @note: this does not check whether the jobs are claimed or not.
646 // This is useful so JobQueueGroup::pop() also sees queues that only
647 // have stale jobs. This lets recycleAndDeleteStaleJobs() re-enqueue
648 // failed jobs so that they can be popped again for that edge case.
649 $res = $dbr->select( 'job', 'DISTINCT job_cmd',
650 [ 'job_cmd' => $types ], __METHOD__
);
653 foreach ( $res as $row ) {
654 $types[] = $row->job_cmd
;
660 protected function doGetSiblingQueueSizes( array $types ) {
661 $dbr = $this->getReplicaDB();
662 /** @noinspection PhpUnusedLocalVariableInspection */
663 $scope = $this->getScopedNoTrxFlag( $dbr );
665 $res = $dbr->select( 'job', [ 'job_cmd', 'COUNT(*) AS count' ],
666 [ 'job_cmd' => $types ], __METHOD__
, [ 'GROUP BY' => 'job_cmd' ] );
669 foreach ( $res as $row ) {
670 $sizes[$row->job_cmd
] = (int)$row->count
;
677 * Recycle or destroy any jobs that have been claimed for too long
679 * @return int Number of jobs recycled/deleted
681 public function recycleAndDeleteStaleJobs() {
683 $count = 0; // affected rows
684 $dbw = $this->getMasterDB();
685 /** @noinspection PhpUnusedLocalVariableInspection */
686 $scope = $this->getScopedNoTrxFlag( $dbw );
689 if ( !$dbw->lock( "jobqueue-recycle-{$this->type}", __METHOD__
, 1 ) ) {
690 return $count; // already in progress
693 // Remove claims on jobs acquired for too long if enabled...
694 if ( $this->claimTTL
> 0 ) {
695 $claimCutoff = $dbw->timestamp( $now - $this->claimTTL
);
696 // Get the IDs of jobs that have be claimed but not finished after too long.
697 // These jobs can be recycled into the queue by expiring the claim. Selecting
698 // the IDs first means that the UPDATE can be done by primary key (less deadlocks).
699 $res = $dbw->select( 'job', 'job_id',
701 'job_cmd' => $this->type
,
702 "job_token != {$dbw->addQuotes( '' )}", // was acquired
703 "job_token_timestamp < {$dbw->addQuotes( $claimCutoff )}", // stale
704 "job_attempts < {$dbw->addQuotes( $this->maxTries )}" ], // retries left
710 }, iterator_to_array( $res )
712 if ( count( $ids ) ) {
713 // Reset job_token for these jobs so that other runners will pick them up.
714 // Set the timestamp to the current time, as it is useful to now that the job
715 // was already tried before (the timestamp becomes the "released" time).
719 'job_token_timestamp' => $dbw->timestamp( $now ) ], // time of release
724 $affected = $dbw->affectedRows();
726 JobQueue
::incrStats( 'recycles', $this->type
, $affected );
727 $this->aggr
->notifyQueueNonEmpty( $this->domain
, $this->type
);
731 // Just destroy any stale jobs...
732 $pruneCutoff = $dbw->timestamp( $now - self
::MAX_AGE_PRUNE
);
734 'job_cmd' => $this->type
,
735 "job_token != {$dbw->addQuotes( '' )}", // was acquired
736 "job_token_timestamp < {$dbw->addQuotes( $pruneCutoff )}" // stale
738 if ( $this->claimTTL
> 0 ) { // only prune jobs attempted too many times...
739 $conds[] = "job_attempts >= {$dbw->addQuotes( $this->maxTries )}";
741 // Get the IDs of jobs that are considered stale and should be removed. Selecting
742 // the IDs first means that the UPDATE can be done by primary key (less deadlocks).
743 $res = $dbw->select( 'job', 'job_id', $conds, __METHOD__
);
747 }, iterator_to_array( $res )
749 if ( count( $ids ) ) {
750 $dbw->delete( 'job', [ 'job_id' => $ids ], __METHOD__
);
751 $affected = $dbw->affectedRows();
753 JobQueue
::incrStats( 'abandons', $this->type
, $affected );
756 $dbw->unlock( "jobqueue-recycle-{$this->type}", __METHOD__
);
757 } catch ( DBError
$e ) {
758 $this->throwDBException( $e );
765 * @param IJobSpecification $job
766 * @param IDatabase $db
769 protected function insertFields( IJobSpecification
$job, IDatabase
$db ) {
771 // Fields that describe the nature of the job
772 'job_cmd' => $job->getType(),
773 'job_namespace' => $job->getTitle()->getNamespace(),
774 'job_title' => $job->getTitle()->getDBkey(),
775 'job_params' => self
::makeBlob( $job->getParams() ),
776 // Additional job metadata
777 'job_timestamp' => $db->timestamp(),
778 'job_sha1' => Wikimedia\base_convert
(
779 sha1( serialize( $job->getDeduplicationInfo() ) ),
782 'job_random' => mt_rand( 0, self
::MAX_JOB_RANDOM
)
787 * @throws JobQueueConnectionError
790 protected function getReplicaDB() {
792 return $this->getDB( DB_REPLICA
);
793 } catch ( DBConnectionError
$e ) {
794 throw new JobQueueConnectionError( "DBConnectionError:" . $e->getMessage() );
799 * @throws JobQueueConnectionError
802 protected function getMasterDB() {
804 return $this->getDB( DB_MASTER
);
805 } catch ( DBConnectionError
$e ) {
806 throw new JobQueueConnectionError( "DBConnectionError:" . $e->getMessage() );
811 * @param int $index (DB_REPLICA/DB_MASTER)
814 protected function getDB( $index ) {
815 if ( $this->server
) {
816 if ( $this->conn
instanceof IDatabase
) {
818 } elseif ( $this->conn
instanceof DBError
) {
823 $this->conn
= Database
::factory( $this->server
['type'], $this->server
);
824 } catch ( DBError
$e ) {
831 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
832 $lb = is_string( $this->cluster
)
833 ?
$lbFactory->getExternalLB( $this->cluster
)
834 : $lbFactory->getMainLB( $this->domain
);
836 return ( $lb->getServerType( $lb->getWriterIndex() ) !== 'sqlite' )
837 // Keep a separate connection to avoid contention and deadlocks;
838 // However, SQLite has the opposite behavior due to DB-level locking.
839 ?
$lb->getConnectionRef( $index, [], $this->domain
, $lb::CONN_TRX_AUTOCOMMIT
)
840 // Jobs insertion will be defered until the PRESEND stage to reduce contention.
841 : $lb->getConnectionRef( $index, [], $this->domain
);
846 * @param IDatabase $db
847 * @return ScopedCallback
849 private function getScopedNoTrxFlag( IDatabase
$db ) {
850 $autoTrx = $db->getFlag( DBO_TRX
); // get current setting
851 $db->clearFlag( DBO_TRX
); // make each query its own transaction
853 return new ScopedCallback( function () use ( $db, $autoTrx ) {
855 $db->setFlag( DBO_TRX
); // restore old setting
861 * @param string $property
864 private function getCacheKey( $property ) {
865 $cluster = is_string( $this->cluster
) ?
$this->cluster
: 'main';
867 return $this->cache
->makeGlobalKey(
877 * @param array|bool $params
880 protected static function makeBlob( $params ) {
881 if ( $params !== false ) {
882 return serialize( $params );
889 * @param string $blob
892 protected static function extractBlob( $blob ) {
893 if ( (string)$blob !== '' ) {
894 return unserialize( $blob );
902 * @throws JobQueueError
904 protected function throwDBException( DBError
$e ) {
905 throw new JobQueueError( get_class( $e ) . ": " . $e->getMessage() );
909 * Return the list of job fields that should be selected.
913 public static function selectFields() {
924 'job_token_timestamp',