AuthManager: Commit transaction after auto-creating a user
[mediawiki.git] / includes / jobqueue / JobQueueDB.php
blob479ec3289cb7f488d071453fafa84df81e8ff14b
1 <?php
2 /**
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
20 * @file
21 * @author Aaron Schulz
24 /**
25 * Class to handle job queues stored in the DB
27 * @ingroup JobQueue
28 * @since 1.21
30 class JobQueueDB extends JobQueue {
31 const CACHE_TTL_SHORT = 30; // integer; seconds to cache info without re-validating
32 const MAX_AGE_PRUNE = 604800; // integer; seconds a job can live once claimed
33 const MAX_JOB_RANDOM = 2147483647; // integer; 2^31 - 1, used for job_random
34 const MAX_OFFSET = 255; // integer; maximum number of rows to skip
36 /** @var WANObjectCache */
37 protected $cache;
39 /** @var bool|string Name of an external DB cluster. False if not set */
40 protected $cluster = false;
42 /**
43 * Additional parameters include:
44 * - cluster : The name of an external cluster registered via LBFactory.
45 * If not specified, the primary DB cluster for the wiki will be used.
46 * This can be overridden with a custom cluster so that DB handles will
47 * be retrieved via LBFactory::getExternalLB() and getConnection().
48 * @param array $params
50 protected function __construct( array $params ) {
51 parent::__construct( $params );
53 $this->cluster = isset( $params['cluster'] ) ? $params['cluster'] : false;
54 $this->cache = ObjectCache::getMainWANInstance();
57 protected function supportedOrders() {
58 return [ 'random', 'timestamp', 'fifo' ];
61 protected function optimalOrder() {
62 return 'random';
65 /**
66 * @see JobQueue::doIsEmpty()
67 * @return bool
69 protected function doIsEmpty() {
70 $dbr = $this->getSlaveDB();
71 try {
72 $found = $dbr->selectField( // unclaimed job
73 'job', '1', [ 'job_cmd' => $this->type, 'job_token' => '' ], __METHOD__
75 } catch ( DBError $e ) {
76 $this->throwDBException( $e );
79 return !$found;
82 /**
83 * @see JobQueue::doGetSize()
84 * @return int
86 protected function doGetSize() {
87 $key = $this->getCacheKey( 'size' );
89 $size = $this->cache->get( $key );
90 if ( is_int( $size ) ) {
91 return $size;
94 try {
95 $dbr = $this->getSlaveDB();
96 $size = (int)$dbr->selectField( 'job', 'COUNT(*)',
97 [ 'job_cmd' => $this->type, 'job_token' => '' ],
98 __METHOD__
100 } catch ( DBError $e ) {
101 $this->throwDBException( $e );
103 $this->cache->set( $key, $size, self::CACHE_TTL_SHORT );
105 return $size;
109 * @see JobQueue::doGetAcquiredCount()
110 * @return int
112 protected function doGetAcquiredCount() {
113 if ( $this->claimTTL <= 0 ) {
114 return 0; // no acknowledgements
117 $key = $this->getCacheKey( 'acquiredcount' );
119 $count = $this->cache->get( $key );
120 if ( is_int( $count ) ) {
121 return $count;
124 $dbr = $this->getSlaveDB();
125 try {
126 $count = (int)$dbr->selectField( 'job', 'COUNT(*)',
127 [ 'job_cmd' => $this->type, "job_token != {$dbr->addQuotes( '' )}" ],
128 __METHOD__
130 } catch ( DBError $e ) {
131 $this->throwDBException( $e );
133 $this->cache->set( $key, $count, self::CACHE_TTL_SHORT );
135 return $count;
139 * @see JobQueue::doGetAbandonedCount()
140 * @return int
141 * @throws MWException
143 protected function doGetAbandonedCount() {
144 if ( $this->claimTTL <= 0 ) {
145 return 0; // no acknowledgements
148 $key = $this->getCacheKey( 'abandonedcount' );
150 $count = $this->cache->get( $key );
151 if ( is_int( $count ) ) {
152 return $count;
155 $dbr = $this->getSlaveDB();
156 try {
157 $count = (int)$dbr->selectField( 'job', 'COUNT(*)',
159 'job_cmd' => $this->type,
160 "job_token != {$dbr->addQuotes( '' )}",
161 "job_attempts >= " . $dbr->addQuotes( $this->maxTries )
163 __METHOD__
165 } catch ( DBError $e ) {
166 $this->throwDBException( $e );
169 $this->cache->set( $key, $count, self::CACHE_TTL_SHORT );
171 return $count;
175 * @see JobQueue::doBatchPush()
176 * @param IJobSpecification[] $jobs
177 * @param int $flags
178 * @throws DBError|Exception
179 * @return void
181 protected function doBatchPush( array $jobs, $flags ) {
182 $dbw = $this->getMasterDB();
184 $method = __METHOD__;
185 $dbw->onTransactionIdle(
186 function () use ( $dbw, $jobs, $flags, $method ) {
187 $this->doBatchPushInternal( $dbw, $jobs, $flags, $method );
193 * This function should *not* be called outside of JobQueueDB
195 * @param IDatabase $dbw
196 * @param IJobSpecification[] $jobs
197 * @param int $flags
198 * @param string $method
199 * @throws DBError
200 * @return void
202 public function doBatchPushInternal( IDatabase $dbw, array $jobs, $flags, $method ) {
203 if ( !count( $jobs ) ) {
204 return;
207 $rowSet = []; // (sha1 => job) map for jobs that are de-duplicated
208 $rowList = []; // list of jobs for jobs that are not de-duplicated
209 foreach ( $jobs as $job ) {
210 $row = $this->insertFields( $job );
211 if ( $job->ignoreDuplicates() ) {
212 $rowSet[$row['job_sha1']] = $row;
213 } else {
214 $rowList[] = $row;
218 if ( $flags & self::QOS_ATOMIC ) {
219 $dbw->startAtomic( $method ); // wrap all the job additions in one transaction
221 try {
222 // Strip out any duplicate jobs that are already in the queue...
223 if ( count( $rowSet ) ) {
224 $res = $dbw->select( 'job', 'job_sha1',
226 // No job_type condition since it's part of the job_sha1 hash
227 'job_sha1' => array_keys( $rowSet ),
228 'job_token' => '' // unclaimed
230 $method
232 foreach ( $res as $row ) {
233 wfDebug( "Job with hash '{$row->job_sha1}' is a duplicate.\n" );
234 unset( $rowSet[$row->job_sha1] ); // already enqueued
237 // Build the full list of job rows to insert
238 $rows = array_merge( $rowList, array_values( $rowSet ) );
239 // Insert the job rows in chunks to avoid slave lag...
240 foreach ( array_chunk( $rows, 50 ) as $rowBatch ) {
241 $dbw->insert( 'job', $rowBatch, $method );
243 JobQueue::incrStats( 'inserts', $this->type, count( $rows ) );
244 JobQueue::incrStats( 'dupe_inserts', $this->type,
245 count( $rowSet ) + count( $rowList ) - count( $rows )
247 } catch ( DBError $e ) {
248 if ( $flags & self::QOS_ATOMIC ) {
249 $dbw->rollback( $method );
251 throw $e;
253 if ( $flags & self::QOS_ATOMIC ) {
254 $dbw->endAtomic( $method );
257 return;
261 * @see JobQueue::doPop()
262 * @return Job|bool
264 protected function doPop() {
265 $dbw = $this->getMasterDB();
266 try {
267 $dbw->commit( __METHOD__, 'flush' ); // flush existing transaction
268 $autoTrx = $dbw->getFlag( DBO_TRX ); // get current setting
269 $dbw->clearFlag( DBO_TRX ); // make each query its own transaction
270 $scopedReset = new ScopedCallback( function () use ( $dbw, $autoTrx ) {
271 $dbw->setFlag( $autoTrx ? DBO_TRX : 0 ); // restore old setting
272 } );
274 $uuid = wfRandomString( 32 ); // pop attempt
275 $job = false; // job popped off
276 do { // retry when our row is invalid or deleted as a duplicate
277 // Try to reserve a row in the DB...
278 if ( in_array( $this->order, [ 'fifo', 'timestamp' ] ) ) {
279 $row = $this->claimOldest( $uuid );
280 } else { // random first
281 $rand = mt_rand( 0, self::MAX_JOB_RANDOM ); // encourage concurrent UPDATEs
282 $gte = (bool)mt_rand( 0, 1 ); // find rows with rand before/after $rand
283 $row = $this->claimRandom( $uuid, $rand, $gte );
285 // Check if we found a row to reserve...
286 if ( !$row ) {
287 break; // nothing to do
289 JobQueue::incrStats( 'pops', $this->type );
290 // Get the job object from the row...
291 $title = Title::makeTitle( $row->job_namespace, $row->job_title );
292 $job = Job::factory( $row->job_cmd, $title,
293 self::extractBlob( $row->job_params ), $row->job_id );
294 $job->metadata['id'] = $row->job_id;
295 $job->metadata['timestamp'] = $row->job_timestamp;
296 break; // done
297 } while ( true );
299 if ( !$job || mt_rand( 0, 9 ) == 0 ) {
300 // Handled jobs that need to be recycled/deleted;
301 // any recycled jobs will be picked up next attempt
302 $this->recycleAndDeleteStaleJobs();
304 } catch ( DBError $e ) {
305 $this->throwDBException( $e );
308 return $job;
312 * Reserve a row with a single UPDATE without holding row locks over RTTs...
314 * @param string $uuid 32 char hex string
315 * @param int $rand Random unsigned integer (31 bits)
316 * @param bool $gte Search for job_random >= $random (otherwise job_random <= $random)
317 * @return stdClass|bool Row|false
319 protected function claimRandom( $uuid, $rand, $gte ) {
320 $dbw = $this->getMasterDB();
321 // Check cache to see if the queue has <= OFFSET items
322 $tinyQueue = $this->cache->get( $this->getCacheKey( 'small' ) );
324 $row = false; // the row acquired
325 $invertedDirection = false; // whether one job_random direction was already scanned
326 // This uses a replication safe method for acquiring jobs. One could use UPDATE+LIMIT
327 // instead, but that either uses ORDER BY (in which case it deadlocks in MySQL) or is
328 // not replication safe. Due to http://bugs.mysql.com/bug.php?id=6980, subqueries cannot
329 // be used here with MySQL.
330 do {
331 if ( $tinyQueue ) { // queue has <= MAX_OFFSET rows
332 // For small queues, using OFFSET will overshoot and return no rows more often.
333 // Instead, this uses job_random to pick a row (possibly checking both directions).
334 $ineq = $gte ? '>=' : '<=';
335 $dir = $gte ? 'ASC' : 'DESC';
336 $row = $dbw->selectRow( 'job', self::selectFields(), // find a random job
338 'job_cmd' => $this->type,
339 'job_token' => '', // unclaimed
340 "job_random {$ineq} {$dbw->addQuotes( $rand )}" ],
341 __METHOD__,
342 [ 'ORDER BY' => "job_random {$dir}" ]
344 if ( !$row && !$invertedDirection ) {
345 $gte = !$gte;
346 $invertedDirection = true;
347 continue; // try the other direction
349 } else { // table *may* have >= MAX_OFFSET rows
350 // Bug 42614: "ORDER BY job_random" with a job_random inequality causes high CPU
351 // in MySQL if there are many rows for some reason. This uses a small OFFSET
352 // instead of job_random for reducing excess claim retries.
353 $row = $dbw->selectRow( 'job', self::selectFields(), // find a random job
355 'job_cmd' => $this->type,
356 'job_token' => '', // unclaimed
358 __METHOD__,
359 [ 'OFFSET' => mt_rand( 0, self::MAX_OFFSET ) ]
361 if ( !$row ) {
362 $tinyQueue = true; // we know the queue must have <= MAX_OFFSET rows
363 $this->cache->set( $this->getCacheKey( 'small' ), 1, 30 );
364 continue; // use job_random
368 if ( $row ) { // claim the job
369 $dbw->update( 'job', // update by PK
371 'job_token' => $uuid,
372 'job_token_timestamp' => $dbw->timestamp(),
373 'job_attempts = job_attempts+1' ],
374 [ 'job_cmd' => $this->type, 'job_id' => $row->job_id, 'job_token' => '' ],
375 __METHOD__
377 // This might get raced out by another runner when claiming the previously
378 // selected row. The use of job_random should minimize this problem, however.
379 if ( !$dbw->affectedRows() ) {
380 $row = false; // raced out
382 } else {
383 break; // nothing to do
385 } while ( !$row );
387 return $row;
391 * Reserve a row with a single UPDATE without holding row locks over RTTs...
393 * @param string $uuid 32 char hex string
394 * @return stdClass|bool Row|false
396 protected function claimOldest( $uuid ) {
397 $dbw = $this->getMasterDB();
399 $row = false; // the row acquired
400 do {
401 if ( $dbw->getType() === 'mysql' ) {
402 // Per http://bugs.mysql.com/bug.php?id=6980, we can't use subqueries on the
403 // same table being changed in an UPDATE query in MySQL (gives Error: 1093).
404 // Oracle and Postgre have no such limitation. However, MySQL offers an
405 // alternative here by supporting ORDER BY + LIMIT for UPDATE queries.
406 $dbw->query( "UPDATE {$dbw->tableName( 'job' )} " .
407 "SET " .
408 "job_token = {$dbw->addQuotes( $uuid ) }, " .
409 "job_token_timestamp = {$dbw->addQuotes( $dbw->timestamp() )}, " .
410 "job_attempts = job_attempts+1 " .
411 "WHERE ( " .
412 "job_cmd = {$dbw->addQuotes( $this->type )} " .
413 "AND job_token = {$dbw->addQuotes( '' )} " .
414 ") ORDER BY job_id ASC LIMIT 1",
415 __METHOD__
417 } else {
418 // Use a subquery to find the job, within an UPDATE to claim it.
419 // This uses as much of the DB wrapper functions as possible.
420 $dbw->update( 'job',
422 'job_token' => $uuid,
423 'job_token_timestamp' => $dbw->timestamp(),
424 'job_attempts = job_attempts+1' ],
425 [ 'job_id = (' .
426 $dbw->selectSQLText( 'job', 'job_id',
427 [ 'job_cmd' => $this->type, 'job_token' => '' ],
428 __METHOD__,
429 [ 'ORDER BY' => 'job_id ASC', 'LIMIT' => 1 ] ) .
432 __METHOD__
435 // Fetch any row that we just reserved...
436 if ( $dbw->affectedRows() ) {
437 $row = $dbw->selectRow( 'job', self::selectFields(),
438 [ 'job_cmd' => $this->type, 'job_token' => $uuid ], __METHOD__
440 if ( !$row ) { // raced out by duplicate job removal
441 wfDebug( "Row deleted as duplicate by another process.\n" );
443 } else {
444 break; // nothing to do
446 } while ( !$row );
448 return $row;
452 * @see JobQueue::doAck()
453 * @param Job $job
454 * @throws MWException
456 protected function doAck( Job $job ) {
457 if ( !isset( $job->metadata['id'] ) ) {
458 throw new MWException( "Job of type '{$job->getType()}' has no ID." );
461 $dbw = $this->getMasterDB();
462 try {
463 $dbw->commit( __METHOD__, 'flush' ); // flush existing transaction
464 $autoTrx = $dbw->getFlag( DBO_TRX ); // get current setting
465 $dbw->clearFlag( DBO_TRX ); // make each query its own transaction
466 $scopedReset = new ScopedCallback( function () use ( $dbw, $autoTrx ) {
467 $dbw->setFlag( $autoTrx ? DBO_TRX : 0 ); // restore old setting
468 } );
470 // Delete a row with a single DELETE without holding row locks over RTTs...
471 $dbw->delete( 'job',
472 [ 'job_cmd' => $this->type, 'job_id' => $job->metadata['id'] ], __METHOD__ );
474 JobQueue::incrStats( 'acks', $this->type );
475 } catch ( DBError $e ) {
476 $this->throwDBException( $e );
481 * @see JobQueue::doDeduplicateRootJob()
482 * @param IJobSpecification $job
483 * @throws MWException
484 * @return bool
486 protected function doDeduplicateRootJob( IJobSpecification $job ) {
487 $params = $job->getParams();
488 if ( !isset( $params['rootJobSignature'] ) ) {
489 throw new MWException( "Cannot register root job; missing 'rootJobSignature'." );
490 } elseif ( !isset( $params['rootJobTimestamp'] ) ) {
491 throw new MWException( "Cannot register root job; missing 'rootJobTimestamp'." );
493 $key = $this->getRootJobCacheKey( $params['rootJobSignature'] );
494 // Callers should call batchInsert() and then this function so that if the insert
495 // fails, the de-duplication registration will be aborted. Since the insert is
496 // deferred till "transaction idle", do the same here, so that the ordering is
497 // maintained. Having only the de-duplication registration succeed would cause
498 // jobs to become no-ops without any actual jobs that made them redundant.
499 $dbw = $this->getMasterDB();
500 $cache = $this->dupCache;
501 $dbw->onTransactionIdle( function () use ( $cache, $params, $key, $dbw ) {
502 $timestamp = $cache->get( $key ); // current last timestamp of this job
503 if ( $timestamp && $timestamp >= $params['rootJobTimestamp'] ) {
504 return true; // a newer version of this root job was enqueued
507 // Update the timestamp of the last root job started at the location...
508 return $cache->set( $key, $params['rootJobTimestamp'], JobQueueDB::ROOTJOB_TTL );
509 } );
511 return true;
515 * @see JobQueue::doDelete()
516 * @return bool
518 protected function doDelete() {
519 $dbw = $this->getMasterDB();
520 try {
521 $dbw->delete( 'job', [ 'job_cmd' => $this->type ] );
522 } catch ( DBError $e ) {
523 $this->throwDBException( $e );
526 return true;
530 * @see JobQueue::doWaitForBackups()
531 * @return void
533 protected function doWaitForBackups() {
534 wfWaitForSlaves( false, $this->wiki, $this->cluster ?: false );
538 * @return void
540 protected function doFlushCaches() {
541 foreach ( [ 'size', 'acquiredcount' ] as $type ) {
542 $this->cache->delete( $this->getCacheKey( $type ) );
547 * @see JobQueue::getAllQueuedJobs()
548 * @return Iterator
550 public function getAllQueuedJobs() {
551 return $this->getJobIterator( [ 'job_cmd' => $this->getType(), 'job_token' => '' ] );
555 * @see JobQueue::getAllAcquiredJobs()
556 * @return Iterator
558 public function getAllAcquiredJobs() {
559 return $this->getJobIterator( [ 'job_cmd' => $this->getType(), "job_token > ''" ] );
563 * @param array $conds Query conditions
564 * @return Iterator
566 protected function getJobIterator( array $conds ) {
567 $dbr = $this->getSlaveDB();
568 try {
569 return new MappedIterator(
570 $dbr->select( 'job', self::selectFields(), $conds ),
571 function ( $row ) {
572 $job = Job::factory(
573 $row->job_cmd,
574 Title::makeTitle( $row->job_namespace, $row->job_title ),
575 strlen( $row->job_params ) ? unserialize( $row->job_params ) : []
577 $job->metadata['id'] = $row->job_id;
578 $job->metadata['timestamp'] = $row->job_timestamp;
580 return $job;
583 } catch ( DBError $e ) {
584 $this->throwDBException( $e );
588 public function getCoalesceLocationInternal() {
589 return $this->cluster
590 ? "DBCluster:{$this->cluster}:{$this->wiki}"
591 : "LBFactory:{$this->wiki}";
594 protected function doGetSiblingQueuesWithJobs( array $types ) {
595 $dbr = $this->getSlaveDB();
596 // @note: this does not check whether the jobs are claimed or not.
597 // This is useful so JobQueueGroup::pop() also sees queues that only
598 // have stale jobs. This lets recycleAndDeleteStaleJobs() re-enqueue
599 // failed jobs so that they can be popped again for that edge case.
600 $res = $dbr->select( 'job', 'DISTINCT job_cmd',
601 [ 'job_cmd' => $types ], __METHOD__ );
603 $types = [];
604 foreach ( $res as $row ) {
605 $types[] = $row->job_cmd;
608 return $types;
611 protected function doGetSiblingQueueSizes( array $types ) {
612 $dbr = $this->getSlaveDB();
613 $res = $dbr->select( 'job', [ 'job_cmd', 'COUNT(*) AS count' ],
614 [ 'job_cmd' => $types ], __METHOD__, [ 'GROUP BY' => 'job_cmd' ] );
616 $sizes = [];
617 foreach ( $res as $row ) {
618 $sizes[$row->job_cmd] = (int)$row->count;
621 return $sizes;
625 * Recycle or destroy any jobs that have been claimed for too long
627 * @return int Number of jobs recycled/deleted
629 public function recycleAndDeleteStaleJobs() {
630 $now = time();
631 $count = 0; // affected rows
632 $dbw = $this->getMasterDB();
634 try {
635 if ( !$dbw->lock( "jobqueue-recycle-{$this->type}", __METHOD__, 1 ) ) {
636 return $count; // already in progress
639 // Remove claims on jobs acquired for too long if enabled...
640 if ( $this->claimTTL > 0 ) {
641 $claimCutoff = $dbw->timestamp( $now - $this->claimTTL );
642 // Get the IDs of jobs that have be claimed but not finished after too long.
643 // These jobs can be recycled into the queue by expiring the claim. Selecting
644 // the IDs first means that the UPDATE can be done by primary key (less deadlocks).
645 $res = $dbw->select( 'job', 'job_id',
647 'job_cmd' => $this->type,
648 "job_token != {$dbw->addQuotes( '' )}", // was acquired
649 "job_token_timestamp < {$dbw->addQuotes( $claimCutoff )}", // stale
650 "job_attempts < {$dbw->addQuotes( $this->maxTries )}" ], // retries left
651 __METHOD__
653 $ids = array_map(
654 function ( $o ) {
655 return $o->job_id;
656 }, iterator_to_array( $res )
658 if ( count( $ids ) ) {
659 // Reset job_token for these jobs so that other runners will pick them up.
660 // Set the timestamp to the current time, as it is useful to now that the job
661 // was already tried before (the timestamp becomes the "released" time).
662 $dbw->update( 'job',
664 'job_token' => '',
665 'job_token_timestamp' => $dbw->timestamp( $now ) ], // time of release
667 'job_id' => $ids ],
668 __METHOD__
670 $affected = $dbw->affectedRows();
671 $count += $affected;
672 JobQueue::incrStats( 'recycles', $this->type, $affected );
673 $this->aggr->notifyQueueNonEmpty( $this->wiki, $this->type );
677 // Just destroy any stale jobs...
678 $pruneCutoff = $dbw->timestamp( $now - self::MAX_AGE_PRUNE );
679 $conds = [
680 'job_cmd' => $this->type,
681 "job_token != {$dbw->addQuotes( '' )}", // was acquired
682 "job_token_timestamp < {$dbw->addQuotes( $pruneCutoff )}" // stale
684 if ( $this->claimTTL > 0 ) { // only prune jobs attempted too many times...
685 $conds[] = "job_attempts >= {$dbw->addQuotes( $this->maxTries )}";
687 // Get the IDs of jobs that are considered stale and should be removed. Selecting
688 // the IDs first means that the UPDATE can be done by primary key (less deadlocks).
689 $res = $dbw->select( 'job', 'job_id', $conds, __METHOD__ );
690 $ids = array_map(
691 function ( $o ) {
692 return $o->job_id;
693 }, iterator_to_array( $res )
695 if ( count( $ids ) ) {
696 $dbw->delete( 'job', [ 'job_id' => $ids ], __METHOD__ );
697 $affected = $dbw->affectedRows();
698 $count += $affected;
699 JobQueue::incrStats( 'abandons', $this->type, $affected );
702 $dbw->unlock( "jobqueue-recycle-{$this->type}", __METHOD__ );
703 } catch ( DBError $e ) {
704 $this->throwDBException( $e );
707 return $count;
711 * @param IJobSpecification $job
712 * @return array
714 protected function insertFields( IJobSpecification $job ) {
715 $dbw = $this->getMasterDB();
717 return [
718 // Fields that describe the nature of the job
719 'job_cmd' => $job->getType(),
720 'job_namespace' => $job->getTitle()->getNamespace(),
721 'job_title' => $job->getTitle()->getDBkey(),
722 'job_params' => self::makeBlob( $job->getParams() ),
723 // Additional job metadata
724 'job_id' => $dbw->nextSequenceValue( 'job_job_id_seq' ),
725 'job_timestamp' => $dbw->timestamp(),
726 'job_sha1' => Wikimedia\base_convert(
727 sha1( serialize( $job->getDeduplicationInfo() ) ),
728 16, 36, 31
730 'job_random' => mt_rand( 0, self::MAX_JOB_RANDOM )
735 * @throws JobQueueConnectionError
736 * @return DBConnRef
738 protected function getSlaveDB() {
739 try {
740 return $this->getDB( DB_SLAVE );
741 } catch ( DBConnectionError $e ) {
742 throw new JobQueueConnectionError( "DBConnectionError:" . $e->getMessage() );
747 * @throws JobQueueConnectionError
748 * @return DBConnRef
750 protected function getMasterDB() {
751 try {
752 return $this->getDB( DB_MASTER );
753 } catch ( DBConnectionError $e ) {
754 throw new JobQueueConnectionError( "DBConnectionError:" . $e->getMessage() );
759 * @param int $index (DB_SLAVE/DB_MASTER)
760 * @return DBConnRef
762 protected function getDB( $index ) {
763 $lb = ( $this->cluster !== false )
764 ? wfGetLBFactory()->getExternalLB( $this->cluster, $this->wiki )
765 : wfGetLB( $this->wiki );
767 return $lb->getConnectionRef( $index, [], $this->wiki );
771 * @param string $property
772 * @return string
774 private function getCacheKey( $property ) {
775 list( $db, $prefix ) = wfSplitWikiID( $this->wiki );
776 $cluster = is_string( $this->cluster ) ? $this->cluster : 'main';
778 return wfForeignMemcKey( $db, $prefix, 'jobqueue', $cluster, $this->type, $property );
782 * @param array|bool $params
783 * @return string
785 protected static function makeBlob( $params ) {
786 if ( $params !== false ) {
787 return serialize( $params );
788 } else {
789 return '';
794 * @param string $blob
795 * @return bool|mixed
797 protected static function extractBlob( $blob ) {
798 if ( (string)$blob !== '' ) {
799 return unserialize( $blob );
800 } else {
801 return false;
806 * @param DBError $e
807 * @throws JobQueueError
809 protected function throwDBException( DBError $e ) {
810 throw new JobQueueError( get_class( $e ) . ": " . $e->getMessage() );
814 * Return the list of job fields that should be selected.
815 * @since 1.23
816 * @return array
818 public static function selectFields() {
819 return [
820 'job_id',
821 'job_cmd',
822 'job_namespace',
823 'job_title',
824 'job_timestamp',
825 'job_params',
826 'job_random',
827 'job_attempts',
828 'job_token',
829 'job_token_timestamp',
830 'job_sha1',