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->setMetadata( 'id', $row->job_id
);
321 $job->setMetadata( '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 $id = $job->getMetadata( 'id' );
488 if ( $id === null ) {
489 throw new MWException( "Job of type '{$job->getType()}' has no ID." );
492 $dbw = $this->getMasterDB();
493 /** @noinspection PhpUnusedLocalVariableInspection */
494 $scope = $this->getScopedNoTrxFlag( $dbw );
496 // Delete a row with a single DELETE without holding row locks over RTTs...
499 [ 'job_cmd' => $this->type
, 'job_id' => $id ],
503 JobQueue
::incrStats( 'acks', $this->type
);
504 } catch ( DBError
$e ) {
505 $this->throwDBException( $e );
510 * @see JobQueue::doDeduplicateRootJob()
511 * @param IJobSpecification $job
512 * @throws MWException
515 protected function doDeduplicateRootJob( IJobSpecification
$job ) {
516 $params = $job->getParams();
517 if ( !isset( $params['rootJobSignature'] ) ) {
518 throw new MWException( "Cannot register root job; missing 'rootJobSignature'." );
519 } elseif ( !isset( $params['rootJobTimestamp'] ) ) {
520 throw new MWException( "Cannot register root job; missing 'rootJobTimestamp'." );
522 $key = $this->getRootJobCacheKey( $params['rootJobSignature'] );
523 // Callers should call JobQueueGroup::push() before this method so that if the insert
524 // fails, the de-duplication registration will be aborted. Since the insert is
525 // deferred till "transaction idle", do the same here, so that the ordering is
526 // maintained. Having only the de-duplication registration succeed would cause
527 // jobs to become no-ops without any actual jobs that made them redundant.
528 $dbw = $this->getMasterDB();
529 /** @noinspection PhpUnusedLocalVariableInspection */
530 $scope = $this->getScopedNoTrxFlag( $dbw );
532 $cache = $this->dupCache
;
533 $dbw->onTransactionCommitOrIdle(
534 function () use ( $cache, $params, $key ) {
535 $timestamp = $cache->get( $key ); // current last timestamp of this job
536 if ( $timestamp && $timestamp >= $params['rootJobTimestamp'] ) {
537 return true; // a newer version of this root job was enqueued
540 // Update the timestamp of the last root job started at the location...
541 return $cache->set( $key, $params['rootJobTimestamp'], JobQueueDB
::ROOTJOB_TTL
);
550 * @see JobQueue::doDelete()
553 protected function doDelete() {
554 $dbw = $this->getMasterDB();
555 /** @noinspection PhpUnusedLocalVariableInspection */
556 $scope = $this->getScopedNoTrxFlag( $dbw );
558 $dbw->delete( 'job', [ 'job_cmd' => $this->type
] );
559 } catch ( DBError
$e ) {
560 $this->throwDBException( $e );
567 * @see JobQueue::doWaitForBackups()
570 protected function doWaitForBackups() {
571 if ( $this->server
) {
572 return; // not using LBFactory instance
575 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
576 $lbFactory->waitForReplication( [
577 'domain' => $this->domain
,
578 'cluster' => is_string( $this->cluster
) ?
$this->cluster
: false
585 protected function doFlushCaches() {
586 foreach ( [ 'size', 'acquiredcount' ] as $type ) {
587 $this->cache
->delete( $this->getCacheKey( $type ) );
592 * @see JobQueue::getAllQueuedJobs()
595 public function getAllQueuedJobs() {
596 return $this->getJobIterator( [ 'job_cmd' => $this->getType(), 'job_token' => '' ] );
600 * @see JobQueue::getAllAcquiredJobs()
603 public function getAllAcquiredJobs() {
604 return $this->getJobIterator( [ 'job_cmd' => $this->getType(), "job_token > ''" ] );
608 * @param array $conds Query conditions
611 protected function getJobIterator( array $conds ) {
612 $dbr = $this->getReplicaDB();
613 /** @noinspection PhpUnusedLocalVariableInspection */
614 $scope = $this->getScopedNoTrxFlag( $dbr );
616 return new MappedIterator(
617 $dbr->select( 'job', self
::selectFields(), $conds ),
621 Title
::makeTitle( $row->job_namespace
, $row->job_title
),
622 strlen( $row->job_params
) ?
unserialize( $row->job_params
) : []
624 $job->setMetadata( 'id', $row->job_id
);
625 $job->setMetadata( 'timestamp', $row->job_timestamp
);
630 } catch ( DBError
$e ) {
631 $this->throwDBException( $e );
635 public function getCoalesceLocationInternal() {
636 if ( $this->server
) {
637 return null; // not using the LBFactory instance
640 return is_string( $this->cluster
)
641 ?
"DBCluster:{$this->cluster}:{$this->domain}"
642 : "LBFactory:{$this->domain}";
645 protected function doGetSiblingQueuesWithJobs( array $types ) {
646 $dbr = $this->getReplicaDB();
647 /** @noinspection PhpUnusedLocalVariableInspection */
648 $scope = $this->getScopedNoTrxFlag( $dbr );
649 // @note: this does not check whether the jobs are claimed or not.
650 // This is useful so JobQueueGroup::pop() also sees queues that only
651 // have stale jobs. This lets recycleAndDeleteStaleJobs() re-enqueue
652 // failed jobs so that they can be popped again for that edge case.
653 $res = $dbr->select( 'job', 'DISTINCT job_cmd',
654 [ 'job_cmd' => $types ], __METHOD__
);
657 foreach ( $res as $row ) {
658 $types[] = $row->job_cmd
;
664 protected function doGetSiblingQueueSizes( array $types ) {
665 $dbr = $this->getReplicaDB();
666 /** @noinspection PhpUnusedLocalVariableInspection */
667 $scope = $this->getScopedNoTrxFlag( $dbr );
669 $res = $dbr->select( 'job', [ 'job_cmd', 'COUNT(*) AS count' ],
670 [ 'job_cmd' => $types ], __METHOD__
, [ 'GROUP BY' => 'job_cmd' ] );
673 foreach ( $res as $row ) {
674 $sizes[$row->job_cmd
] = (int)$row->count
;
681 * Recycle or destroy any jobs that have been claimed for too long
683 * @return int Number of jobs recycled/deleted
685 public function recycleAndDeleteStaleJobs() {
687 $count = 0; // affected rows
688 $dbw = $this->getMasterDB();
689 /** @noinspection PhpUnusedLocalVariableInspection */
690 $scope = $this->getScopedNoTrxFlag( $dbw );
693 if ( !$dbw->lock( "jobqueue-recycle-{$this->type}", __METHOD__
, 1 ) ) {
694 return $count; // already in progress
697 // Remove claims on jobs acquired for too long if enabled...
698 if ( $this->claimTTL
> 0 ) {
699 $claimCutoff = $dbw->timestamp( $now - $this->claimTTL
);
700 // Get the IDs of jobs that have be claimed but not finished after too long.
701 // These jobs can be recycled into the queue by expiring the claim. Selecting
702 // the IDs first means that the UPDATE can be done by primary key (less deadlocks).
703 $res = $dbw->select( 'job', 'job_id',
705 'job_cmd' => $this->type
,
706 "job_token != {$dbw->addQuotes( '' )}", // was acquired
707 "job_token_timestamp < {$dbw->addQuotes( $claimCutoff )}", // stale
708 "job_attempts < {$dbw->addQuotes( $this->maxTries )}" ], // retries left
714 }, iterator_to_array( $res )
716 if ( count( $ids ) ) {
717 // Reset job_token for these jobs so that other runners will pick them up.
718 // Set the timestamp to the current time, as it is useful to now that the job
719 // was already tried before (the timestamp becomes the "released" time).
723 'job_token_timestamp' => $dbw->timestamp( $now ) ], // time of release
728 $affected = $dbw->affectedRows();
730 JobQueue
::incrStats( 'recycles', $this->type
, $affected );
731 $this->aggr
->notifyQueueNonEmpty( $this->domain
, $this->type
);
735 // Just destroy any stale jobs...
736 $pruneCutoff = $dbw->timestamp( $now - self
::MAX_AGE_PRUNE
);
738 'job_cmd' => $this->type
,
739 "job_token != {$dbw->addQuotes( '' )}", // was acquired
740 "job_token_timestamp < {$dbw->addQuotes( $pruneCutoff )}" // stale
742 if ( $this->claimTTL
> 0 ) { // only prune jobs attempted too many times...
743 $conds[] = "job_attempts >= {$dbw->addQuotes( $this->maxTries )}";
745 // Get the IDs of jobs that are considered stale and should be removed. Selecting
746 // the IDs first means that the UPDATE can be done by primary key (less deadlocks).
747 $res = $dbw->select( 'job', 'job_id', $conds, __METHOD__
);
751 }, iterator_to_array( $res )
753 if ( count( $ids ) ) {
754 $dbw->delete( 'job', [ 'job_id' => $ids ], __METHOD__
);
755 $affected = $dbw->affectedRows();
757 JobQueue
::incrStats( 'abandons', $this->type
, $affected );
760 $dbw->unlock( "jobqueue-recycle-{$this->type}", __METHOD__
);
761 } catch ( DBError
$e ) {
762 $this->throwDBException( $e );
769 * @param IJobSpecification $job
770 * @param IDatabase $db
773 protected function insertFields( IJobSpecification
$job, IDatabase
$db ) {
775 // Fields that describe the nature of the job
776 'job_cmd' => $job->getType(),
777 'job_namespace' => $job->getTitle()->getNamespace(),
778 'job_title' => $job->getTitle()->getDBkey(),
779 'job_params' => self
::makeBlob( $job->getParams() ),
780 // Additional job metadata
781 'job_timestamp' => $db->timestamp(),
782 'job_sha1' => Wikimedia\base_convert
(
783 sha1( serialize( $job->getDeduplicationInfo() ) ),
786 'job_random' => mt_rand( 0, self
::MAX_JOB_RANDOM
)
791 * @throws JobQueueConnectionError
794 protected function getReplicaDB() {
796 return $this->getDB( DB_REPLICA
);
797 } catch ( DBConnectionError
$e ) {
798 throw new JobQueueConnectionError( "DBConnectionError:" . $e->getMessage() );
803 * @throws JobQueueConnectionError
806 protected function getMasterDB() {
808 return $this->getDB( DB_MASTER
);
809 } catch ( DBConnectionError
$e ) {
810 throw new JobQueueConnectionError( "DBConnectionError:" . $e->getMessage() );
815 * @param int $index (DB_REPLICA/DB_MASTER)
818 protected function getDB( $index ) {
819 if ( $this->server
) {
820 if ( $this->conn
instanceof IDatabase
) {
822 } elseif ( $this->conn
instanceof DBError
) {
827 $this->conn
= Database
::factory( $this->server
['type'], $this->server
);
828 } catch ( DBError
$e ) {
835 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
836 $lb = is_string( $this->cluster
)
837 ?
$lbFactory->getExternalLB( $this->cluster
)
838 : $lbFactory->getMainLB( $this->domain
);
840 return ( $lb->getServerType( $lb->getWriterIndex() ) !== 'sqlite' )
841 // Keep a separate connection to avoid contention and deadlocks;
842 // However, SQLite has the opposite behavior due to DB-level locking.
843 ?
$lb->getConnectionRef( $index, [], $this->domain
, $lb::CONN_TRX_AUTOCOMMIT
)
844 // Jobs insertion will be defered until the PRESEND stage to reduce contention.
845 : $lb->getConnectionRef( $index, [], $this->domain
);
850 * @param IDatabase $db
851 * @return ScopedCallback
853 private function getScopedNoTrxFlag( IDatabase
$db ) {
854 $autoTrx = $db->getFlag( DBO_TRX
); // get current setting
855 $db->clearFlag( DBO_TRX
); // make each query its own transaction
857 return new ScopedCallback( function () use ( $db, $autoTrx ) {
859 $db->setFlag( DBO_TRX
); // restore old setting
865 * @param string $property
868 private function getCacheKey( $property ) {
869 $cluster = is_string( $this->cluster
) ?
$this->cluster
: 'main';
871 return $this->cache
->makeGlobalKey(
881 * @param array|bool $params
884 protected static function makeBlob( $params ) {
885 if ( $params !== false ) {
886 return serialize( $params );
893 * @param string $blob
896 protected static function extractBlob( $blob ) {
897 if ( (string)$blob !== '' ) {
898 return unserialize( $blob );
906 * @throws JobQueueError
908 protected function throwDBException( DBError
$e ) {
909 throw new JobQueueError( get_class( $e ) . ": " . $e->getMessage() );
913 * Return the list of job fields that should be selected.
917 public static function selectFields() {
928 'job_token_timestamp',