Merge "Bug 42039 - Fix some file-related issues in the distribution Minor issues."
[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 $count = 0; // affected rows
298
299 if ( $this->claimTTL > 0 ) { // re-try stale jobs...
300 $claimCutoff = $dbw->timestamp( $now - $this->claimTTL );
301 // Reset job_token for these jobs so that other runners will pick them up.
302 // Set the timestamp to the current time, as it is useful to now that the job
303 // was already tried before.
304 $dbw->update( 'job',
305 array(
306 'job_token' => '',
307 'job_token_timestamp' => $dbw->timestamp( $now ) ), // time of release
308 array(
309 'job_cmd' => $this->type,
310 "job_token != {$dbw->addQuotes( '' )}", // was acquired
311 "job_token_timestamp < {$dbw->addQuotes( $claimCutoff )}", // stale
312 "job_attempts < {$dbw->addQuotes( self::MAX_ATTEMPTS )}" ),
313 __METHOD__
314 );
315 $count += $dbw->affectedRows();
316 }
317
318 // Just destroy stale jobs...
319 $pruneCutoff = $dbw->timestamp( $now - self::MAX_AGE_PRUNE );
320 $conds = array(
321 'job_cmd' => $this->type,
322 "job_token != {$dbw->addQuotes( '' )}", // was acquired
323 "job_token_timestamp < {$dbw->addQuotes( $pruneCutoff )}" // stale
324 );
325 if ( $this->claimTTL > 0 ) { // only prune jobs attempted too many times...
326 $conds[] = "job_attempts >= {$dbw->addQuotes( self::MAX_ATTEMPTS )}";
327 }
328 $dbw->delete( 'job', $conds, __METHOD__ );
329 $count += $dbw->affectedRows();
330
331 return $count;
332 }
333
334 /**
335 * @see JobQueue::doAck()
336 * @return Job|bool
337 */
338 protected function doAck( Job $job ) {
339 $dbw = $this->getMasterDB();
340 $dbw->commit( __METHOD__, 'flush' ); // flush existing transaction
341
342 $autoTrx = $dbw->getFlag( DBO_TRX ); // automatic begin() enabled?
343 $dbw->clearFlag( DBO_TRX ); // make each query its own transaction
344 try {
345 // Delete a row with a single DELETE without holding row locks over RTTs...
346 $dbw->delete( 'job', array( 'job_cmd' => $this->type, 'job_id' => $job->getId() ) );
347 } catch ( Exception $e ) {
348 $dbw->setFlag( $autoTrx ? DBO_TRX : 0 ); // restore automatic begin()
349 throw $e;
350 }
351 $dbw->setFlag( $autoTrx ? DBO_TRX : 0 ); // restore automatic begin()
352
353 return true;
354 }
355
356 /**
357 * @see JobQueue::doWaitForBackups()
358 * @return void
359 */
360 protected function doWaitForBackups() {
361 wfWaitForSlaves();
362 }
363
364 /**
365 * @return DatabaseBase
366 */
367 protected function getSlaveDB() {
368 return wfGetDB( DB_SLAVE, array(), $this->wiki );
369 }
370
371 /**
372 * @return DatabaseBase
373 */
374 protected function getMasterDB() {
375 return wfGetDB( DB_MASTER, array(), $this->wiki );
376 }
377
378 /**
379 * @param $job Job
380 * @return array
381 */
382 protected function insertFields( Job $job ) {
383 // Rows that describe the nature of the job
384 $descFields = array(
385 'job_cmd' => $job->getType(),
386 'job_namespace' => $job->getTitle()->getNamespace(),
387 'job_title' => $job->getTitle()->getDBkey(),
388 'job_params' => self::makeBlob( $job->getParams() ),
389 );
390 // Additional job metadata
391 $dbw = $this->getMasterDB();
392 $metaFields = array(
393 'job_id' => $dbw->nextSequenceValue( 'job_job_id_seq' ),
394 'job_timestamp' => $dbw->timestamp(),
395 'job_sha1' => wfBaseConvert( sha1( serialize( $descFields ) ), 16, 36, 32 ),
396 'job_random' => mt_rand( 0, self::MAX_JOB_RANDOM )
397 );
398 return ( $descFields + $metaFields );
399 }
400
401 /**
402 * @return string
403 */
404 private function getEmptinessCacheKey() {
405 list( $db, $prefix ) = wfSplitWikiID( $this->wiki );
406 return wfForeignMemcKey( $db, $prefix, 'jobqueue', $this->type, 'isempty' );
407 }
408
409 /**
410 * @param $params
411 * @return string
412 */
413 protected static function makeBlob( $params ) {
414 if ( $params !== false ) {
415 return serialize( $params );
416 } else {
417 return '';
418 }
419 }
420
421 /**
422 * @param $blob
423 * @return bool|mixed
424 */
425 protected static function extractBlob( $blob ) {
426 if ( (string)$blob !== '' ) {
427 return unserialize( $blob );
428 } else {
429 return false;
430 }
431 }
432 }