[JobQueue] Added support for retrying jobs when runners die.
[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.21
29 */
30 class JobQueueDB extends JobQueue {
31 const CACHE_TTL = 300; // integer; seconds to cache queue information
32 const MAX_AGE_PRUNE = 604800; // integer; seconds a job can live once claimed
33 const MAX_ATTEMPTS = 3; // integer; number of times to try a job
34 const MAX_JOB_RANDOM = 2147483647; // integer; 2^31 - 1, used for job_random
35
36 /**
37 * @see JobQueue::doIsEmpty()
38 * @return bool
39 */
40 protected function doIsEmpty() {
41 global $wgMemc;
42
43 $key = $this->getEmptinessCacheKey();
44
45 $isEmpty = $wgMemc->get( $key );
46 if ( $isEmpty === 'true' ) {
47 return true;
48 } elseif ( $isEmpty === 'false' ) {
49 return false;
50 }
51
52 $found = $this->getSlaveDB()->selectField(
53 'job', '1', array( 'job_cmd' => $this->type ), __METHOD__
54 );
55
56 $wgMemc->add( $key, $found ? 'false' : 'true', self::CACHE_TTL );
57 }
58
59 /**
60 * @see JobQueue::doBatchPush()
61 * @return bool
62 */
63 protected function doBatchPush( array $jobs, $flags ) {
64 if ( count( $jobs ) ) {
65 $dbw = $this->getMasterDB();
66
67 $rows = array();
68 foreach ( $jobs as $job ) {
69 $rows[] = $this->insertFields( $job );
70 }
71 $atomic = ( $flags & self::QoS_Atomic );
72 $key = $this->getEmptinessCacheKey();
73 $ttl = self::CACHE_TTL;
74
75 $dbw->onTransactionIdle( function() use ( $dbw, $rows, $atomic, $key, $ttl ) {
76 global $wgMemc;
77
78 $autoTrx = $dbw->getFlag( DBO_TRX ); // automatic begin() enabled?
79 if ( $atomic ) {
80 $dbw->begin(); // wrap all the job additions in one transaction
81 } else {
82 $dbw->clearFlag( DBO_TRX ); // make each query its own transaction
83 }
84 try {
85 foreach ( array_chunk( $rows, 50 ) as $rowBatch ) { // avoid slave lag
86 $dbw->insert( 'job', $rowBatch, __METHOD__ );
87 }
88 } catch ( DBError $e ) {
89 if ( $atomic ) {
90 $dbw->rollback();
91 } else {
92 $dbw->setFlag( $autoTrx ? DBO_TRX : 0 ); // restore automatic begin()
93 }
94 throw $e;
95 }
96 if ( $atomic ) {
97 $dbw->commit();
98 } else {
99 $dbw->setFlag( $autoTrx ? DBO_TRX : 0 ); // restore automatic begin()
100 }
101
102 $wgMemc->set( $key, 'false', $ttl ); // queue is not empty
103 } );
104 }
105
106 return true;
107 }
108
109 /**
110 * @see JobQueue::doPop()
111 * @return Job|bool
112 */
113 protected function doPop() {
114 global $wgMemc;
115
116 if ( $wgMemc->get( $this->getEmptinessCacheKey() ) === 'true' ) {
117 return false; // queue is empty
118 }
119
120 $dbw = $this->getMasterDB();
121 $dbw->commit( __METHOD__, 'flush' ); // flush existing transaction
122
123 $uuid = wfRandomString( 32 ); // pop attempt
124 $job = false; // job popped off
125 $autoTrx = $dbw->getFlag( DBO_TRX ); // automatic begin() enabled?
126 $dbw->clearFlag( DBO_TRX ); // make each query its own transaction
127 try {
128 // Occasionally recycle jobs back into the queue that have been claimed too long
129 if ( mt_rand( 0, 99 ) == 0 ) {
130 $this->recycleStaleJobs();
131 }
132 do { // retry when our row is invalid or deleted as a duplicate
133 // Try to reserve a row in the DB...
134 if ( in_array( $this->order, array( 'fifo', 'timestamp' ) ) ) {
135 $row = $this->claimOldest( $uuid );
136 } else { // random first
137 $rand = mt_rand( 0, self::MAX_JOB_RANDOM ); // encourage concurrent UPDATEs
138 $gte = (bool)mt_rand( 0, 1 ); // find rows with rand before/after $rand
139 $row = $this->claimRandom( $uuid, $rand, $gte );
140 if ( !$row ) { // need to try the other direction
141 $row = $this->claimRandom( $uuid, $rand, !$gte );
142 }
143 }
144 // Check if we found a row to reserve...
145 if ( !$row ) {
146 $wgMemc->set( $this->getEmptinessCacheKey(), 'true', self::CACHE_TTL );
147 break; // nothing to do
148 }
149 // Get the job object from the row...
150 $title = Title::makeTitleSafe( $row->job_namespace, $row->job_title );
151 if ( !$title ) {
152 $dbw->delete( 'job', array( 'job_id' => $row->job_id ), __METHOD__ );
153 wfIncrStats( 'job-pop' );
154 wfDebugLog( 'JobQueueDB', "Row has invalid title '{$row->job_title}'." );
155 continue; // try again
156 }
157 $job = Job::factory( $row->job_cmd, $title,
158 self::extractBlob( $row->job_params ), $row->job_id );
159 // Delete any *other* duplicate jobs in the queue...
160 if ( $job->ignoreDuplicates() && strlen( $row->job_sha1 ) ) {
161 $dbw->delete( 'job',
162 array( 'job_sha1' => $row->job_sha1,
163 "job_id != {$dbw->addQuotes( $row->job_id )}" ),
164 __METHOD__
165 );
166 wfIncrStats( 'job-pop', $dbw->affectedRows() );
167 }
168 break; // done
169 } while( true );
170 } catch ( DBError $e ) {
171 $dbw->setFlag( $autoTrx ? DBO_TRX : 0 ); // restore automatic begin()
172 throw $e;
173 }
174 $dbw->setFlag( $autoTrx ? DBO_TRX : 0 ); // restore automatic begin()
175
176 return $job;
177 }
178
179 /**
180 * Reserve a row with a single UPDATE without holding row locks over RTTs...
181 *
182 * @param $uuid string 32 char hex string
183 * @param $rand integer Random unsigned integer (31 bits)
184 * @param $gte bool Search for job_random >= $random (otherwise job_random <= $random)
185 * @return Row|false
186 */
187 protected function claimRandom( $uuid, $rand, $gte ) {
188 $dbw = $this->getMasterDB();
189 $dir = $gte ? 'ASC' : 'DESC';
190 $ineq = $gte ? '>=' : '<=';
191
192 $row = false; // the row acquired
193 // This uses a replication safe method for acquiring jobs. One could use UPDATE+LIMIT
194 // instead, but that either uses ORDER BY (in which case it deadlocks in MySQL) or is
195 // not replication safe. Due to http://bugs.mysql.com/bug.php?id=6980, subqueries cannot
196 // be used here with MySQL.
197 do {
198 $row = $dbw->selectRow( 'job', '*', // find a random job
199 array(
200 'job_cmd' => $this->type,
201 'job_token' => '',
202 "job_random {$ineq} {$dbw->addQuotes( $rand )}" ),
203 __METHOD__,
204 array( 'ORDER BY' => "job_random {$dir}" )
205 );
206 if ( $row ) { // claim the job
207 $dbw->update( 'job', // update by PK
208 array(
209 'job_token' => $uuid,
210 'job_token_timestamp' => $dbw->timestamp(),
211 'job_attempts = job_attempts+1' ),
212 array( 'job_cmd' => $this->type, 'job_id' => $row->job_id, 'job_token' => '' ),
213 __METHOD__
214 );
215 // This might get raced out by another runner when claiming the previously
216 // selected row. The use of job_random should minimize this problem, however.
217 if ( !$dbw->affectedRows() ) {
218 $row = false; // raced out
219 }
220 } else {
221 break; // nothing to do
222 }
223 } while ( !$row );
224
225 return $row;
226 }
227
228 /**
229 * Reserve a row with a single UPDATE without holding row locks over RTTs...
230 *
231 * @param $uuid string 32 char hex string
232 * @return Row|false
233 */
234 protected function claimOldest( $uuid ) {
235 $dbw = $this->getMasterDB();
236
237 $row = false; // the row acquired
238 do {
239 if ( $dbw->getType() === 'mysql' ) {
240 // Per http://bugs.mysql.com/bug.php?id=6980, we can't use subqueries on the
241 // same table being changed in an UPDATE query in MySQL (gives Error: 1093).
242 // Oracle and Postgre have no such limitation. However, MySQL offers an
243 // alternative here by supporting ORDER BY + LIMIT for UPDATE queries.
244 $dbw->query( "UPDATE {$dbw->tableName( 'job' )} " .
245 "SET " .
246 "job_token = {$dbw->addQuotes( $uuid ) }, " .
247 "job_token_timestamp = {$dbw->addQuotes( $dbw->timestamp() )}, " .
248 "job_attempts = job_attempts+1 " .
249 "WHERE ( " .
250 "job_cmd = {$dbw->addQuotes( $this->type )} " .
251 "AND job_token = {$dbw->addQuotes( '' )} " .
252 ") ORDER BY job_id ASC LIMIT 1",
253 __METHOD__
254 );
255 } else {
256 // Use a subquery to find the job, within an UPDATE to claim it.
257 // This uses as much of the DB wrapper functions as possible.
258 $dbw->update( 'job',
259 array(
260 'job_token' => $uuid,
261 'job_token_timestamp' => $dbw->timestamp(),
262 'job_attempts = job_attempts+1' ),
263 array( 'job_id = (' .
264 $dbw->selectSQLText( 'job', 'job_id',
265 array( 'job_cmd' => $this->type, 'job_token' => '' ),
266 __METHOD__,
267 array( 'ORDER BY' => 'job_id ASC', 'LIMIT' => 1 ) ) .
268 ')'
269 ),
270 __METHOD__
271 );
272 }
273 // Fetch any row that we just reserved...
274 if ( $dbw->affectedRows() ) {
275 $row = $dbw->selectRow( 'job', '*',
276 array( 'job_cmd' => $this->type, 'job_token' => $uuid ), __METHOD__
277 );
278 if ( !$row ) { // raced out by duplicate job removal
279 wfDebugLog( 'JobQueueDB', "Row deleted as duplicate by another process." );
280 }
281 } else {
282 break; // nothing to do
283 }
284 } while ( !$row );
285
286 return $row;
287 }
288
289 /**
290 * Recycle or destroy any jobs that have been claimed for too long
291 *
292 * @return integer Number of jobs recycled/deleted
293 */
294 protected function recycleStaleJobs() {
295 $now = time();
296 $dbw = $this->getMasterDB();
297
298 if ( $this->claimTTL > 0 ) { // re-try stale jobs...
299 $claimCutoff = $dbw->timestamp( $now - $this->claimTTL );
300 // Reset job_token for these jobs so that other runners will pick them up.
301 // Set the timestamp to the current time, as it is useful to now that the job
302 // was already tried before.
303 $dbw->update( 'job',
304 array(
305 'job_token' => '',
306 'job_token_timestamp' => $dbw->timestamp( $now ) ), // time of release
307 array(
308 'job_cmd' => $this->type,
309 "job_token != {$dbw->addQuotes( '' )}", // was acquired
310 "job_token_timestamp < {$dbw->addQuotes( $claimCutoff )}", // stale
311 "job_attempts < {$dbw->addQuotes( self::MAX_ATTEMPTS )}" ),
312 __METHOD__
313 );
314 }
315
316 // Just destroy stale jobs...
317 $pruneCutoff = $dbw->timestamp( $now - self::MAX_AGE_PRUNE );
318 $conds = array(
319 'job_cmd' => $this->type,
320 "job_token != {$dbw->addQuotes( '' )}", // was acquired
321 "job_token_timestamp < {$dbw->addQuotes( $pruneCutoff )}" // stale
322 );
323 if ( $this->claimTTL > 0 ) { // only prune jobs attempted too many times...
324 $conds[] = "job_attempts >= {$dbw->addQuotes( self::MAX_ATTEMPTS )}";
325 }
326
327 return $dbw->affectedRows();
328 }
329
330 /**
331 * @see JobQueue::doAck()
332 * @return Job|bool
333 */
334 protected function doAck( Job $job ) {
335 $dbw = $this->getMasterDB();
336 $dbw->commit( __METHOD__, 'flush' ); // flush existing transaction
337
338 $autoTrx = $dbw->getFlag( DBO_TRX ); // automatic begin() enabled?
339 $dbw->clearFlag( DBO_TRX ); // make each query its own transaction
340 try {
341 // Delete a row with a single DELETE without holding row locks over RTTs...
342 $dbw->delete( 'job', array( 'job_cmd' => $this->type, 'job_id' => $job->getId() ) );
343 } catch ( Exception $e ) {
344 $dbw->setFlag( $autoTrx ? DBO_TRX : 0 ); // restore automatic begin()
345 throw $e;
346 }
347 $dbw->setFlag( $autoTrx ? DBO_TRX : 0 ); // restore automatic begin()
348
349 return true;
350 }
351
352 /**
353 * @see JobQueue::doWaitForBackups()
354 * @return void
355 */
356 protected function doWaitForBackups() {
357 wfWaitForSlaves();
358 }
359
360 /**
361 * @return DatabaseBase
362 */
363 protected function getSlaveDB() {
364 return wfGetDB( DB_SLAVE, array(), $this->wiki );
365 }
366
367 /**
368 * @return DatabaseBase
369 */
370 protected function getMasterDB() {
371 return wfGetDB( DB_MASTER, array(), $this->wiki );
372 }
373
374 /**
375 * @param $job Job
376 * @return array
377 */
378 protected function insertFields( Job $job ) {
379 // Rows that describe the nature of the job
380 $descFields = array(
381 'job_cmd' => $job->getType(),
382 'job_namespace' => $job->getTitle()->getNamespace(),
383 'job_title' => $job->getTitle()->getDBkey(),
384 'job_params' => self::makeBlob( $job->getParams() ),
385 );
386 // Additional job metadata
387 $dbw = $this->getMasterDB();
388 $metaFields = array(
389 'job_id' => $dbw->nextSequenceValue( 'job_job_id_seq' ),
390 'job_timestamp' => $dbw->timestamp(),
391 'job_sha1' => wfBaseConvert( sha1( serialize( $descFields ) ), 16, 36, 32 ),
392 'job_random' => mt_rand( 0, self::MAX_JOB_RANDOM )
393 );
394 return ( $descFields + $metaFields );
395 }
396
397 /**
398 * @return string
399 */
400 private function getEmptinessCacheKey() {
401 list( $db, $prefix ) = wfSplitWikiID( $this->wiki );
402 return wfForeignMemcKey( $db, $prefix, 'jobqueue', $this->type, 'isempty' );
403 }
404
405 /**
406 * @param $params
407 * @return string
408 */
409 protected static function makeBlob( $params ) {
410 if ( $params !== false ) {
411 return serialize( $params );
412 } else {
413 return '';
414 }
415 }
416
417 /**
418 * @param $blob
419 * @return bool|mixed
420 */
421 protected static function extractBlob( $blob ) {
422 if ( (string)$blob !== '' ) {
423 return unserialize( $blob );
424 } else {
425 return false;
426 }
427 }
428 }