Merge "reinstating Change Ifb1f6125..."
[lhc/web/wiklou.git] / includes / job / JobQueueDB.php
1 <?php
2 /**
3 * Database-backed job queue code.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 * @author Aaron Schulz
22 */
23
24 /**
25 * Class to handle job queues stored in the DB
26 *
27 * @ingroup JobQueue
28 * @since 1.20
29 */
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
33
34 /**
35 * @see JobQueue::doIsEmpty()
36 * @return bool
37 */
38 protected function doIsEmpty() {
39 global $wgMemc;
40
41 $key = $this->getEmptinessCacheKey();
42
43 $isEmpty = $wgMemc->get( $key );
44 if ( $isEmpty === 'true' ) {
45 return true;
46 } elseif ( $isEmpty === 'false' ) {
47 return false;
48 }
49
50 $found = $this->getSlaveDB()->selectField(
51 'job', '1', array( 'job_cmd' => $this->type ), __METHOD__
52 );
53
54 $wgMemc->add( $key, $found ? 'false' : 'true', self::CACHE_TTL );
55 }
56
57 /**
58 * @see JobQueue::doBatchPush()
59 * @return bool
60 */
61 protected function doBatchPush( array $jobs, $flags ) {
62 if ( count( $jobs ) ) {
63 $dbw = $this->getMasterDB();
64
65 $rows = array();
66 foreach ( $jobs as $job ) {
67 $rows[] = $this->insertFields( $job );
68 }
69 $atomic = ( $flags & self::QoS_Atomic );
70 $key = $this->getEmptinessCacheKey();
71 $ttl = self::CACHE_TTL;
72
73 $dbw->onTransactionIdle( function() use ( $dbw, $rows, $atomic, $key, $ttl ) {
74 global $wgMemc;
75
76 $autoTrx = $dbw->getFlag( DBO_TRX ); // automatic begin() enabled?
77 if ( $atomic ) {
78 $dbw->begin(); // wrap all the job additions in one transaction
79 } else {
80 $dbw->clearFlag( DBO_TRX ); // make each query its own transaction
81 }
82 try {
83 foreach ( array_chunk( $rows, 50 ) as $rowBatch ) { // avoid slave lag
84 $dbw->insert( 'job', $rowBatch, __METHOD__ );
85 }
86 } catch ( DBError $e ) {
87 if ( $atomic ) {
88 $dbw->rollback();
89 } else {
90 $dbw->setFlag( $autoTrx ? DBO_TRX : 0 ); // restore automatic begin()
91 }
92 throw $e;
93 }
94 if ( $atomic ) {
95 $dbw->commit();
96 } else {
97 $dbw->setFlag( $autoTrx ? DBO_TRX : 0 ); // restore automatic begin()
98 }
99
100 $wgMemc->set( $key, 'false', $ttl );
101 } );
102 }
103
104 return true;
105 }
106
107 /**
108 * @see JobQueue::doPop()
109 * @return Job|bool
110 */
111 protected function doPop() {
112 global $wgMemc;
113
114 $uuid = wfRandomString( 32 ); // pop attempt
115
116 $dbw = $this->getMasterDB();
117 $dbw->commit( __METHOD__, 'flush' ); // flush existing transaction
118
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
122 try {
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
133 if ( !$row ) {
134 wfDebugLog( 'JobQueueDB', "Row deleted as duplicate by another process." );
135 continue; // try again
136 }
137 // Get the job object from the row...
138 $title = Title::makeTitleSafe( $row->job_namespace, $row->job_title );
139 if ( !$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
143 }
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 ) ) {
148 $dbw->delete( 'job',
149 array( 'job_sha1' => $row->job_sha1,
150 "job_id != {$dbw->addQuotes( $row->job_id )}" ),
151 __METHOD__
152 );
153 }
154 } else {
155 $wgMemc->set( $this->getEmptinessCacheKey(), 'true', self::CACHE_TTL );
156 }
157 break; // done
158 } while( true );
159 } catch ( DBError $e ) {
160 $dbw->setFlag( $autoTrx ? DBO_TRX : 0 ); // restore automatic begin()
161 throw $e;
162 }
163 $dbw->setFlag( $autoTrx ? DBO_TRX : 0 ); // restore automatic begin()
164
165 return $job;
166 }
167
168 /**
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
174 */
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' )}
186 SET
187 job_token = {$dbw->addQuotes( $uuid ) },
188 job_token_timestamp = {$dbw->addQuotes( $dbw->timestamp() )}
189 WHERE (
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",
194 __METHOD__
195 );
196 } else {
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.
199 $dbw->update( 'job',
200 array( 'job_token' => $uuid, 'job_token_timestamp' => $dbw->timestamp() ),
201 array( 'job_id = (' .
202 $dbw->selectSQLText( 'job', 'job_id',
203 array(
204 'job_cmd' => $this->type,
205 'job_token' => '',
206 "job_random {$ineq} {$dbw->addQuotes( $rand )}" ),
207 __METHOD__,
208 array( 'ORDER BY' => "job_random {$dir}", 'LIMIT' => 1 ) ) .
209 ')'
210 ),
211 __METHOD__
212 );
213 }
214 return $dbw->affectedRows();
215 }
216
217 /**
218 * @see JobQueue::doAck()
219 * @return Job|bool
220 */
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
226 }
227
228 $autoTrx = $dbw->getFlag( DBO_TRX ); // automatic begin() enabled?
229 $dbw->clearFlag( DBO_TRX ); // make each query its own transaction
230 try {
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()
235 throw $e;
236 }
237 $dbw->setFlag( $autoTrx ? DBO_TRX : 0 ); // restore automatic begin()
238
239 return true;
240 }
241
242 /**
243 * @see JobQueue::doWaitForBackups()
244 * @return void
245 */
246 protected function doWaitForBackups() {
247 wfWaitForSlaves();
248 }
249
250 /**
251 * @return DatabaseBase
252 */
253 protected function getSlaveDB() {
254 return wfGetDB( DB_SLAVE, array(), $this->wiki );
255 }
256
257 /**
258 * @return DatabaseBase
259 */
260 protected function getMasterDB() {
261 return wfGetDB( DB_MASTER, array(), $this->wiki );
262 }
263
264 /**
265 * @param $job Job
266 * @return array
267 */
268 protected function insertFields( Job $job ) {
269 // Rows that describe the nature of the job
270 $descFields = array(
271 'job_cmd' => $job->getType(),
272 'job_namespace' => $job->getTitle()->getNamespace(),
273 'job_title' => $job->getTitle()->getDBkey(),
274 'job_params' => self::makeBlob( $job->getParams() ),
275 );
276 // Additional job metadata
277 $dbw = $this->getMasterDB();
278 $metaFields = array(
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 )
283 );
284 return ( $descFields + $metaFields );
285 }
286
287 /**
288 * @return string
289 */
290 private function getEmptinessCacheKey() {
291 list( $db, $prefix ) = wfSplitWikiID( $this->wiki );
292 return wfForeignMemcKey( $db, $prefix, 'jobqueue', $this->type, 'isempty' );
293 }
294
295 /**
296 * @param $params
297 * @return string
298 */
299 protected static function makeBlob( $params ) {
300 if ( $params !== false ) {
301 return serialize( $params );
302 } else {
303 return '';
304 }
305 }
306
307 /**
308 * @param $blob
309 * @return bool|mixed
310 */
311 protected static function extractBlob( $blob ) {
312 if ( (string)$blob !== '' ) {
313 return unserialize( $blob );
314 } else {
315 return false;
316 }
317 }
318 }