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