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 if ( $wgMemc->get( $this->getEmptinessCacheKey() ) === 'true' ) {
115 return false; // queue is empty
118 $dbw = $this->getMasterDB();
119 $dbw->commit( __METHOD__
, 'flush' ); // flush existing transaction
121 $uuid = wfRandomString( 32 ); // pop attempt
122 $job = false; // job popped off
123 $autoTrx = $dbw->getFlag( DBO_TRX
); // automatic begin() enabled?
124 $dbw->clearFlag( DBO_TRX
); // make each query its own transaction
126 do { // retry when our row is invalid or deleted as a duplicate
127 // Try to reserve a row in the DB...
128 if ( $this->order
=== 'timestamp' ) { // oldest first
129 $row = $this->claimOldest( $uuid );
130 } else { // random first
131 $rand = mt_rand( 0, self
::MAX_JOB_RANDOM
); // encourage concurrent UPDATEs
132 $gte = (bool)mt_rand( 0, 1 ); // find rows with rand before/after $rand
133 $row = $this->claimRandom( $uuid, $rand, $gte );
134 if ( !$row ) { // need to try the other direction
135 $row = $this->claimRandom( $uuid, $rand, !$gte );
138 // Check if we found a row to reserve...
140 $wgMemc->set( $this->getEmptinessCacheKey(), 'true', self
::CACHE_TTL
);
141 break; // nothing to do
143 // Get the job object from the row...
144 $title = Title
::makeTitleSafe( $row->job_namespace
, $row->job_title
);
146 $dbw->delete( 'job', array( 'job_id' => $row->job_id
), __METHOD__
);
147 wfDebugLog( 'JobQueueDB', "Row has invalid title '{$row->job_title}'." );
148 continue; // try again
150 $job = Job
::factory( $row->job_cmd
, $title,
151 self
::extractBlob( $row->job_params
), $row->job_id
);
152 // Delete any *other* duplicate jobs in the queue...
153 if ( $job->ignoreDuplicates() && strlen( $row->job_sha1
) ) {
155 array( 'job_sha1' => $row->job_sha1
,
156 "job_id != {$dbw->addQuotes( $row->job_id )}" ),
162 } catch ( DBError
$e ) {
163 $dbw->setFlag( $autoTrx ? DBO_TRX
: 0 ); // restore automatic begin()
166 $dbw->setFlag( $autoTrx ? DBO_TRX
: 0 ); // restore automatic begin()
172 * Reserve a row with a single UPDATE without holding row locks over RTTs...
174 * @param $uuid string 32 char hex string
175 * @param $rand integer Random unsigned integer (31 bits)
176 * @param $gte bool Search for job_random >= $random (otherwise job_random <= $random)
179 protected function claimRandom( $uuid, $rand, $gte ) {
180 $dbw = $this->getMasterDB();
181 $dir = $gte ?
'ASC' : 'DESC';
182 $ineq = $gte ?
'>=' : '<=';
184 $row = false; // the row acquired
185 // This uses a replication safe method for acquiring jobs. One could use UPDATE+LIMIT
186 // instead, but that either uses ORDER BY (in which case it deadlocks in MySQL) or is
187 // not replication safe. Due to http://bugs.mysql.com/bug.php?id=6980, subqueries cannot
188 // be used here with MySQL.
190 $row = $dbw->selectRow( 'job', '*', // find a random job
192 'job_cmd' => $this->type
,
194 "job_random {$ineq} {$dbw->addQuotes( $rand )}" ),
196 array( 'ORDER BY' => "job_random {$dir}" )
198 if ( $row ) { // claim the job
199 $dbw->update( 'job', // update by PK
200 array( 'job_token' => $uuid, 'job_token_timestamp' => $dbw->timestamp() ),
201 array( 'job_cmd' => $this->type
, 'job_id' => $row->job_id
, 'job_token' => '' ),
204 // This might get raced out by another runner when claiming the previously
205 // selected row. The use of job_random should minimize this problem, however.
206 if ( !$dbw->affectedRows() ) {
207 $row = false; // raced out
210 break; // nothing to do
218 * Reserve a row with a single UPDATE without holding row locks over RTTs...
220 * @param $uuid string 32 char hex string
223 protected function claimOldest( $uuid ) {
224 $dbw = $this->getMasterDB();
226 $row = false; // the row acquired
228 if ( $dbw->getType() === 'mysql' ) {
229 // Per http://bugs.mysql.com/bug.php?id=6980, we can't use subqueries on the
230 // same table being changed in an UPDATE query in MySQL (gives Error: 1093).
231 // Oracle and Postgre have no such limitation. However, MySQL offers an
232 // alternative here by supporting ORDER BY + LIMIT for UPDATE queries.
233 $dbw->query( "UPDATE {$dbw->tableName( 'job' )}
235 job_token = {$dbw->addQuotes( $uuid ) },
236 job_token_timestamp = {$dbw->addQuotes( $dbw->timestamp() )}
238 job_cmd = {$dbw->addQuotes( $this->type )}
239 AND job_token = {$dbw->addQuotes( '' )}
240 ) ORDER BY job_random ASC LIMIT 1",
244 // Use a subquery to find the job, within an UPDATE to claim it.
245 // This uses as much of the DB wrapper functions as possible.
247 array( 'job_token' => $uuid, 'job_token_timestamp' => $dbw->timestamp() ),
248 array( 'job_id = (' .
249 $dbw->selectSQLText( 'job', 'job_id',
250 array( 'job_cmd' => $this->type
, 'job_token' => '' ),
252 array( 'ORDER BY' => 'job_random ASC', 'LIMIT' => 1 ) ) .
258 // Fetch any row that we just reserved...
259 if ( $dbw->affectedRows() ) {
260 $row = $dbw->selectRow( 'job', '*',
261 array( 'job_cmd' => $this->type
, 'job_token' => $uuid ), __METHOD__
263 if ( !$row ) { // raced out by duplicate job removal
264 wfDebugLog( 'JobQueueDB', "Row deleted as duplicate by another process." );
267 break; // nothing to do
275 * @see JobQueue::doAck()
278 protected function doAck( Job
$job ) {
279 $dbw = $this->getMasterDB();
280 if ( $dbw->trxLevel() ) {
281 wfWarn( "Attempted to ack a job in a transaction; committing first." );
282 $dbw->commit(); // push existing transaction
285 $autoTrx = $dbw->getFlag( DBO_TRX
); // automatic begin() enabled?
286 $dbw->clearFlag( DBO_TRX
); // make each query its own transaction
288 // Delete a row with a single DELETE without holding row locks over RTTs...
289 $dbw->delete( 'job', array( 'job_cmd' => $this->type
, 'job_id' => $job->getId() ) );
290 } catch ( Exception
$e ) {
291 $dbw->setFlag( $autoTrx ? DBO_TRX
: 0 ); // restore automatic begin()
294 $dbw->setFlag( $autoTrx ? DBO_TRX
: 0 ); // restore automatic begin()
300 * @see JobQueue::doWaitForBackups()
303 protected function doWaitForBackups() {
308 * @return DatabaseBase
310 protected function getSlaveDB() {
311 return wfGetDB( DB_SLAVE
, array(), $this->wiki
);
315 * @return DatabaseBase
317 protected function getMasterDB() {
318 return wfGetDB( DB_MASTER
, array(), $this->wiki
);
325 protected function insertFields( Job
$job ) {
326 // Rows that describe the nature of the job
328 'job_cmd' => $job->getType(),
329 'job_namespace' => $job->getTitle()->getNamespace(),
330 'job_title' => $job->getTitle()->getDBkey(),
331 'job_params' => self
::makeBlob( $job->getParams() ),
333 // Additional job metadata
334 if ( $this->order
=== 'timestamp' ) { // oldest first
335 $random = time() - 1325376000; // seconds since "January 1, 2012"
336 } else { // random first
337 $random = mt_rand( 0, self
::MAX_JOB_RANDOM
);
339 $dbw = $this->getMasterDB();
341 'job_id' => $dbw->nextSequenceValue( 'job_job_id_seq' ),
342 'job_timestamp' => $dbw->timestamp(),
343 'job_sha1' => wfBaseConvert( sha1( serialize( $descFields ) ), 16, 36, 32 ),
344 'job_random' => mt_rand( 0, self
::MAX_JOB_RANDOM
)
346 return ( $descFields +
$metaFields );
352 private function getEmptinessCacheKey() {
353 list( $db, $prefix ) = wfSplitWikiID( $this->wiki
);
354 return wfForeignMemcKey( $db, $prefix, 'jobqueue', $this->type
, 'isempty' );
361 protected static function makeBlob( $params ) {
362 if ( $params !== false ) {
363 return serialize( $params );
373 protected static function extractBlob( $blob ) {
374 if ( (string)$blob !== '' ) {
375 return unserialize( $blob );