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 // Try to reserve a row in the DB...
125 if ( $this->order
=== 'timestamp' ) { // oldest first
126 $found = $this->claim( $uuid, 0, true );
127 } else { // random first
128 $rand = mt_rand( 0, self
::MAX_JOB_RANDOM
); // encourage concurrent UPDATEs
129 $gte = (bool)mt_rand( 0, 1 ); // find rows with rand before/after $rand
130 $found = $this->claim( $uuid, $rand, $gte )
131 ||
$this->claim( $uuid, $rand, !$gte ); // try both directions
133 // Check if we found a row to reserve...
135 $wgMemc->set( $this->getEmptinessCacheKey(), 'true', self
::CACHE_TTL
);
136 break; // nothing to do
138 // Fetch any row that we just reserved...
139 $row = $dbw->selectRow( 'job', '*',
140 array( 'job_cmd' => $this->type
, 'job_token' => $uuid ), __METHOD__
);
141 // Check if another process deleted it as a duplicate
143 wfDebugLog( 'JobQueueDB', "Row deleted as duplicate by another process." );
144 continue; // try again
146 // Get the job object from the row...
147 $title = Title
::makeTitleSafe( $row->job_namespace
, $row->job_title
);
149 $dbw->delete( 'job', array( 'job_id' => $row->job_id
), __METHOD__
);
150 wfDebugLog( 'JobQueueDB', "Row has invalid title '{$row->job_title}'." );
151 continue; // try again
153 $job = Job
::factory( $row->job_cmd
, $title,
154 self
::extractBlob( $row->job_params
), $row->job_id
);
155 // Delete any *other* duplicate jobs in the queue...
156 if ( $job->ignoreDuplicates() && strlen( $row->job_sha1
) ) {
158 array( 'job_sha1' => $row->job_sha1
,
159 "job_id != {$dbw->addQuotes( $row->job_id )}" ),
165 } catch ( DBError
$e ) {
166 $dbw->setFlag( $autoTrx ? DBO_TRX
: 0 ); // restore automatic begin()
169 $dbw->setFlag( $autoTrx ? DBO_TRX
: 0 ); // restore automatic begin()
175 * Reserve a row with a single UPDATE without holding row locks over RTTs...
176 * @param $uuid string 32 char hex string
177 * @param $rand integer Random unsigned integer (31 bits)
178 * @param $gte bool Search for job_random >= $random (otherwise job_random <= $random)
179 * @return integer Number of affected rows
181 protected function claim( $uuid, $rand, $gte ) {
182 $dbw = $this->getMasterDB();
183 $dir = $gte ?
'ASC' : 'DESC';
184 $ineq = $gte ?
'>=' : '<=';
185 if ( $dbw->getType() === 'mysql' ) {
186 // Per http://bugs.mysql.com/bug.php?id=6980, we can't use subqueries on the
187 // same table being changed in an UPDATE query in MySQL (gives Error: 1093).
188 // Oracle and Postgre have no such limitation. However, MySQL offers an
189 // alternative here by supporting ORDER BY + LIMIT for UPDATE queries.
190 // The DB wrapper functions do not support this, so it's done manually.
191 $dbw->query( "UPDATE {$dbw->tableName( 'job' )}
193 job_token = {$dbw->addQuotes( $uuid ) },
194 job_token_timestamp = {$dbw->addQuotes( $dbw->timestamp() )}
196 job_cmd = {$dbw->addQuotes( $this->type )}
197 AND job_token = {$dbw->addQuotes( '' )}
198 AND job_random {$ineq} {$dbw->addQuotes( $rand )}
199 ) ORDER BY job_random {$dir} LIMIT 1",
203 // Use a subquery to find the job, within an UPDATE to claim it.
204 // This uses as much of the DB wrapper functions as possible.
206 array( 'job_token' => $uuid, 'job_token_timestamp' => $dbw->timestamp() ),
207 array( 'job_id = (' .
208 $dbw->selectSQLText( 'job', 'job_id',
210 'job_cmd' => $this->type
,
212 "job_random {$ineq} {$dbw->addQuotes( $rand )}" ),
214 array( 'ORDER BY' => "job_random {$dir}", 'LIMIT' => 1 ) ) .
220 return $dbw->affectedRows();
224 * @see JobQueue::doAck()
227 protected function doAck( Job
$job ) {
228 $dbw = $this->getMasterDB();
229 if ( $dbw->trxLevel() ) {
230 wfWarn( "Attempted to ack a job in a transaction; committing first." );
231 $dbw->commit(); // push existing transaction
234 $autoTrx = $dbw->getFlag( DBO_TRX
); // automatic begin() enabled?
235 $dbw->clearFlag( DBO_TRX
); // make each query its own transaction
237 // Delete a row with a single DELETE without holding row locks over RTTs...
238 $dbw->delete( 'job', array( 'job_cmd' => $this->type
, 'job_id' => $job->getId() ) );
239 } catch ( Exception
$e ) {
240 $dbw->setFlag( $autoTrx ? DBO_TRX
: 0 ); // restore automatic begin()
243 $dbw->setFlag( $autoTrx ? DBO_TRX
: 0 ); // restore automatic begin()
249 * @see JobQueue::doWaitForBackups()
252 protected function doWaitForBackups() {
257 * @return DatabaseBase
259 protected function getSlaveDB() {
260 return wfGetDB( DB_SLAVE
, array(), $this->wiki
);
264 * @return DatabaseBase
266 protected function getMasterDB() {
267 return wfGetDB( DB_MASTER
, array(), $this->wiki
);
274 protected function insertFields( Job
$job ) {
275 // Rows that describe the nature of the job
277 'job_cmd' => $job->getType(),
278 'job_namespace' => $job->getTitle()->getNamespace(),
279 'job_title' => $job->getTitle()->getDBkey(),
280 'job_params' => self
::makeBlob( $job->getParams() ),
282 // Additional job metadata
283 if ( $this->order
=== 'timestamp' ) { // oldest first
284 $random = time() - 1325376000; // seconds since "January 1, 2012"
285 } else { // random first
286 $random = mt_rand( 0, self
::MAX_JOB_RANDOM
);
288 $dbw = $this->getMasterDB();
290 'job_id' => $dbw->nextSequenceValue( 'job_job_id_seq' ),
291 'job_timestamp' => $dbw->timestamp(),
292 'job_sha1' => wfBaseConvert( sha1( serialize( $descFields ) ), 16, 36, 32 ),
293 'job_random' => mt_rand( 0, self
::MAX_JOB_RANDOM
)
295 return ( $descFields +
$metaFields );
301 private function getEmptinessCacheKey() {
302 list( $db, $prefix ) = wfSplitWikiID( $this->wiki
);
303 return wfForeignMemcKey( $db, $prefix, 'jobqueue', $this->type
, 'isempty' );
310 protected static function makeBlob( $params ) {
311 if ( $params !== false ) {
312 return serialize( $params );
322 protected static function extractBlob( $blob ) {
323 if ( (string)$blob !== '' ) {
324 return unserialize( $blob );