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\Rdbms\IMaintainableDatabase
;
28 use Wikimedia\ScopedCallback
;
31 * Class to handle job queues stored in the DB
36 class JobQueueDB
extends JobQueue
{
37 const CACHE_TTL_SHORT
= 30; // integer; seconds to cache info without re-validating
38 const MAX_AGE_PRUNE
= 604800; // integer; seconds a job can live once claimed
39 const MAX_JOB_RANDOM
= 2147483647; // integer; 2^31 - 1, used for job_random
40 const MAX_OFFSET
= 255; // integer; maximum number of rows to skip
42 /** @var IMaintainableDatabase|DBError|null */
45 /** @var array|null Server configuration array */
47 /** @var string|null Name of an external DB cluster or null for the local DB cluster */
51 * Additional parameters include:
52 * - server : Server configuration array for Database::factory. Overrides "cluster".
53 * - cluster : The name of an external cluster registered via LBFactory.
54 * If not specified, the primary DB cluster for the wiki will be used.
55 * This can be overridden with a custom cluster so that DB handles will
56 * be retrieved via LBFactory::getExternalLB() and getConnection().
57 * @param array $params
59 protected function __construct( array $params ) {
60 parent
::__construct( $params );
62 if ( isset( $params['server'] ) ) {
63 $this->server
= $params['server'];
64 } elseif ( isset( $params['cluster'] ) && is_string( $params['cluster'] ) ) {
65 $this->cluster
= $params['cluster'];
69 protected function supportedOrders() {
70 return [ 'random', 'timestamp', 'fifo' ];
73 protected function optimalOrder() {
78 * @see JobQueue::doIsEmpty()
81 protected function doIsEmpty() {
82 $dbr = $this->getReplicaDB();
83 /** @noinspection PhpUnusedLocalVariableInspection */
84 $scope = $this->getScopedNoTrxFlag( $dbr );
86 $found = $dbr->selectField( // unclaimed job
87 'job', '1', [ 'job_cmd' => $this->type
, 'job_token' => '' ], __METHOD__
89 } catch ( DBError
$e ) {
90 throw $this->getDBException( $e );
97 * @see JobQueue::doGetSize()
100 protected function doGetSize() {
101 $key = $this->getCacheKey( 'size' );
103 $size = $this->wanCache
->get( $key );
104 if ( is_int( $size ) ) {
108 $dbr = $this->getReplicaDB();
109 /** @noinspection PhpUnusedLocalVariableInspection */
110 $scope = $this->getScopedNoTrxFlag( $dbr );
112 $size = (int)$dbr->selectField( 'job', 'COUNT(*)',
113 [ 'job_cmd' => $this->type
, 'job_token' => '' ],
116 } catch ( DBError
$e ) {
117 throw $this->getDBException( $e );
119 $this->wanCache
->set( $key, $size, self
::CACHE_TTL_SHORT
);
125 * @see JobQueue::doGetAcquiredCount()
128 protected function doGetAcquiredCount() {
129 if ( $this->claimTTL
<= 0 ) {
130 return 0; // no acknowledgements
133 $key = $this->getCacheKey( 'acquiredcount' );
135 $count = $this->wanCache
->get( $key );
136 if ( is_int( $count ) ) {
140 $dbr = $this->getReplicaDB();
141 /** @noinspection PhpUnusedLocalVariableInspection */
142 $scope = $this->getScopedNoTrxFlag( $dbr );
144 $count = (int)$dbr->selectField( 'job', 'COUNT(*)',
145 [ 'job_cmd' => $this->type
, "job_token != {$dbr->addQuotes( '' )}" ],
148 } catch ( DBError
$e ) {
149 throw $this->getDBException( $e );
151 $this->wanCache
->set( $key, $count, self
::CACHE_TTL_SHORT
);
157 * @see JobQueue::doGetAbandonedCount()
159 * @throws MWException
161 protected function doGetAbandonedCount() {
162 if ( $this->claimTTL
<= 0 ) {
163 return 0; // no acknowledgements
166 $key = $this->getCacheKey( 'abandonedcount' );
168 $count = $this->wanCache
->get( $key );
169 if ( is_int( $count ) ) {
173 $dbr = $this->getReplicaDB();
174 /** @noinspection PhpUnusedLocalVariableInspection */
175 $scope = $this->getScopedNoTrxFlag( $dbr );
177 $count = (int)$dbr->selectField( 'job', 'COUNT(*)',
179 'job_cmd' => $this->type
,
180 "job_token != {$dbr->addQuotes( '' )}",
181 "job_attempts >= " . $dbr->addQuotes( $this->maxTries
)
185 } catch ( DBError
$e ) {
186 throw $this->getDBException( $e );
189 $this->wanCache
->set( $key, $count, self
::CACHE_TTL_SHORT
);
195 * @see JobQueue::doBatchPush()
196 * @param IJobSpecification[] $jobs
198 * @throws DBError|Exception
201 protected function doBatchPush( array $jobs, $flags ) {
202 $dbw = $this->getMasterDB();
203 /** @noinspection PhpUnusedLocalVariableInspection */
204 $scope = $this->getScopedNoTrxFlag( $dbw );
205 // In general, there will be two cases here:
206 // a) sqlite; DB connection is probably a regular round-aware handle.
207 // If the connection is busy with a transaction, then defer the job writes
208 // until right before the main round commit step. Any errors that bubble
209 // up will rollback the main commit round.
210 // b) mysql/postgres; DB connection is generally a separate CONN_TRX_AUTOCOMMIT handle.
211 // No transaction is active nor will be started by writes, so enqueue the jobs
212 // now so that any errors will show up immediately as the interface expects. Any
213 // errors that bubble up will rollback the main commit round.
215 $dbw->onTransactionPreCommitOrIdle(
216 function ( IDatabase
$dbw ) use ( $jobs, $flags, $fname ) {
217 $this->doBatchPushInternal( $dbw, $jobs, $flags, $fname );
224 * This function should *not* be called outside of JobQueueDB
226 * @suppress SecurityCheck-SQLInjection Bug in phan-taint-check handling bulk inserts
227 * @param IDatabase $dbw
228 * @param IJobSpecification[] $jobs
230 * @param string $method
234 public function doBatchPushInternal( IDatabase
$dbw, array $jobs, $flags, $method ) {
235 if ( $jobs === [] ) {
239 $rowSet = []; // (sha1 => job) map for jobs that are de-duplicated
240 $rowList = []; // list of jobs for jobs that are not de-duplicated
241 foreach ( $jobs as $job ) {
242 $row = $this->insertFields( $job, $dbw );
243 if ( $job->ignoreDuplicates() ) {
244 $rowSet[$row['job_sha1']] = $row;
250 if ( $flags & self
::QOS_ATOMIC
) {
251 $dbw->startAtomic( $method ); // wrap all the job additions in one transaction
254 // Strip out any duplicate jobs that are already in the queue...
255 if ( count( $rowSet ) ) {
256 $res = $dbw->select( 'job', 'job_sha1',
258 // No job_type condition since it's part of the job_sha1 hash
259 'job_sha1' => array_keys( $rowSet ),
260 'job_token' => '' // unclaimed
264 foreach ( $res as $row ) {
265 wfDebug( "Job with hash '{$row->job_sha1}' is a duplicate.\n" );
266 unset( $rowSet[$row->job_sha1
] ); // already enqueued
269 // Build the full list of job rows to insert
270 $rows = array_merge( $rowList, array_values( $rowSet ) );
271 // Insert the job rows in chunks to avoid replica DB lag...
272 foreach ( array_chunk( $rows, 50 ) as $rowBatch ) {
273 $dbw->insert( 'job', $rowBatch, $method );
275 $this->incrStats( 'inserts', $this->type
, count( $rows ) );
276 $this->incrStats( 'dupe_inserts', $this->type
,
277 count( $rowSet ) +
count( $rowList ) - count( $rows )
279 } catch ( DBError
$e ) {
280 throw $this->getDBException( $e );
282 if ( $flags & self
::QOS_ATOMIC
) {
283 $dbw->endAtomic( $method );
288 * @see JobQueue::doPop()
289 * @return RunnableJob|bool
291 protected function doPop() {
292 $dbw = $this->getMasterDB();
293 /** @noinspection PhpUnusedLocalVariableInspection */
294 $scope = $this->getScopedNoTrxFlag( $dbw );
296 $job = false; // job popped off
298 $uuid = wfRandomString( 32 ); // pop attempt
299 do { // retry when our row is invalid or deleted as a duplicate
300 // Try to reserve a row in the DB...
301 if ( in_array( $this->order
, [ 'fifo', 'timestamp' ] ) ) {
302 $row = $this->claimOldest( $uuid );
303 } else { // random first
304 $rand = mt_rand( 0, self
::MAX_JOB_RANDOM
); // encourage concurrent UPDATEs
305 $gte = (bool)mt_rand( 0, 1 ); // find rows with rand before/after $rand
306 $row = $this->claimRandom( $uuid, $rand, $gte );
308 // Check if we found a row to reserve...
310 break; // nothing to do
312 $this->incrStats( 'pops', $this->type
);
314 // Get the job object from the row...
315 $job = $this->jobFromRow( $row );
319 if ( !$job ||
mt_rand( 0, 9 ) == 0 ) {
320 // Handled jobs that need to be recycled/deleted;
321 // any recycled jobs will be picked up next attempt
322 $this->recycleAndDeleteStaleJobs();
324 } catch ( DBError
$e ) {
325 throw $this->getDBException( $e );
332 * Reserve a row with a single UPDATE without holding row locks over RTTs...
334 * @param string $uuid 32 char hex string
335 * @param int $rand Random unsigned integer (31 bits)
336 * @param bool $gte Search for job_random >= $random (otherwise job_random <= $random)
337 * @return stdClass|bool Row|false
339 protected function claimRandom( $uuid, $rand, $gte ) {
340 $dbw = $this->getMasterDB();
341 /** @noinspection PhpUnusedLocalVariableInspection */
342 $scope = $this->getScopedNoTrxFlag( $dbw );
343 // Check cache to see if the queue has <= OFFSET items
344 $tinyQueue = $this->wanCache
->get( $this->getCacheKey( 'small' ) );
346 $invertedDirection = false; // whether one job_random direction was already scanned
347 // This uses a replication safe method for acquiring jobs. One could use UPDATE+LIMIT
348 // instead, but that either uses ORDER BY (in which case it deadlocks in MySQL) or is
349 // not replication safe. Due to https://bugs.mysql.com/bug.php?id=6980, subqueries cannot
350 // be used here with MySQL.
352 if ( $tinyQueue ) { // queue has <= MAX_OFFSET rows
353 // For small queues, using OFFSET will overshoot and return no rows more often.
354 // Instead, this uses job_random to pick a row (possibly checking both directions).
355 $ineq = $gte ?
'>=' : '<=';
356 $dir = $gte ?
'ASC' : 'DESC';
357 $row = $dbw->selectRow( 'job', self
::selectFields(), // find a random job
359 'job_cmd' => $this->type
,
360 'job_token' => '', // unclaimed
361 "job_random {$ineq} {$dbw->addQuotes( $rand )}" ],
363 [ 'ORDER BY' => "job_random {$dir}" ]
365 if ( !$row && !$invertedDirection ) {
367 $invertedDirection = true;
368 continue; // try the other direction
370 } else { // table *may* have >= MAX_OFFSET rows
371 // T44614: "ORDER BY job_random" with a job_random inequality causes high CPU
372 // in MySQL if there are many rows for some reason. This uses a small OFFSET
373 // instead of job_random for reducing excess claim retries.
374 $row = $dbw->selectRow( 'job', self
::selectFields(), // find a random job
376 'job_cmd' => $this->type
,
377 'job_token' => '', // unclaimed
380 [ 'OFFSET' => mt_rand( 0, self
::MAX_OFFSET
) ]
383 $tinyQueue = true; // we know the queue must have <= MAX_OFFSET rows
384 $this->wanCache
->set( $this->getCacheKey( 'small' ), 1, 30 );
385 continue; // use job_random
389 if ( $row ) { // claim the job
390 $dbw->update( 'job', // update by PK
392 'job_token' => $uuid,
393 'job_token_timestamp' => $dbw->timestamp(),
394 'job_attempts = job_attempts+1' ],
395 [ 'job_cmd' => $this->type
, 'job_id' => $row->job_id
, 'job_token' => '' ],
398 // This might get raced out by another runner when claiming the previously
399 // selected row. The use of job_random should minimize this problem, however.
400 if ( !$dbw->affectedRows() ) {
401 $row = false; // raced out
404 break; // nothing to do
412 * Reserve a row with a single UPDATE without holding row locks over RTTs...
414 * @param string $uuid 32 char hex string
415 * @return stdClass|bool Row|false
417 protected function claimOldest( $uuid ) {
418 $dbw = $this->getMasterDB();
419 /** @noinspection PhpUnusedLocalVariableInspection */
420 $scope = $this->getScopedNoTrxFlag( $dbw );
422 $row = false; // the row acquired
424 if ( $dbw->getType() === 'mysql' ) {
425 // Per https://bugs.mysql.com/bug.php?id=6980, we can't use subqueries on the
426 // same table being changed in an UPDATE query in MySQL (gives Error: 1093).
427 // Oracle and Postgre have no such limitation. However, MySQL offers an
428 // alternative here by supporting ORDER BY + LIMIT for UPDATE queries.
429 $dbw->query( "UPDATE {$dbw->tableName( 'job' )} " .
431 "job_token = {$dbw->addQuotes( $uuid ) }, " .
432 "job_token_timestamp = {$dbw->addQuotes( $dbw->timestamp() )}, " .
433 "job_attempts = job_attempts+1 " .
435 "job_cmd = {$dbw->addQuotes( $this->type )} " .
436 "AND job_token = {$dbw->addQuotes( '' )} " .
437 ") ORDER BY job_id ASC LIMIT 1",
441 // Use a subquery to find the job, within an UPDATE to claim it.
442 // This uses as much of the DB wrapper functions as possible.
445 'job_token' => $uuid,
446 'job_token_timestamp' => $dbw->timestamp(),
447 'job_attempts = job_attempts+1' ],
449 $dbw->selectSQLText( 'job', 'job_id',
450 [ 'job_cmd' => $this->type
, 'job_token' => '' ],
452 [ 'ORDER BY' => 'job_id ASC', 'LIMIT' => 1 ] ) .
458 // Fetch any row that we just reserved...
459 if ( $dbw->affectedRows() ) {
460 $row = $dbw->selectRow( 'job', self
::selectFields(),
461 [ 'job_cmd' => $this->type
, 'job_token' => $uuid ], __METHOD__
463 if ( !$row ) { // raced out by duplicate job removal
464 wfDebug( "Row deleted as duplicate by another process.\n" );
467 break; // nothing to do
475 * @see JobQueue::doAck()
476 * @param RunnableJob $job
477 * @throws MWException
479 protected function doAck( RunnableJob
$job ) {
480 $id = $job->getMetadata( 'id' );
481 if ( $id === null ) {
482 throw new MWException( "Job of type '{$job->getType()}' has no ID." );
485 $dbw = $this->getMasterDB();
486 /** @noinspection PhpUnusedLocalVariableInspection */
487 $scope = $this->getScopedNoTrxFlag( $dbw );
489 // Delete a row with a single DELETE without holding row locks over RTTs...
492 [ 'job_cmd' => $this->type
, 'job_id' => $id ],
496 $this->incrStats( 'acks', $this->type
);
497 } catch ( DBError
$e ) {
498 throw $this->getDBException( $e );
503 * @see JobQueue::doDeduplicateRootJob()
504 * @param IJobSpecification $job
505 * @throws MWException
508 protected function doDeduplicateRootJob( IJobSpecification
$job ) {
509 // Callers should call JobQueueGroup::push() before this method so that if the
510 // insert fails, the de-duplication registration will be aborted. Since the insert
511 // is 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 $dbw = $this->getMasterDB();
515 /** @noinspection PhpUnusedLocalVariableInspection */
516 $scope = $this->getScopedNoTrxFlag( $dbw );
517 $dbw->onTransactionCommitOrIdle(
518 function () use ( $job ) {
519 parent
::doDeduplicateRootJob( $job );
528 * @see JobQueue::doDelete()
531 protected function doDelete() {
532 $dbw = $this->getMasterDB();
533 /** @noinspection PhpUnusedLocalVariableInspection */
534 $scope = $this->getScopedNoTrxFlag( $dbw );
536 $dbw->delete( 'job', [ 'job_cmd' => $this->type
] );
537 } catch ( DBError
$e ) {
538 throw $this->getDBException( $e );
545 * @see JobQueue::doWaitForBackups()
548 protected function doWaitForBackups() {
549 if ( $this->server
) {
550 return; // not using LBFactory instance
553 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
554 $lbFactory->waitForReplication( [
555 'domain' => $this->domain
,
556 'cluster' => is_string( $this->cluster
) ?
$this->cluster
: false
563 protected function doFlushCaches() {
564 foreach ( [ 'size', 'acquiredcount' ] as $type ) {
565 $this->wanCache
->delete( $this->getCacheKey( $type ) );
570 * @see JobQueue::getAllQueuedJobs()
573 public function getAllQueuedJobs() {
574 return $this->getJobIterator( [ 'job_cmd' => $this->getType(), 'job_token' => '' ] );
578 * @see JobQueue::getAllAcquiredJobs()
581 public function getAllAcquiredJobs() {
582 return $this->getJobIterator( [ 'job_cmd' => $this->getType(), "job_token > ''" ] );
586 * @param array $conds Query conditions
589 protected function getJobIterator( array $conds ) {
590 $dbr = $this->getReplicaDB();
591 /** @noinspection PhpUnusedLocalVariableInspection */
592 $scope = $this->getScopedNoTrxFlag( $dbr );
594 return new MappedIterator(
595 $dbr->select( 'job', self
::selectFields(), $conds ),
597 return $this->jobFromRow( $row );
600 } catch ( DBError
$e ) {
601 throw $this->getDBException( $e );
605 public function getCoalesceLocationInternal() {
606 if ( $this->server
) {
607 return null; // not using the LBFactory instance
610 return is_string( $this->cluster
)
611 ?
"DBCluster:{$this->cluster}:{$this->domain}"
612 : "LBFactory:{$this->domain}";
615 protected function doGetSiblingQueuesWithJobs( array $types ) {
616 $dbr = $this->getReplicaDB();
617 /** @noinspection PhpUnusedLocalVariableInspection */
618 $scope = $this->getScopedNoTrxFlag( $dbr );
619 // @note: this does not check whether the jobs are claimed or not.
620 // This is useful so JobQueueGroup::pop() also sees queues that only
621 // have stale jobs. This lets recycleAndDeleteStaleJobs() re-enqueue
622 // failed jobs so that they can be popped again for that edge case.
623 $res = $dbr->select( 'job', 'DISTINCT job_cmd',
624 [ 'job_cmd' => $types ], __METHOD__
);
627 foreach ( $res as $row ) {
628 $types[] = $row->job_cmd
;
634 protected function doGetSiblingQueueSizes( array $types ) {
635 $dbr = $this->getReplicaDB();
636 /** @noinspection PhpUnusedLocalVariableInspection */
637 $scope = $this->getScopedNoTrxFlag( $dbr );
639 $res = $dbr->select( 'job', [ 'job_cmd', 'COUNT(*) AS count' ],
640 [ 'job_cmd' => $types ], __METHOD__
, [ 'GROUP BY' => 'job_cmd' ] );
643 foreach ( $res as $row ) {
644 $sizes[$row->job_cmd
] = (int)$row->count
;
651 * Recycle or destroy any jobs that have been claimed for too long
653 * @return int Number of jobs recycled/deleted
655 public function recycleAndDeleteStaleJobs() {
657 $count = 0; // affected rows
658 $dbw = $this->getMasterDB();
659 /** @noinspection PhpUnusedLocalVariableInspection */
660 $scope = $this->getScopedNoTrxFlag( $dbw );
663 if ( !$dbw->lock( "jobqueue-recycle-{$this->type}", __METHOD__
, 1 ) ) {
664 return $count; // already in progress
667 // Remove claims on jobs acquired for too long if enabled...
668 if ( $this->claimTTL
> 0 ) {
669 $claimCutoff = $dbw->timestamp( $now - $this->claimTTL
);
670 // Get the IDs of jobs that have be claimed but not finished after too long.
671 // These jobs can be recycled into the queue by expiring the claim. Selecting
672 // the IDs first means that the UPDATE can be done by primary key (less deadlocks).
673 $res = $dbw->select( 'job', 'job_id',
675 'job_cmd' => $this->type
,
676 "job_token != {$dbw->addQuotes( '' )}", // was acquired
677 "job_token_timestamp < {$dbw->addQuotes( $claimCutoff )}", // stale
678 "job_attempts < {$dbw->addQuotes( $this->maxTries )}" ], // retries left
684 }, iterator_to_array( $res )
686 if ( count( $ids ) ) {
687 // Reset job_token for these jobs so that other runners will pick them up.
688 // Set the timestamp to the current time, as it is useful to now that the job
689 // was already tried before (the timestamp becomes the "released" time).
693 'job_token_timestamp' => $dbw->timestamp( $now ) // time of release
695 [ 'job_id' => $ids, "job_token != ''" ],
698 $affected = $dbw->affectedRows();
700 $this->incrStats( 'recycles', $this->type
, $affected );
704 // Just destroy any stale jobs...
705 $pruneCutoff = $dbw->timestamp( $now - self
::MAX_AGE_PRUNE
);
707 'job_cmd' => $this->type
,
708 "job_token != {$dbw->addQuotes( '' )}", // was acquired
709 "job_token_timestamp < {$dbw->addQuotes( $pruneCutoff )}" // stale
711 if ( $this->claimTTL
> 0 ) { // only prune jobs attempted too many times...
712 $conds[] = "job_attempts >= {$dbw->addQuotes( $this->maxTries )}";
714 // Get the IDs of jobs that are considered stale and should be removed. Selecting
715 // the IDs first means that the UPDATE can be done by primary key (less deadlocks).
716 $res = $dbw->select( 'job', 'job_id', $conds, __METHOD__
);
720 }, iterator_to_array( $res )
722 if ( count( $ids ) ) {
723 $dbw->delete( 'job', [ 'job_id' => $ids ], __METHOD__
);
724 $affected = $dbw->affectedRows();
726 $this->incrStats( 'abandons', $this->type
, $affected );
729 $dbw->unlock( "jobqueue-recycle-{$this->type}", __METHOD__
);
730 } catch ( DBError
$e ) {
731 throw $this->getDBException( $e );
738 * @param IJobSpecification $job
739 * @param IDatabase $db
742 protected function insertFields( IJobSpecification
$job, IDatabase
$db ) {
744 // Fields that describe the nature of the job
745 'job_cmd' => $job->getType(),
746 'job_namespace' => $job->getParams()['namespace'] ?? NS_SPECIAL
,
747 'job_title' => $job->getParams()['title'] ??
'',
748 'job_params' => self
::makeBlob( $job->getParams() ),
749 // Additional job metadata
750 'job_timestamp' => $db->timestamp(),
751 'job_sha1' => Wikimedia\base_convert
(
752 sha1( serialize( $job->getDeduplicationInfo() ) ),
755 'job_random' => mt_rand( 0, self
::MAX_JOB_RANDOM
)
760 * @throws JobQueueConnectionError
763 protected function getReplicaDB() {
765 return $this->getDB( DB_REPLICA
);
766 } catch ( DBConnectionError
$e ) {
767 throw new JobQueueConnectionError( "DBConnectionError:" . $e->getMessage() );
772 * @throws JobQueueConnectionError
773 * @return IMaintainableDatabase
775 protected function getMasterDB() {
777 return $this->getDB( DB_MASTER
);
778 } catch ( DBConnectionError
$e ) {
779 throw new JobQueueConnectionError( "DBConnectionError:" . $e->getMessage() );
784 * @param int $index (DB_REPLICA/DB_MASTER)
785 * @return IMaintainableDatabase
787 protected function getDB( $index ) {
788 if ( $this->server
) {
789 if ( $this->conn
instanceof IDatabase
) {
791 } elseif ( $this->conn
instanceof DBError
) {
796 $this->conn
= Database
::factory( $this->server
['type'], $this->server
);
797 } catch ( DBError
$e ) {
804 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
805 $lb = is_string( $this->cluster
)
806 ?
$lbFactory->getExternalLB( $this->cluster
)
807 : $lbFactory->getMainLB( $this->domain
);
809 if ( $lb->getServerType( $lb->getWriterIndex() ) !== 'sqlite' ) {
810 // Keep a separate connection to avoid contention and deadlocks;
811 // However, SQLite has the opposite behavior due to DB-level locking.
812 $flags = $lb::CONN_TRX_AUTOCOMMIT
;
814 // Jobs insertion will be defered until the PRESEND stage to reduce contention.
818 return $lb->getMaintenanceConnectionRef( $index, [], $this->domain
, $flags );
823 * @param IDatabase $db
824 * @return ScopedCallback
826 private function getScopedNoTrxFlag( IDatabase
$db ) {
827 $autoTrx = $db->getFlag( DBO_TRX
); // get current setting
828 $db->clearFlag( DBO_TRX
); // make each query its own transaction
830 return new ScopedCallback( function () use ( $db, $autoTrx ) {
832 $db->setFlag( DBO_TRX
); // restore old setting
838 * @param string $property
841 private function getCacheKey( $property ) {
842 $cluster = is_string( $this->cluster
) ?
$this->cluster
: 'main';
844 return $this->wanCache
->makeGlobalKey(
854 * @param array|bool $params
857 protected static function makeBlob( $params ) {
858 if ( $params !== false ) {
859 return serialize( $params );
866 * @param stdClass $row
867 * @return RunnableJob|null
869 protected function jobFromRow( $row ) {
870 $params = ( (string)$row->job_params
!== '' ) ?
unserialize( $row->job_params
) : [];
871 if ( !is_array( $params ) ) { // this shouldn't happen
872 throw new UnexpectedValueException(
873 "Could not unserialize job with ID '{$row->job_id}'." );
876 $params +
= [ 'namespace' => $row->job_namespace
, 'title' => $row->job_title
];
877 $job = $this->factoryJob( $row->job_cmd
, $params );
878 $job->setMetadata( 'id', $row->job_id
);
879 $job->setMetadata( 'timestamp', $row->job_timestamp
);
886 * @return JobQueueError
888 protected function getDBException( DBError
$e ) {
889 return new JobQueueError( get_class( $e ) . ": " . $e->getMessage() );
893 * Return the list of job fields that should be selected.
897 public static function selectFields() {
908 'job_token_timestamp',