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
21 * @author Aaron Schulz
25 * Class to handle job queues stored in the DB
30 class JobQueueDB
extends JobQueue
{
31 const CACHE_TTL
= 30; // integer; seconds
32 const MAX_JOB_RANDOM
= 2147483647; // 2^31 - 1; used for job_random
35 * @see JobQueue::doIsEmpty()
38 protected function doIsEmpty() {
41 $key = $this->getEmptinessCacheKey();
43 $isEmpty = $wgMemc->get( $key );
44 if ( $isEmpty === 'true' ) {
46 } elseif ( $isEmpty === 'false' ) {
50 $found = $this->getSlaveDB()->selectField(
51 'job', '1', array( 'job_cmd' => $this->type
), __METHOD__
54 $wgMemc->add( $key, $found ?
'false' : 'true', self
::CACHE_TTL
);
58 * @see JobQueue::doBatchPush()
61 protected function doBatchPush( array $jobs, $flags ) {
62 if ( count( $jobs ) ) {
63 $dbw = $this->getMasterDB();
66 foreach ( $jobs as $job ) {
67 $rows[] = $this->insertFields( $job );
69 $atomic = ( $flags & self
::QoS_Atomic
);
70 $key = $this->getEmptinessCacheKey();
71 $ttl = self
::CACHE_TTL
;
73 $dbw->onTransactionIdle( function() use ( $dbw, $rows, $atomic, $key, $ttl ) {
76 $autoTrx = $dbw->getFlag( DBO_TRX
); // automatic begin() enabled?
78 $dbw->begin(); // wrap all the job additions in one transaction
80 $dbw->clearFlag( DBO_TRX
); // make each query its own transaction
83 foreach ( array_chunk( $rows, 50 ) as $rowBatch ) { // avoid slave lag
84 $dbw->insert( 'job', $rowBatch, __METHOD__
);
86 } catch ( DBError
$e ) {
90 $dbw->setFlag( $autoTrx ? DBO_TRX
: 0 ); // restore automatic begin()
97 $dbw->setFlag( $autoTrx ? DBO_TRX
: 0 ); // restore automatic begin()
100 $wgMemc->set( $key, 'false', $ttl );
108 * @see JobQueue::doPop()
111 protected function doPop() {
114 $uuid = wfRandomString( 32 ); // pop attempt
116 $dbw = $this->getMasterDB();
117 $dbw->commit( __METHOD__
, 'flush' ); // flush existing transaction
119 $job = false; // job popped off
120 $autoTrx = $dbw->getFlag( DBO_TRX
); // automatic begin() enabled?
121 $dbw->clearFlag( DBO_TRX
); // make each query its own transaction
123 do { // retry when our row is invalid or deleted as a duplicate
124 $row = false; // row claimed
125 $rand = mt_rand( 0, self
::MAX_JOB_RANDOM
); // encourage concurrent UPDATEs
126 $gte = (bool)mt_rand( 0, 1 ); // find rows with rand before/after $rand
127 // Try to reserve a DB row...
128 if ( $this->claim( $uuid, $rand, $gte ) ||
$this->claim( $uuid, $rand, !$gte ) ) {
129 // Fetch any row that we just reserved...
130 $row = $dbw->selectRow( 'job', '*',
131 array( 'job_cmd' => $this->type
, 'job_token' => $uuid ), __METHOD__
);
132 // Check if another process deleted it as a duplicate
134 wfDebugLog( 'JobQueueDB', "Row deleted as duplicate by another process." );
135 continue; // try again
137 // Get the job object from the row...
138 $title = Title
::makeTitleSafe( $row->job_namespace
, $row->job_title
);
140 $dbw->delete( 'job', array( 'job_id' => $row->job_id
), __METHOD__
);
141 wfDebugLog( 'JobQueueDB', "Row has invalid title '{$row->job_title}'." );
142 continue; // try again
144 $job = Job
::factory( $row->job_cmd
, $title,
145 self
::extractBlob( $row->job_params
), $row->job_id
);
146 // Delete any *other* duplicate jobs in the queue...
147 if ( $job->ignoreDuplicates() && strlen( $row->job_sha1
) ) {
149 array( 'job_sha1' => $row->job_sha1
,
150 "job_id != {$dbw->addQuotes( $row->job_id )}" ),
155 $wgMemc->set( $this->getEmptinessCacheKey(), 'true', self
::CACHE_TTL
);
159 } catch ( DBError
$e ) {
160 $dbw->setFlag( $autoTrx ? DBO_TRX
: 0 ); // restore automatic begin()
163 $dbw->setFlag( $autoTrx ? DBO_TRX
: 0 ); // restore automatic begin()
169 * Reserve a row with a single UPDATE without holding row locks over RTTs...
170 * @param $uuid string 32 char hex string
171 * @param $rand integer Random unsigned integer (31 bits)
172 * @param $gte bool Search for job_random >= $random (otherwise job_random <= $random)
173 * @return integer Number of affected rows
175 protected function claim( $uuid, $rand, $gte ) {
176 $dbw = $this->getMasterDB();
177 $dir = $gte ?
'ASC' : 'DESC';
178 $ineq = $gte ?
'>=' : '<=';
179 if ( $dbw->getType() === 'mysql' ) {
180 // Per http://bugs.mysql.com/bug.php?id=6980, we can't use subqueries on the
181 // same table being changed in an UPDATE query in MySQL (gives Error: 1093).
182 // Oracle and Postgre have no such limitation. However, MySQL offers an
183 // alternative here by supporting ORDER BY + LIMIT for UPDATE queries.
184 // The DB wrapper functions do not support this, so it's done manually.
185 $dbw->query( "UPDATE {$dbw->tableName( 'job' )}
187 job_token = {$dbw->addQuotes( $uuid ) },
188 job_token_timestamp = {$dbw->addQuotes( $dbw->timestamp() )}
190 job_cmd = {$dbw->addQuotes( $this->type )}
191 AND job_token = {$dbw->addQuotes( '' )}
192 AND job_random {$ineq} {$dbw->addQuotes( $rand )}
193 ) ORDER BY job_random {$dir} LIMIT 1",
197 // Use a subquery to find the job, within an UPDATE to claim it.
198 // This uses as much of the DB wrapper functions as possible.
200 array( 'job_token' => $uuid, 'job_token_timestamp' => $dbw->timestamp() ),
201 array( 'job_id = (' .
202 $dbw->selectSQLText( 'job', 'job_id',
204 'job_cmd' => $this->type
,
206 "job_random {$ineq} {$dbw->addQuotes( $rand )}" ),
208 array( 'ORDER BY' => "job_random {$dir}", 'LIMIT' => 1 ) ) .
214 return $dbw->affectedRows();
218 * @see JobQueue::doAck()
221 protected function doAck( Job
$job ) {
222 $dbw = $this->getMasterDB();
223 if ( $dbw->trxLevel() ) {
224 wfWarn( "Attempted to ack a job in a transaction; committing first." );
225 $dbw->commit(); // push existing transaction
228 $autoTrx = $dbw->getFlag( DBO_TRX
); // automatic begin() enabled?
229 $dbw->clearFlag( DBO_TRX
); // make each query its own transaction
231 // Delete a row with a single DELETE without holding row locks over RTTs...
232 $dbw->delete( 'job', array( 'job_cmd' => $this->type
, 'job_id' => $job->getId() ) );
233 } catch ( Exception
$e ) {
234 $dbw->setFlag( $autoTrx ? DBO_TRX
: 0 ); // restore automatic begin()
237 $dbw->setFlag( $autoTrx ? DBO_TRX
: 0 ); // restore automatic begin()
243 * @see JobQueue::doWaitForBackups()
246 protected function doWaitForBackups() {
251 * @return DatabaseBase
253 protected function getSlaveDB() {
254 return wfGetDB( DB_SLAVE
, array(), $this->wiki
);
258 * @return DatabaseBase
260 protected function getMasterDB() {
261 return wfGetDB( DB_MASTER
, array(), $this->wiki
);
268 protected function insertFields( Job
$job ) {
269 // Rows that describe the nature of the job
271 'job_cmd' => $job->getType(),
272 'job_namespace' => $job->getTitle()->getNamespace(),
273 'job_title' => $job->getTitle()->getDBkey(),
274 'job_params' => self
::makeBlob( $job->getParams() ),
276 // Additional job metadata
277 $dbw = $this->getMasterDB();
279 'job_id' => $dbw->nextSequenceValue( 'job_job_id_seq' ),
280 'job_timestamp' => $dbw->timestamp(),
281 'job_sha1' => wfBaseConvert( sha1( serialize( $descFields ) ), 16, 36, 32 ),
282 'job_random' => mt_rand( 0, self
::MAX_JOB_RANDOM
)
284 return ( $descFields +
$metaFields );
290 private function getEmptinessCacheKey() {
291 list( $db, $prefix ) = wfSplitWikiID( $this->wiki
);
292 return wfForeignMemcKey( $db, $prefix, 'jobqueue', $this->type
, 'isempty' );
299 protected static function makeBlob( $params ) {
300 if ( $params !== false ) {
301 return serialize( $params );
311 protected static function extractBlob( $blob ) {
312 if ( (string)$blob !== '' ) {
313 return unserialize( $blob );