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