f6003b239d61ae15c8933c93e2c6e163f8c57bd6
[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 // 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
132 }
133 // Check if we found a row to reserve...
134 if ( !$found ) {
135 $wgMemc->set( $this->getEmptinessCacheKey(), 'true', self::CACHE_TTL );
136 break; // nothing to do
137 }
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
142 if ( !$row ) {
143 wfDebugLog( 'JobQueueDB', "Row deleted as duplicate by another process." );
144 continue; // try again
145 }
146 // Get the job object from the row...
147 $title = Title::makeTitleSafe( $row->job_namespace, $row->job_title );
148 if ( !$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
152 }
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 ) ) {
157 $dbw->delete( 'job',
158 array( 'job_sha1' => $row->job_sha1,
159 "job_id != {$dbw->addQuotes( $row->job_id )}" ),
160 __METHOD__
161 );
162 }
163 break; // done
164 } while( true );
165 } catch ( DBError $e ) {
166 $dbw->setFlag( $autoTrx ? DBO_TRX : 0 ); // restore automatic begin()
167 throw $e;
168 }
169 $dbw->setFlag( $autoTrx ? DBO_TRX : 0 ); // restore automatic begin()
170
171 return $job;
172 }
173
174 /**
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
180 */
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' )}
192 SET
193 job_token = {$dbw->addQuotes( $uuid ) },
194 job_token_timestamp = {$dbw->addQuotes( $dbw->timestamp() )}
195 WHERE (
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",
200 __METHOD__
201 );
202 } else {
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.
205 $dbw->update( 'job',
206 array( 'job_token' => $uuid, 'job_token_timestamp' => $dbw->timestamp() ),
207 array( 'job_id = (' .
208 $dbw->selectSQLText( 'job', 'job_id',
209 array(
210 'job_cmd' => $this->type,
211 'job_token' => '',
212 "job_random {$ineq} {$dbw->addQuotes( $rand )}" ),
213 __METHOD__,
214 array( 'ORDER BY' => "job_random {$dir}", 'LIMIT' => 1 ) ) .
215 ')'
216 ),
217 __METHOD__
218 );
219 }
220 return $dbw->affectedRows();
221 }
222
223 /**
224 * @see JobQueue::doAck()
225 * @return Job|bool
226 */
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
232 }
233
234 $autoTrx = $dbw->getFlag( DBO_TRX ); // automatic begin() enabled?
235 $dbw->clearFlag( DBO_TRX ); // make each query its own transaction
236 try {
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()
241 throw $e;
242 }
243 $dbw->setFlag( $autoTrx ? DBO_TRX : 0 ); // restore automatic begin()
244
245 return true;
246 }
247
248 /**
249 * @see JobQueue::doWaitForBackups()
250 * @return void
251 */
252 protected function doWaitForBackups() {
253 wfWaitForSlaves();
254 }
255
256 /**
257 * @return DatabaseBase
258 */
259 protected function getSlaveDB() {
260 return wfGetDB( DB_SLAVE, array(), $this->wiki );
261 }
262
263 /**
264 * @return DatabaseBase
265 */
266 protected function getMasterDB() {
267 return wfGetDB( DB_MASTER, array(), $this->wiki );
268 }
269
270 /**
271 * @param $job Job
272 * @return array
273 */
274 protected function insertFields( Job $job ) {
275 // Rows that describe the nature of the job
276 $descFields = array(
277 'job_cmd' => $job->getType(),
278 'job_namespace' => $job->getTitle()->getNamespace(),
279 'job_title' => $job->getTitle()->getDBkey(),
280 'job_params' => self::makeBlob( $job->getParams() ),
281 );
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 );
287 }
288 $dbw = $this->getMasterDB();
289 $metaFields = array(
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 )
294 );
295 return ( $descFields + $metaFields );
296 }
297
298 /**
299 * @return string
300 */
301 private function getEmptinessCacheKey() {
302 list( $db, $prefix ) = wfSplitWikiID( $this->wiki );
303 return wfForeignMemcKey( $db, $prefix, 'jobqueue', $this->type, 'isempty' );
304 }
305
306 /**
307 * @param $params
308 * @return string
309 */
310 protected static function makeBlob( $params ) {
311 if ( $params !== false ) {
312 return serialize( $params );
313 } else {
314 return '';
315 }
316 }
317
318 /**
319 * @param $blob
320 * @return bool|mixed
321 */
322 protected static function extractBlob( $blob ) {
323 if ( (string)$blob !== '' ) {
324 return unserialize( $blob );
325 } else {
326 return false;
327 }
328 }
329 }