3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
20 use MediaWiki\MediaWikiServices
;
21 use Wikimedia\Rdbms\DBConnectionError
;
22 use Wikimedia\Rdbms\DBError
;
23 use Wikimedia\Rdbms\IDatabase
;
24 use Wikimedia\Rdbms\IMaintainableDatabase
;
25 use Wikimedia\Rdbms\IReadableDatabase
;
26 use Wikimedia\Rdbms\RawSQLValue
;
27 use Wikimedia\Rdbms\SelectQueryBuilder
;
28 use Wikimedia\Rdbms\ServerInfo
;
29 use Wikimedia\ScopedCallback
;
32 * Database-backed job queue storage.
37 class JobQueueDB
extends JobQueue
{
38 /* seconds to cache info without re-validating */
39 private const CACHE_TTL_SHORT
= 30;
40 /* seconds a job can live once claimed */
41 private const MAX_AGE_PRUNE
= 7 * 24 * 3600;
43 * Used for job_random, the highest safe 32-bit signed integer.
44 * Equivalent to `( 2 ** 31 ) - 1` on 64-bit.
46 private const MAX_JOB_RANDOM
= 2_147_483_647
;
47 /* maximum number of rows to skip */
48 private const MAX_OFFSET
= 255;
50 /** @var IMaintainableDatabase|DBError|null */
53 /** @var array|null Server configuration array */
55 /** @var string|null Name of an external DB cluster or null for the local DB cluster */
59 * Additional parameters include:
60 * - server : Server configuration array for Database::factory. Overrides "cluster".
61 * - cluster : The name of an external cluster registered via LBFactory.
62 * If not specified, the primary DB cluster for the wiki will be used.
63 * This can be overridden with a custom cluster so that DB handles will
64 * be retrieved via LBFactory::getExternalLB() and getConnection().
65 * @param array $params
67 protected function __construct( array $params ) {
68 parent
::__construct( $params );
70 if ( isset( $params['server'] ) ) {
71 $this->server
= $params['server'];
72 // Always use autocommit mode, even if DBO_TRX is configured
73 $this->server
['flags'] ??
= 0;
74 $this->server
['flags'] &= ~
( IDatabase
::DBO_TRX | IDatabase
::DBO_DEFAULT
);
75 } elseif ( isset( $params['cluster'] ) && is_string( $params['cluster'] ) ) {
76 $this->cluster
= $params['cluster'];
80 protected function supportedOrders() {
81 return [ 'random', 'timestamp', 'fifo' ];
84 protected function optimalOrder() {
89 * @see JobQueue::doIsEmpty()
92 protected function doIsEmpty() {
93 $dbr = $this->getReplicaDB();
96 $found = (bool)$dbr->newSelectQueryBuilder()
99 ->where( [ 'job_cmd' => $this->type
, 'job_token' => '' ] )
100 ->caller( __METHOD__
)->fetchField();
101 } catch ( DBError
$e ) {
102 throw $this->getDBException( $e );
109 * @see JobQueue::doGetSize()
112 protected function doGetSize() {
113 $key = $this->getCacheKey( 'size' );
115 $size = $this->wanCache
->get( $key );
116 if ( is_int( $size ) ) {
120 $dbr = $this->getReplicaDB();
122 $size = $dbr->newSelectQueryBuilder()
124 ->where( [ 'job_cmd' => $this->type
, 'job_token' => '' ] )
125 ->caller( __METHOD__
)->fetchRowCount();
126 } catch ( DBError
$e ) {
127 throw $this->getDBException( $e );
129 $this->wanCache
->set( $key, $size, self
::CACHE_TTL_SHORT
);
135 * @see JobQueue::doGetAcquiredCount()
138 protected function doGetAcquiredCount() {
139 if ( $this->claimTTL
<= 0 ) {
140 return 0; // no acknowledgements
143 $key = $this->getCacheKey( 'acquiredcount' );
145 $count = $this->wanCache
->get( $key );
146 if ( is_int( $count ) ) {
150 $dbr = $this->getReplicaDB();
152 $count = $dbr->newSelectQueryBuilder()
155 'job_cmd' => $this->type
,
156 $dbr->expr( 'job_token', '!=', '' ),
158 ->caller( __METHOD__
)->fetchRowCount();
159 } catch ( DBError
$e ) {
160 throw $this->getDBException( $e );
162 $this->wanCache
->set( $key, $count, self
::CACHE_TTL_SHORT
);
168 * @see JobQueue::doGetAbandonedCount()
170 * @throws JobQueueConnectionError
171 * @throws JobQueueError
173 protected function doGetAbandonedCount() {
174 if ( $this->claimTTL
<= 0 ) {
175 return 0; // no acknowledgements
178 $key = $this->getCacheKey( 'abandonedcount' );
180 $count = $this->wanCache
->get( $key );
181 if ( is_int( $count ) ) {
185 $dbr = $this->getReplicaDB();
187 $count = $dbr->newSelectQueryBuilder()
191 'job_cmd' => $this->type
,
192 $dbr->expr( 'job_token', '!=', '' ),
193 $dbr->expr( 'job_attempts', '>=', $this->maxTries
),
196 ->caller( __METHOD__
)->fetchRowCount();
197 } catch ( DBError
$e ) {
198 throw $this->getDBException( $e );
201 $this->wanCache
->set( $key, $count, self
::CACHE_TTL_SHORT
);
207 * @see JobQueue::doBatchPush()
208 * @param IJobSpecification[] $jobs
210 * @throws DBError|Exception
213 protected function doBatchPush( array $jobs, $flags ) {
214 // Silence expectations related to getting a primary DB, as we have to get a primary DB to insert the job.
215 $transactionProfiler = Profiler
::instance()->getTransactionProfiler();
216 $scope = $transactionProfiler->silenceForScope();
217 $dbw = $this->getPrimaryDB();
218 ScopedCallback
::consume( $scope );
219 // In general, there will be two cases here:
220 // a) sqlite; DB connection is probably a regular round-aware handle.
221 // If the connection is busy with a transaction, then defer the job writes
222 // until right before the main round commit step. Any errors that bubble
223 // up will rollback the main commit round.
224 // b) mysql/postgres; DB connection is generally a separate CONN_TRX_AUTOCOMMIT handle.
225 // No transaction is active nor will be started by writes, so enqueue the jobs
226 // now so that any errors will show up immediately as the interface expects. Any
227 // errors that bubble up will rollback the main commit round.
229 $dbw->onTransactionPreCommitOrIdle(
230 function ( IDatabase
$dbw ) use ( $jobs, $flags, $fname ) {
231 $this->doBatchPushInternal( $dbw, $jobs, $flags, $fname );
238 * This function should *not* be called outside of JobQueueDB
240 * @suppress SecurityCheck-SQLInjection Bug in phan-taint-check handling bulk inserts
241 * @param IDatabase $dbw
242 * @param IJobSpecification[] $jobs
244 * @param string $method
248 public function doBatchPushInternal( IDatabase
$dbw, array $jobs, $flags, $method ) {
249 if ( $jobs === [] ) {
253 $rowSet = []; // (sha1 => job) map for jobs that are de-duplicated
254 $rowList = []; // list of jobs for jobs that are not de-duplicated
255 foreach ( $jobs as $job ) {
256 $row = $this->insertFields( $job, $dbw );
257 if ( $job->ignoreDuplicates() ) {
258 $rowSet[$row['job_sha1']] = $row;
264 if ( $flags & self
::QOS_ATOMIC
) {
265 $dbw->startAtomic( $method ); // wrap all the job additions in one transaction
268 // Strip out any duplicate jobs that are already in the queue...
269 if ( count( $rowSet ) ) {
270 $res = $dbw->newSelectQueryBuilder()
271 ->select( 'job_sha1' )
275 // No job_type condition since it's part of the job_sha1 hash
276 'job_sha1' => array_map( 'strval', array_keys( $rowSet ) ),
277 'job_token' => '' // unclaimed
280 ->caller( $method )->fetchResultSet();
281 foreach ( $res as $row ) {
282 wfDebug( "Job with hash '{$row->job_sha1}' is a duplicate." );
283 unset( $rowSet[$row->job_sha1
] ); // already enqueued
286 // Build the full list of job rows to insert
287 $rows = array_merge( $rowList, array_values( $rowSet ) );
288 // Silence expectations related to inserting to the job table, because we have to perform the inserts to
290 $transactionProfiler = Profiler
::instance()->getTransactionProfiler();
291 $scope = $transactionProfiler->silenceForScope();
292 // Insert the job rows in chunks to avoid replica DB lag...
293 foreach ( array_chunk( $rows, 50 ) as $rowBatch ) {
294 $dbw->newInsertQueryBuilder()
295 ->insertInto( 'job' )
297 ->caller( $method )->execute();
299 ScopedCallback
::consume( $scope );
300 $this->incrStats( 'inserts', $this->type
, count( $rows ) );
301 $this->incrStats( 'dupe_inserts', $this->type
,
302 count( $rowSet ) +
count( $rowList ) - count( $rows )
304 } catch ( DBError
$e ) {
305 throw $this->getDBException( $e );
307 if ( $flags & self
::QOS_ATOMIC
) {
308 $dbw->endAtomic( $method );
313 * @see JobQueue::doPop()
314 * @return RunnableJob|false
316 protected function doPop() {
317 $job = false; // job popped off
319 $uuid = wfRandomString( 32 ); // pop attempt
320 do { // retry when our row is invalid or deleted as a duplicate
321 // Try to reserve a row in the DB...
322 if ( in_array( $this->order
, [ 'fifo', 'timestamp' ] ) ) {
323 $row = $this->claimOldest( $uuid );
324 } else { // random first
325 $rand = mt_rand( 0, self
::MAX_JOB_RANDOM
); // encourage concurrent UPDATEs
326 $gte = (bool)mt_rand( 0, 1 ); // find rows with rand before/after $rand
327 $row = $this->claimRandom( $uuid, $rand, $gte );
329 // Check if we found a row to reserve...
331 break; // nothing to do
333 $this->incrStats( 'pops', $this->type
);
335 // Get the job object from the row...
336 $job = $this->jobFromRow( $row );
340 if ( !$job ||
mt_rand( 0, 9 ) == 0 ) {
341 // Handled jobs that need to be recycled/deleted;
342 // any recycled jobs will be picked up next attempt
343 $this->recycleAndDeleteStaleJobs();
345 } catch ( DBError
$e ) {
346 throw $this->getDBException( $e );
353 * Reserve a row with a single UPDATE without holding row locks over RTTs...
355 * @param string $uuid 32 char hex string
356 * @param int $rand Random unsigned integer (31 bits)
357 * @param bool $gte Search for job_random >= $random (otherwise job_random <= $random)
358 * @return stdClass|false Row|false
360 protected function claimRandom( $uuid, $rand, $gte ) {
361 $dbw = $this->getPrimaryDB();
362 // Check cache to see if the queue has <= OFFSET items
363 $tinyQueue = $this->wanCache
->get( $this->getCacheKey( 'small' ) );
365 $invertedDirection = false; // whether one job_random direction was already scanned
366 // This uses a replication safe method for acquiring jobs. One could use UPDATE+LIMIT
367 // instead, but that either uses ORDER BY (in which case it deadlocks in MySQL) or is
368 // not replication safe. Due to https://bugs.mysql.com/bug.php?id=6980, subqueries cannot
369 // be used here with MySQL.
371 if ( $tinyQueue ) { // queue has <= MAX_OFFSET rows
372 // For small queues, using OFFSET will overshoot and return no rows more often.
373 // Instead, this uses job_random to pick a row (possibly checking both directions).
374 $row = $dbw->newSelectQueryBuilder()
375 ->select( self
::selectFields() )
379 'job_cmd' => $this->type
,
380 'job_token' => '', // unclaimed
381 $dbw->expr( 'job_random', $gte ?
'>=' : '<=', $rand )
386 $gte ? SelectQueryBuilder
::SORT_ASC
: SelectQueryBuilder
::SORT_DESC
388 ->caller( __METHOD__
)->fetchRow();
389 if ( !$row && !$invertedDirection ) {
391 $invertedDirection = true;
392 continue; // try the other direction
394 } else { // table *may* have >= MAX_OFFSET rows
395 // T44614: "ORDER BY job_random" with a job_random inequality causes high CPU
396 // in MySQL if there are many rows for some reason. This uses a small OFFSET
397 // instead of job_random for reducing excess claim retries.
398 $row = $dbw->newSelectQueryBuilder()
399 ->select( self
::selectFields() )
403 'job_cmd' => $this->type
,
404 'job_token' => '', // unclaimed
407 ->offset( mt_rand( 0, self
::MAX_OFFSET
) )
408 ->caller( __METHOD__
)->fetchRow();
410 $tinyQueue = true; // we know the queue must have <= MAX_OFFSET rows
411 $this->wanCache
->set( $this->getCacheKey( 'small' ), 1, 30 );
412 continue; // use job_random
420 $dbw->newUpdateQueryBuilder()
421 ->update( 'job' ) // update by PK
423 'job_token' => $uuid,
424 'job_token_timestamp' => $dbw->timestamp(),
425 'job_attempts' => new RawSQLValue( 'job_attempts+1' ),
428 'job_cmd' => $this->type
,
429 'job_id' => $row->job_id
,
432 ->caller( __METHOD__
)->execute();
434 // This might get raced out by another runner when claiming the previously
435 // selected row. The use of job_random should minimize this problem, however.
436 if ( !$dbw->affectedRows() ) {
437 $row = false; // raced out
445 * Reserve a row with a single UPDATE without holding row locks over RTTs...
447 * @param string $uuid 32 char hex string
448 * @return stdClass|false Row|false
450 protected function claimOldest( $uuid ) {
451 $dbw = $this->getPrimaryDB();
453 $row = false; // the row acquired
455 if ( $dbw->getType() === 'mysql' ) {
456 // Per https://bugs.mysql.com/bug.php?id=6980, we can't use subqueries on the
457 // same table being changed in an UPDATE query in MySQL (gives Error: 1093).
458 // Postgres has no such limitation. However, MySQL offers an
459 // alternative here by supporting ORDER BY + LIMIT for UPDATE queries.
460 $dbw->query( "UPDATE {$dbw->tableName( 'job' )} " .
462 "job_token = {$dbw->addQuotes( $uuid ) }, " .
463 "job_token_timestamp = {$dbw->addQuotes( $dbw->timestamp() )}, " .
464 "job_attempts = job_attempts+1 " .
466 "job_cmd = {$dbw->addQuotes( $this->type )} " .
467 "AND job_token = {$dbw->addQuotes( '' )} " .
468 ") ORDER BY job_id ASC LIMIT 1",
472 // Use a subquery to find the job, within an UPDATE to claim it.
473 // This uses as much of the DB wrapper functions as possible.
474 $qb = $dbw->newSelectQueryBuilder()
477 ->where( [ 'job_cmd' => $this->type
, 'job_token' => '' ] )
478 ->orderBy( 'job_id', SelectQueryBuilder
::SORT_ASC
)
481 $dbw->newUpdateQueryBuilder()
484 'job_token' => $uuid,
485 'job_token_timestamp' => $dbw->timestamp(),
486 'job_attempts' => new RawSQLValue( 'job_attempts+1' ),
488 ->where( [ 'job_id' => new RawSQLValue( '(' . $qb->getSQL() . ')' ) ] )
489 ->caller( __METHOD__
)->execute();
492 if ( !$dbw->affectedRows() ) {
496 // Fetch any row that we just reserved...
497 $row = $dbw->newSelectQueryBuilder()
498 ->select( self
::selectFields() )
500 ->where( [ 'job_cmd' => $this->type
, 'job_token' => $uuid ] )
501 ->caller( __METHOD__
)->fetchRow();
502 if ( !$row ) { // raced out by duplicate job removal
503 wfDebug( "Row deleted as duplicate by another process." );
511 * @see JobQueue::doAck()
512 * @param RunnableJob $job
513 * @throws JobQueueConnectionError
514 * @throws JobQueueError
516 protected function doAck( RunnableJob
$job ) {
517 $id = $job->getMetadata( 'id' );
518 if ( $id === null ) {
519 throw new UnexpectedValueException( "Job of type '{$job->getType()}' has no ID." );
522 $dbw = $this->getPrimaryDB();
524 // Delete a row with a single DELETE without holding row locks over RTTs...
525 $dbw->newDeleteQueryBuilder()
526 ->deleteFrom( 'job' )
527 ->where( [ 'job_cmd' => $this->type
, 'job_id' => $id ] )
528 ->caller( __METHOD__
)->execute();
530 $this->incrStats( 'acks', $this->type
);
531 } catch ( DBError
$e ) {
532 throw $this->getDBException( $e );
537 * @see JobQueue::doDeduplicateRootJob()
538 * @param IJobSpecification $job
539 * @throws JobQueueConnectionError
542 protected function doDeduplicateRootJob( IJobSpecification
$job ) {
543 // Callers should call JobQueueGroup::push() before this method so that if the
544 // insert fails, the de-duplication registration will be aborted. Since the insert
545 // is deferred till "transaction idle", do the same here, so that the ordering is
546 // maintained. Having only the de-duplication registration succeed would cause
547 // jobs to become no-ops without any actual jobs that made them redundant.
548 $dbw = $this->getPrimaryDB();
549 $dbw->onTransactionCommitOrIdle(
550 function () use ( $job ) {
551 parent
::doDeduplicateRootJob( $job );
560 * @see JobQueue::doDelete()
563 protected function doDelete() {
564 $dbw = $this->getPrimaryDB();
566 $dbw->newDeleteQueryBuilder()
567 ->deleteFrom( 'job' )
568 ->where( [ 'job_cmd' => $this->type
] )
569 ->caller( __METHOD__
)->execute();
570 } catch ( DBError
$e ) {
571 throw $this->getDBException( $e );
578 * @see JobQueue::doWaitForBackups()
581 protected function doWaitForBackups() {
582 if ( $this->server
) {
583 return; // not using LBFactory instance
586 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
587 $lbFactory->waitForReplication();
593 protected function doFlushCaches() {
594 foreach ( [ 'size', 'acquiredcount' ] as $type ) {
595 $this->wanCache
->delete( $this->getCacheKey( $type ) );
600 * @see JobQueue::getAllQueuedJobs()
601 * @return Iterator<RunnableJob>
603 public function getAllQueuedJobs() {
604 return $this->getJobIterator( [ 'job_cmd' => $this->getType(), 'job_token' => '' ] );
608 * @see JobQueue::getAllAcquiredJobs()
609 * @return Iterator<RunnableJob>
611 public function getAllAcquiredJobs() {
612 $dbr = $this->getReplicaDB();
613 return $this->getJobIterator( [ 'job_cmd' => $this->getType(), $dbr->expr( 'job_token', '>', '' ) ] );
617 * @see JobQueue::getAllAbandonedJobs()
618 * @return Iterator<RunnableJob>
620 public function getAllAbandonedJobs() {
621 $dbr = $this->getReplicaDB();
622 return $this->getJobIterator( [
623 'job_cmd' => $this->getType(),
624 $dbr->expr( 'job_token', '>', '' ),
625 $dbr->expr( 'job_attempts', '>=', intval( $this->maxTries
) ),
630 * @param array $conds Query conditions
631 * @return Iterator<RunnableJob>
633 protected function getJobIterator( array $conds ) {
634 $dbr = $this->getReplicaDB();
635 $qb = $dbr->newSelectQueryBuilder()
636 ->select( self
::selectFields() )
640 return new MappedIterator(
641 $qb->caller( __METHOD__
)->fetchResultSet(),
643 return $this->jobFromRow( $row );
646 } catch ( DBError
$e ) {
647 throw $this->getDBException( $e );
651 public function getCoalesceLocationInternal() {
652 if ( $this->server
) {
653 return null; // not using the LBFactory instance
656 return is_string( $this->cluster
)
657 ?
"DBCluster:{$this->cluster}:{$this->domain}"
658 : "LBFactory:{$this->domain}";
661 protected function doGetSiblingQueuesWithJobs( array $types ) {
662 $dbr = $this->getReplicaDB();
663 // @note: this does not check whether the jobs are claimed or not.
664 // This is useful so JobQueueGroup::pop() also sees queues that only
665 // have stale jobs. This lets recycleAndDeleteStaleJobs() re-enqueue
666 // failed jobs so that they can be popped again for that edge case.
667 $res = $dbr->newSelectQueryBuilder()
668 ->select( 'job_cmd' )
671 ->where( [ 'job_cmd' => $types ] )
672 ->caller( __METHOD__
)->fetchResultSet();
675 foreach ( $res as $row ) {
676 $types[] = $row->job_cmd
;
682 protected function doGetSiblingQueueSizes( array $types ) {
683 $dbr = $this->getReplicaDB();
685 $res = $dbr->newSelectQueryBuilder()
686 ->select( [ 'job_cmd', 'count' => 'COUNT(*)' ] )
688 ->where( [ 'job_cmd' => $types ] )
689 ->groupBy( 'job_cmd' )
690 ->caller( __METHOD__
)->fetchResultSet();
693 foreach ( $res as $row ) {
694 $sizes[$row->job_cmd
] = (int)$row->count
;
701 * Recycle or destroy any jobs that have been claimed for too long
703 * @return int Number of jobs recycled/deleted
705 public function recycleAndDeleteStaleJobs() {
707 $count = 0; // affected rows
708 $dbw = $this->getPrimaryDB();
711 if ( !$dbw->lock( "jobqueue-recycle-{$this->type}", __METHOD__
, 1 ) ) {
712 return $count; // already in progress
715 // Remove claims on jobs acquired for too long if enabled...
716 if ( $this->claimTTL
> 0 ) {
717 $claimCutoff = $dbw->timestamp( $now - $this->claimTTL
);
718 // Get the IDs of jobs that have be claimed but not finished after too long.
719 // These jobs can be recycled into the queue by expiring the claim. Selecting
720 // the IDs first means that the UPDATE can be done by primary key (less deadlocks).
721 $res = $dbw->newSelectQueryBuilder()
726 'job_cmd' => $this->type
,
727 $dbw->expr( 'job_token', '!=', '' ), // was acquired
728 $dbw->expr( 'job_token_timestamp', '<', $claimCutoff ), // stale
729 $dbw->expr( 'job_attempts', '<', $this->maxTries
), // retries left
732 ->caller( __METHOD__
)->fetchResultSet();
734 static function ( $o ) {
736 }, iterator_to_array( $res )
738 if ( count( $ids ) ) {
739 // Reset job_token for these jobs so that other runners will pick them up.
740 // Set the timestamp to the current time, as it is useful to now that the job
741 // was already tried before (the timestamp becomes the "released" time).
742 $dbw->newUpdateQueryBuilder()
746 'job_token_timestamp' => $dbw->timestamp( $now ) // time of release
750 $dbw->expr( 'job_token', '!=', '' ),
752 ->caller( __METHOD__
)->execute();
754 $affected = $dbw->affectedRows();
756 $this->incrStats( 'recycles', $this->type
, $affected );
760 // Just destroy any stale jobs...
761 $pruneCutoff = $dbw->timestamp( $now - self
::MAX_AGE_PRUNE
);
762 $qb = $dbw->newSelectQueryBuilder()
767 'job_cmd' => $this->type
,
768 $dbw->expr( 'job_token', '!=', '' ), // was acquired
769 $dbw->expr( 'job_token_timestamp', '<', $pruneCutoff ) // stale
772 if ( $this->claimTTL
> 0 ) { // only prune jobs attempted too many times...
773 $qb->andWhere( $dbw->expr( 'job_attempts', '>=', $this->maxTries
) );
775 // Get the IDs of jobs that are considered stale and should be removed. Selecting
776 // the IDs first means that the UPDATE can be done by primary key (less deadlocks).
777 $res = $qb->caller( __METHOD__
)->fetchResultSet();
779 static function ( $o ) {
781 }, iterator_to_array( $res )
783 if ( count( $ids ) ) {
784 $dbw->newDeleteQueryBuilder()
785 ->deleteFrom( 'job' )
786 ->where( [ 'job_id' => $ids ] )
787 ->caller( __METHOD__
)->execute();
788 $affected = $dbw->affectedRows();
790 $this->incrStats( 'abandons', $this->type
, $affected );
793 $dbw->unlock( "jobqueue-recycle-{$this->type}", __METHOD__
);
794 } catch ( DBError
$e ) {
795 throw $this->getDBException( $e );
802 * @param IJobSpecification $job
803 * @param IReadableDatabase $db
806 protected function insertFields( IJobSpecification
$job, IReadableDatabase
$db ) {
808 // Fields that describe the nature of the job
809 'job_cmd' => $job->getType(),
810 'job_namespace' => $job->getParams()['namespace'] ?? NS_SPECIAL
,
811 'job_title' => $job->getParams()['title'] ??
'',
812 'job_params' => self
::makeBlob( $job->getParams() ),
813 // Additional job metadata
814 'job_timestamp' => $db->timestamp(),
815 'job_sha1' => Wikimedia\base_convert
(
816 sha1( serialize( $job->getDeduplicationInfo() ) ),
819 'job_random' => mt_rand( 0, self
::MAX_JOB_RANDOM
)
824 * @throws JobQueueConnectionError
827 protected function getReplicaDB() {
829 return $this->getDB( DB_REPLICA
);
830 } catch ( DBConnectionError
$e ) {
831 throw new JobQueueConnectionError( "DBConnectionError:" . $e->getMessage() );
836 * @throws JobQueueConnectionError
837 * @return IMaintainableDatabase
840 protected function getPrimaryDB() {
842 return $this->getDB( DB_PRIMARY
);
843 } catch ( DBConnectionError
$e ) {
844 throw new JobQueueConnectionError( "DBConnectionError:" . $e->getMessage() );
849 * @param int $index (DB_REPLICA/DB_PRIMARY)
850 * @return IMaintainableDatabase
852 protected function getDB( $index ) {
853 if ( $this->server
) {
854 if ( $this->conn
instanceof IDatabase
) {
856 } elseif ( $this->conn
instanceof DBError
) {
861 $this->conn
= MediaWikiServices
::getInstance()->getDatabaseFactory()->create(
862 $this->server
['type'],
865 } catch ( DBError
$e ) {
872 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
873 $lb = is_string( $this->cluster
)
874 ?
$lbFactory->getExternalLB( $this->cluster
)
875 : $lbFactory->getMainLB( $this->domain
);
877 if ( $lb->getServerType( ServerInfo
::WRITER_INDEX
) !== 'sqlite' ) {
878 // Keep a separate connection to avoid contention and deadlocks;
879 // However, SQLite has the opposite behavior due to DB-level locking.
880 $flags = $lb::CONN_TRX_AUTOCOMMIT
;
882 // Jobs insertion will be deferred until the PRESEND stage to reduce contention.
886 return $lb->getMaintenanceConnectionRef( $index, [], $this->domain
, $flags );
891 * @param string $property
894 private function getCacheKey( $property ) {
895 $cluster = is_string( $this->cluster
) ?
$this->cluster
: 'main';
897 return $this->wanCache
->makeGlobalKey(
907 * @param array|false $params
910 protected static function makeBlob( $params ) {
911 if ( $params !== false ) {
912 return serialize( $params );
919 * @param stdClass $row
920 * @return RunnableJob
922 protected function jobFromRow( $row ) {
923 $params = ( (string)$row->job_params
!== '' ) ?
unserialize( $row->job_params
) : [];
924 if ( !is_array( $params ) ) { // this shouldn't happen
925 throw new UnexpectedValueException(
926 "Could not unserialize job with ID '{$row->job_id}'." );
929 $params +
= [ 'namespace' => $row->job_namespace
, 'title' => $row->job_title
];
930 $job = $this->factoryJob( $row->job_cmd
, $params );
931 $job->setMetadata( 'id', $row->job_id
);
932 $job->setMetadata( 'timestamp', $row->job_timestamp
);
939 * @return JobQueueError
941 protected function getDBException( DBError
$e ) {
942 return new JobQueueError( get_class( $e ) . ": " . $e->getMessage() );
946 * Return the list of job fields that should be selected.
950 public static function selectFields() {
961 'job_token_timestamp',