Merge "(bug 42638) Fix API action=options&reset=1 & unit tests"
[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 $rowSet = array(); // (sha1 => job) map for jobs that are de-duplicated
68 $rowList = array(); // list of jobs for jobs that are are not de-duplicated
69
70 foreach ( $jobs as $job ) {
71 $row = $this->insertFields( $job );
72 if ( $job->ignoreDuplicates() ) {
73 $rowSet[$row['job_sha1']] = $row;
74 } else {
75 $rowList[] = $row;
76 }
77 }
78
79 $atomic = ( $flags & self::QoS_Atomic );
80 $key = $this->getEmptinessCacheKey();
81 $ttl = self::CACHE_TTL;
82
83 $dbw->onTransactionIdle(
84 function() use ( $dbw, $rowSet, $rowList, $atomic, $key, $ttl
85 ) {
86 global $wgMemc;
87
88 $autoTrx = $dbw->getFlag( DBO_TRX ); // automatic begin() enabled?
89 if ( $atomic ) {
90 $dbw->begin( __METHOD__ ); // wrap all the job additions in one transaction
91 } else {
92 $dbw->clearFlag( DBO_TRX ); // make each query its own transaction
93 }
94 try {
95 // Strip out any duplicate jobs that are already in the queue...
96 if ( count( $rowSet ) ) {
97 $res = $dbw->select( 'job', 'job_sha1',
98 array(
99 // No job_type condition since it's part of the job_sha1 hash
100 'job_sha1' => array_keys( $rowSet ),
101 'job_token' => '' // unclaimed
102 ),
103 __METHOD__
104 );
105 foreach ( $res as $row ) {
106 wfDebug( "Job with hash '{$row->job_sha1}' is a duplicate." );
107 unset( $rowSet[$row->job_sha1] ); // already enqueued
108 }
109 }
110 // Build the full list of job rows to insert
111 $rows = array_merge( $rowList, array_values( $rowSet ) );
112 // Insert the job rows in chunks to avoid slave lag...
113 foreach ( array_chunk( $rows, 50 ) as $rowBatch ) {
114 $dbw->insert( 'job', $rowBatch, __METHOD__ );
115 }
116 } catch ( DBError $e ) {
117 if ( $atomic ) {
118 $dbw->rollback( __METHOD__ );
119 } else {
120 $dbw->setFlag( $autoTrx ? DBO_TRX : 0 ); // restore automatic begin()
121 }
122 throw $e;
123 }
124 if ( $atomic ) {
125 $dbw->commit( __METHOD__ );
126 } else {
127 $dbw->setFlag( $autoTrx ? DBO_TRX : 0 ); // restore automatic begin()
128 }
129
130 $wgMemc->set( $key, 'false', $ttl ); // queue is not empty
131 } );
132 }
133
134 return true;
135 }
136
137 /**
138 * @see JobQueue::doPop()
139 * @return Job|bool
140 */
141 protected function doPop() {
142 global $wgMemc;
143
144 if ( $wgMemc->get( $this->getEmptinessCacheKey() ) === 'true' ) {
145 return false; // queue is empty
146 }
147
148 $dbw = $this->getMasterDB();
149 $dbw->commit( __METHOD__, 'flush' ); // flush existing transaction
150
151 $uuid = wfRandomString( 32 ); // pop attempt
152 $job = false; // job popped off
153 $autoTrx = $dbw->getFlag( DBO_TRX ); // automatic begin() enabled?
154 $dbw->clearFlag( DBO_TRX ); // make each query its own transaction
155 try {
156 // Occasionally recycle jobs back into the queue that have been claimed too long
157 if ( mt_rand( 0, 99 ) == 0 ) {
158 $this->recycleStaleJobs();
159 }
160 do { // retry when our row is invalid or deleted as a duplicate
161 // Try to reserve a row in the DB...
162 if ( in_array( $this->order, array( 'fifo', 'timestamp' ) ) ) {
163 $row = $this->claimOldest( $uuid );
164 } else { // random first
165 $rand = mt_rand( 0, self::MAX_JOB_RANDOM ); // encourage concurrent UPDATEs
166 $gte = (bool)mt_rand( 0, 1 ); // find rows with rand before/after $rand
167 $row = $this->claimRandom( $uuid, $rand, $gte );
168 if ( !$row ) { // need to try the other direction
169 $row = $this->claimRandom( $uuid, $rand, !$gte );
170 }
171 }
172 // Check if we found a row to reserve...
173 if ( !$row ) {
174 $wgMemc->set( $this->getEmptinessCacheKey(), 'true', self::CACHE_TTL );
175 break; // nothing to do
176 }
177 // Get the job object from the row...
178 $title = Title::makeTitleSafe( $row->job_namespace, $row->job_title );
179 if ( !$title ) {
180 $dbw->delete( 'job', array( 'job_id' => $row->job_id ), __METHOD__ );
181 wfIncrStats( 'job-pop' );
182 wfDebugLog( 'JobQueueDB', "Row has invalid title '{$row->job_title}'." );
183 continue; // try again
184 }
185 $job = Job::factory( $row->job_cmd, $title,
186 self::extractBlob( $row->job_params ), $row->job_id );
187 // Flag this job as an old duplicate based on its "root" job...
188 if ( $this->isRootJobOldDuplicate( $job ) ) {
189 $job = DuplicateJob::newFromJob( $job ); // convert to a no-op
190 }
191 break; // done
192 } while( true );
193 } catch ( DBError $e ) {
194 $dbw->setFlag( $autoTrx ? DBO_TRX : 0 ); // restore automatic begin()
195 throw $e;
196 }
197 $dbw->setFlag( $autoTrx ? DBO_TRX : 0 ); // restore automatic begin()
198
199 return $job;
200 }
201
202 /**
203 * Reserve a row with a single UPDATE without holding row locks over RTTs...
204 *
205 * @param $uuid string 32 char hex string
206 * @param $rand integer Random unsigned integer (31 bits)
207 * @param $gte bool Search for job_random >= $random (otherwise job_random <= $random)
208 * @return Row|false
209 */
210 protected function claimRandom( $uuid, $rand, $gte ) {
211 $dbw = $this->getMasterDB();
212 $dir = $gte ? 'ASC' : 'DESC';
213 $ineq = $gte ? '>=' : '<=';
214
215 $row = false; // the row acquired
216 // This uses a replication safe method for acquiring jobs. One could use UPDATE+LIMIT
217 // instead, but that either uses ORDER BY (in which case it deadlocks in MySQL) or is
218 // not replication safe. Due to http://bugs.mysql.com/bug.php?id=6980, subqueries cannot
219 // be used here with MySQL.
220 do {
221 $row = $dbw->selectRow( 'job', '*', // find a random job
222 array(
223 'job_cmd' => $this->type,
224 'job_token' => '',
225 "job_random {$ineq} {$dbw->addQuotes( $rand )}" ),
226 __METHOD__,
227 array( 'ORDER BY' => "job_random {$dir}" )
228 );
229 if ( $row ) { // claim the job
230 $dbw->update( 'job', // update by PK
231 array(
232 'job_token' => $uuid,
233 'job_token_timestamp' => $dbw->timestamp(),
234 'job_attempts = job_attempts+1' ),
235 array( 'job_cmd' => $this->type, 'job_id' => $row->job_id, 'job_token' => '' ),
236 __METHOD__
237 );
238 // This might get raced out by another runner when claiming the previously
239 // selected row. The use of job_random should minimize this problem, however.
240 if ( !$dbw->affectedRows() ) {
241 $row = false; // raced out
242 }
243 } else {
244 break; // nothing to do
245 }
246 } while ( !$row );
247
248 return $row;
249 }
250
251 /**
252 * Reserve a row with a single UPDATE without holding row locks over RTTs...
253 *
254 * @param $uuid string 32 char hex string
255 * @return Row|false
256 */
257 protected function claimOldest( $uuid ) {
258 $dbw = $this->getMasterDB();
259
260 $row = false; // the row acquired
261 do {
262 if ( $dbw->getType() === 'mysql' ) {
263 // Per http://bugs.mysql.com/bug.php?id=6980, we can't use subqueries on the
264 // same table being changed in an UPDATE query in MySQL (gives Error: 1093).
265 // Oracle and Postgre have no such limitation. However, MySQL offers an
266 // alternative here by supporting ORDER BY + LIMIT for UPDATE queries.
267 $dbw->query( "UPDATE {$dbw->tableName( 'job' )} " .
268 "SET " .
269 "job_token = {$dbw->addQuotes( $uuid ) }, " .
270 "job_token_timestamp = {$dbw->addQuotes( $dbw->timestamp() )}, " .
271 "job_attempts = job_attempts+1 " .
272 "WHERE ( " .
273 "job_cmd = {$dbw->addQuotes( $this->type )} " .
274 "AND job_token = {$dbw->addQuotes( '' )} " .
275 ") ORDER BY job_id ASC LIMIT 1",
276 __METHOD__
277 );
278 } else {
279 // Use a subquery to find the job, within an UPDATE to claim it.
280 // This uses as much of the DB wrapper functions as possible.
281 $dbw->update( 'job',
282 array(
283 'job_token' => $uuid,
284 'job_token_timestamp' => $dbw->timestamp(),
285 'job_attempts = job_attempts+1' ),
286 array( 'job_id = (' .
287 $dbw->selectSQLText( 'job', 'job_id',
288 array( 'job_cmd' => $this->type, 'job_token' => '' ),
289 __METHOD__,
290 array( 'ORDER BY' => 'job_id ASC', 'LIMIT' => 1 ) ) .
291 ')'
292 ),
293 __METHOD__
294 );
295 }
296 // Fetch any row that we just reserved...
297 if ( $dbw->affectedRows() ) {
298 $row = $dbw->selectRow( 'job', '*',
299 array( 'job_cmd' => $this->type, 'job_token' => $uuid ), __METHOD__
300 );
301 if ( !$row ) { // raced out by duplicate job removal
302 wfDebugLog( 'JobQueueDB', "Row deleted as duplicate by another process." );
303 }
304 } else {
305 break; // nothing to do
306 }
307 } while ( !$row );
308
309 return $row;
310 }
311
312 /**
313 * Recycle or destroy any jobs that have been claimed for too long
314 *
315 * @return integer Number of jobs recycled/deleted
316 */
317 protected function recycleStaleJobs() {
318 $now = time();
319 $dbw = $this->getMasterDB();
320 $count = 0; // affected rows
321
322 if ( $this->claimTTL > 0 ) { // re-try stale jobs...
323 $claimCutoff = $dbw->timestamp( $now - $this->claimTTL );
324 // Reset job_token for these jobs so that other runners will pick them up.
325 // Set the timestamp to the current time, as it is useful to now that the job
326 // was already tried before.
327 $dbw->update( 'job',
328 array(
329 'job_token' => '',
330 'job_token_timestamp' => $dbw->timestamp( $now ) ), // time of release
331 array(
332 'job_cmd' => $this->type,
333 "job_token != {$dbw->addQuotes( '' )}", // was acquired
334 "job_token_timestamp < {$dbw->addQuotes( $claimCutoff )}", // stale
335 "job_attempts < {$dbw->addQuotes( self::MAX_ATTEMPTS )}" ),
336 __METHOD__
337 );
338 $count += $dbw->affectedRows();
339 }
340
341 // Just destroy stale jobs...
342 $pruneCutoff = $dbw->timestamp( $now - self::MAX_AGE_PRUNE );
343 $conds = array(
344 'job_cmd' => $this->type,
345 "job_token != {$dbw->addQuotes( '' )}", // was acquired
346 "job_token_timestamp < {$dbw->addQuotes( $pruneCutoff )}" // stale
347 );
348 if ( $this->claimTTL > 0 ) { // only prune jobs attempted too many times...
349 $conds[] = "job_attempts >= {$dbw->addQuotes( self::MAX_ATTEMPTS )}";
350 }
351 $dbw->delete( 'job', $conds, __METHOD__ );
352 $count += $dbw->affectedRows();
353
354 return $count;
355 }
356
357 /**
358 * @see JobQueue::doAck()
359 * @return Job|bool
360 */
361 protected function doAck( Job $job ) {
362 $dbw = $this->getMasterDB();
363 $dbw->commit( __METHOD__, 'flush' ); // flush existing transaction
364
365 $autoTrx = $dbw->getFlag( DBO_TRX ); // automatic begin() enabled?
366 $dbw->clearFlag( DBO_TRX ); // make each query its own transaction
367 try {
368 // Delete a row with a single DELETE without holding row locks over RTTs...
369 $dbw->delete( 'job', array( 'job_cmd' => $this->type, 'job_id' => $job->getId() ) );
370 } catch ( Exception $e ) {
371 $dbw->setFlag( $autoTrx ? DBO_TRX : 0 ); // restore automatic begin()
372 throw $e;
373 }
374 $dbw->setFlag( $autoTrx ? DBO_TRX : 0 ); // restore automatic begin()
375
376 return true;
377 }
378
379 /**
380 * @see JobQueue::doDeduplicateRootJob()
381 * @return bool
382 */
383 protected function doDeduplicateRootJob( Job $job ) {
384 $params = $job->getParams();
385 if ( !isset( $params['rootJobSignature'] ) ) {
386 throw new MWException( "Cannot register root job; missing 'rootJobSignature'." );
387 } elseif ( !isset( $params['rootJobTimestamp'] ) ) {
388 throw new MWException( "Cannot register root job; missing 'rootJobTimestamp'." );
389 }
390 $key = $this->getRootJobCacheKey( $params['rootJobSignature'] );
391 // Callers should call batchInsert() and then this function so that if the insert
392 // fails, the de-duplication registration will be aborted. Since the insert is
393 // deferred till "transaction idle", do that same here, so that the ordering is
394 // maintained. Having only the de-duplication registration succeed would cause
395 // jobs to become no-ops without any actual jobs that made them redundant.
396 $this->getMasterDB()->onTransactionIdle( function() use ( $params, $key ) {
397 global $wgMemc;
398
399 $timestamp = $wgMemc->get( $key ); // current last timestamp of this job
400 if ( $timestamp && $timestamp >= $params['rootJobTimestamp'] ) {
401 return true; // a newer version of this root job was enqueued
402 }
403
404 // Update the timestamp of the last root job started at the location...
405 return $wgMemc->set( $key, $params['rootJobTimestamp'], 14*86400 ); // 2 weeks
406 } );
407
408 return true;
409 }
410
411 /**
412 * Check if the "root" job of a given job has been superseded by a newer one
413 *
414 * @param $job Job
415 * @return bool
416 */
417 protected function isRootJobOldDuplicate( Job $job ) {
418 global $wgMemc;
419
420 $params = $job->getParams();
421 if ( !isset( $params['rootJobSignature'] ) ) {
422 return false; // job has no de-deplication info
423 } elseif ( !isset( $params['rootJobTimestamp'] ) ) {
424 trigger_error( "Cannot check root job; missing 'rootJobTimestamp'." );
425 return false;
426 }
427
428 // Get the last time this root job was enqueued
429 $timestamp = $wgMemc->get( $this->getRootJobCacheKey( $params['rootJobSignature'] ) );
430
431 // Check if a new root job was started at the location after this one's...
432 return ( $timestamp && $timestamp > $params['rootJobTimestamp'] );
433 }
434
435 /**
436 * @see JobQueue::doWaitForBackups()
437 * @return void
438 */
439 protected function doWaitForBackups() {
440 wfWaitForSlaves();
441 }
442
443 /**
444 * @return DatabaseBase
445 */
446 protected function getSlaveDB() {
447 return wfGetDB( DB_SLAVE, array(), $this->wiki );
448 }
449
450 /**
451 * @return DatabaseBase
452 */
453 protected function getMasterDB() {
454 return wfGetDB( DB_MASTER, array(), $this->wiki );
455 }
456
457 /**
458 * @param $job Job
459 * @return array
460 */
461 protected function insertFields( Job $job ) {
462 $dbw = $this->getMasterDB();
463 return array(
464 // Fields that describe the nature of the job
465 'job_cmd' => $job->getType(),
466 'job_namespace' => $job->getTitle()->getNamespace(),
467 'job_title' => $job->getTitle()->getDBkey(),
468 'job_params' => self::makeBlob( $job->getParams() ),
469 // Additional job metadata
470 'job_id' => $dbw->nextSequenceValue( 'job_job_id_seq' ),
471 'job_timestamp' => $dbw->timestamp(),
472 'job_sha1' => wfBaseConvert(
473 sha1( serialize( $job->getDeduplicationInfo() ) ),
474 16, 36, 31
475 ),
476 'job_random' => mt_rand( 0, self::MAX_JOB_RANDOM )
477 );
478 }
479
480 /**
481 * @return string
482 */
483 private function getEmptinessCacheKey() {
484 list( $db, $prefix ) = wfSplitWikiID( $this->wiki );
485 return wfForeignMemcKey( $db, $prefix, 'jobqueue', $this->type, 'isempty' );
486 }
487
488 /**
489 * @param string $signature Hash identifier of the root job
490 * @return string
491 */
492 private function getRootJobCacheKey( $signature ) {
493 list( $db, $prefix ) = wfSplitWikiID( $this->wiki );
494 return wfForeignMemcKey( $db, $prefix, 'jobqueue', $this->type, 'rootjob', $signature );
495 }
496
497 /**
498 * @param $params
499 * @return string
500 */
501 protected static function makeBlob( $params ) {
502 if ( $params !== false ) {
503 return serialize( $params );
504 } else {
505 return '';
506 }
507 }
508
509 /**
510 * @param $blob
511 * @return bool|mixed
512 */
513 protected static function extractBlob( $blob ) {
514 if ( (string)$blob !== '' ) {
515 return unserialize( $blob );
516 } else {
517 return false;
518 }
519 }
520 }