Send job ACKs to statsd
[lhc/web/wiklou.git] / includes / jobqueue / 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_SHORT = 30; // integer; seconds to cache info without re-validating
32 const MAX_AGE_PRUNE = 604800; // integer; seconds a job can live once claimed
33 const MAX_JOB_RANDOM = 2147483647; // integer; 2^31 - 1, used for job_random
34 const MAX_OFFSET = 255; // integer; maximum number of rows to skip
35
36 /** @var BagOStuff */
37 protected $cache;
38
39 /** @var bool|string Name of an external DB cluster. False if not set */
40 protected $cluster = false;
41
42 /**
43 * Additional parameters include:
44 * - cluster : The name of an external cluster registered via LBFactory.
45 * If not specified, the primary DB cluster for the wiki will be used.
46 * This can be overridden with a custom cluster so that DB handles will
47 * be retrieved via LBFactory::getExternalLB() and getConnection().
48 * @param array $params
49 */
50 protected function __construct( array $params ) {
51 global $wgMemc;
52
53 parent::__construct( $params );
54
55 $this->cluster = isset( $params['cluster'] ) ? $params['cluster'] : false;
56 // Make sure that we don't use the SQL cache, which would be harmful
57 $this->cache = ( $wgMemc instanceof SqlBagOStuff ) ? new EmptyBagOStuff() : $wgMemc;
58 }
59
60 protected function supportedOrders() {
61 return array( 'random', 'timestamp', 'fifo' );
62 }
63
64 protected function optimalOrder() {
65 return 'random';
66 }
67
68 /**
69 * @see JobQueue::doIsEmpty()
70 * @return bool
71 */
72 protected function doIsEmpty() {
73 $dbr = $this->getSlaveDB();
74 try {
75 $found = $dbr->selectField( // unclaimed job
76 'job', '1', array( 'job_cmd' => $this->type, 'job_token' => '' ), __METHOD__
77 );
78 } catch ( DBError $e ) {
79 $this->throwDBException( $e );
80 }
81
82 return !$found;
83 }
84
85 /**
86 * @see JobQueue::doGetSize()
87 * @return int
88 */
89 protected function doGetSize() {
90 $key = $this->getCacheKey( 'size' );
91
92 $size = $this->cache->get( $key );
93 if ( is_int( $size ) ) {
94 return $size;
95 }
96
97 try {
98 $dbr = $this->getSlaveDB();
99 $size = (int)$dbr->selectField( 'job', 'COUNT(*)',
100 array( 'job_cmd' => $this->type, 'job_token' => '' ),
101 __METHOD__
102 );
103 } catch ( DBError $e ) {
104 $this->throwDBException( $e );
105 }
106 $this->cache->set( $key, $size, self::CACHE_TTL_SHORT );
107
108 return $size;
109 }
110
111 /**
112 * @see JobQueue::doGetAcquiredCount()
113 * @return int
114 */
115 protected function doGetAcquiredCount() {
116 if ( $this->claimTTL <= 0 ) {
117 return 0; // no acknowledgements
118 }
119
120 $key = $this->getCacheKey( 'acquiredcount' );
121
122 $count = $this->cache->get( $key );
123 if ( is_int( $count ) ) {
124 return $count;
125 }
126
127 $dbr = $this->getSlaveDB();
128 try {
129 $count = (int)$dbr->selectField( 'job', 'COUNT(*)',
130 array( 'job_cmd' => $this->type, "job_token != {$dbr->addQuotes( '' )}" ),
131 __METHOD__
132 );
133 } catch ( DBError $e ) {
134 $this->throwDBException( $e );
135 }
136 $this->cache->set( $key, $count, self::CACHE_TTL_SHORT );
137
138 return $count;
139 }
140
141 /**
142 * @see JobQueue::doGetAbandonedCount()
143 * @return int
144 * @throws MWException
145 */
146 protected function doGetAbandonedCount() {
147 global $wgMemc;
148
149 if ( $this->claimTTL <= 0 ) {
150 return 0; // no acknowledgements
151 }
152
153 $key = $this->getCacheKey( 'abandonedcount' );
154
155 $count = $wgMemc->get( $key );
156 if ( is_int( $count ) ) {
157 return $count;
158 }
159
160 $dbr = $this->getSlaveDB();
161 try {
162 $count = (int)$dbr->selectField( 'job', 'COUNT(*)',
163 array(
164 'job_cmd' => $this->type,
165 "job_token != {$dbr->addQuotes( '' )}",
166 "job_attempts >= " . $dbr->addQuotes( $this->maxTries )
167 ),
168 __METHOD__
169 );
170 } catch ( DBError $e ) {
171 $this->throwDBException( $e );
172 }
173 $wgMemc->set( $key, $count, self::CACHE_TTL_SHORT );
174
175 return $count;
176 }
177
178 /**
179 * @see JobQueue::doBatchPush()
180 * @param array $jobs
181 * @param int $flags
182 * @throws DBError|Exception
183 * @return void
184 */
185 protected function doBatchPush( array $jobs, $flags ) {
186 $dbw = $this->getMasterDB();
187
188 $that = $this;
189 $method = __METHOD__;
190 $dbw->onTransactionIdle(
191 function () use ( $dbw, $that, $jobs, $flags, $method ) {
192 $that->doBatchPushInternal( $dbw, $jobs, $flags, $method );
193 }
194 );
195 }
196
197 /**
198 * This function should *not* be called outside of JobQueueDB
199 *
200 * @param IDatabase $dbw
201 * @param array $jobs
202 * @param int $flags
203 * @param string $method
204 * @throws DBError
205 * @return void
206 */
207 public function doBatchPushInternal( IDatabase $dbw, array $jobs, $flags, $method ) {
208 if ( !count( $jobs ) ) {
209 return;
210 }
211
212 $rowSet = array(); // (sha1 => job) map for jobs that are de-duplicated
213 $rowList = array(); // list of jobs for jobs that are not de-duplicated
214 foreach ( $jobs as $job ) {
215 $row = $this->insertFields( $job );
216 if ( $job->ignoreDuplicates() ) {
217 $rowSet[$row['job_sha1']] = $row;
218 } else {
219 $rowList[] = $row;
220 }
221 }
222
223 if ( $flags & self::QOS_ATOMIC ) {
224 $dbw->begin( $method ); // wrap all the job additions in one transaction
225 }
226 try {
227 // Strip out any duplicate jobs that are already in the queue...
228 if ( count( $rowSet ) ) {
229 $res = $dbw->select( 'job', 'job_sha1',
230 array(
231 // No job_type condition since it's part of the job_sha1 hash
232 'job_sha1' => array_keys( $rowSet ),
233 'job_token' => '' // unclaimed
234 ),
235 $method
236 );
237 foreach ( $res as $row ) {
238 wfDebug( "Job with hash '{$row->job_sha1}' is a duplicate.\n" );
239 unset( $rowSet[$row->job_sha1] ); // already enqueued
240 }
241 }
242 // Build the full list of job rows to insert
243 $rows = array_merge( $rowList, array_values( $rowSet ) );
244 // Insert the job rows in chunks to avoid slave lag...
245 foreach ( array_chunk( $rows, 50 ) as $rowBatch ) {
246 $dbw->insert( 'job', $rowBatch, $method );
247 }
248 JobQueue::incrStats( 'job-insert', $this->type, count( $rows ) );
249 JobQueue::incrStats(
250 'job-insert-duplicate',
251 $this->type,
252 count( $rowSet ) + count( $rowList ) - count( $rows )
253 );
254 } catch ( DBError $e ) {
255 if ( $flags & self::QOS_ATOMIC ) {
256 $dbw->rollback( $method );
257 }
258 throw $e;
259 }
260 if ( $flags & self::QOS_ATOMIC ) {
261 $dbw->commit( $method );
262 }
263
264 return;
265 }
266
267 /**
268 * @see JobQueue::doPop()
269 * @return Job|bool
270 */
271 protected function doPop() {
272 $dbw = $this->getMasterDB();
273 try {
274 $dbw->commit( __METHOD__, 'flush' ); // flush existing transaction
275 $autoTrx = $dbw->getFlag( DBO_TRX ); // get current setting
276 $dbw->clearFlag( DBO_TRX ); // make each query its own transaction
277 $scopedReset = new ScopedCallback( function () use ( $dbw, $autoTrx ) {
278 $dbw->setFlag( $autoTrx ? DBO_TRX : 0 ); // restore old setting
279 } );
280
281 $uuid = wfRandomString( 32 ); // pop attempt
282 $job = false; // job popped off
283 do { // retry when our row is invalid or deleted as a duplicate
284 // Try to reserve a row in the DB...
285 if ( in_array( $this->order, array( 'fifo', 'timestamp' ) ) ) {
286 $row = $this->claimOldest( $uuid );
287 } else { // random first
288 $rand = mt_rand( 0, self::MAX_JOB_RANDOM ); // encourage concurrent UPDATEs
289 $gte = (bool)mt_rand( 0, 1 ); // find rows with rand before/after $rand
290 $row = $this->claimRandom( $uuid, $rand, $gte );
291 }
292 // Check if we found a row to reserve...
293 if ( !$row ) {
294 break; // nothing to do
295 }
296 JobQueue::incrStats( 'job-pop', $this->type );
297 // Get the job object from the row...
298 $title = Title::makeTitle( $row->job_namespace, $row->job_title );
299 $job = Job::factory( $row->job_cmd, $title,
300 self::extractBlob( $row->job_params ), $row->job_id );
301 $job->metadata['id'] = $row->job_id;
302 break; // done
303 } while ( true );
304 } catch ( DBError $e ) {
305 $this->throwDBException( $e );
306 }
307
308 return $job;
309 }
310
311 /**
312 * Reserve a row with a single UPDATE without holding row locks over RTTs...
313 *
314 * @param string $uuid 32 char hex string
315 * @param int $rand Random unsigned integer (31 bits)
316 * @param bool $gte Search for job_random >= $random (otherwise job_random <= $random)
317 * @return stdClass|bool Row|false
318 */
319 protected function claimRandom( $uuid, $rand, $gte ) {
320 $dbw = $this->getMasterDB();
321 // Check cache to see if the queue has <= OFFSET items
322 $tinyQueue = $this->cache->get( $this->getCacheKey( 'small' ) );
323
324 $row = false; // the row acquired
325 $invertedDirection = false; // whether one job_random direction was already scanned
326 // This uses a replication safe method for acquiring jobs. One could use UPDATE+LIMIT
327 // instead, but that either uses ORDER BY (in which case it deadlocks in MySQL) or is
328 // not replication safe. Due to http://bugs.mysql.com/bug.php?id=6980, subqueries cannot
329 // be used here with MySQL.
330 do {
331 if ( $tinyQueue ) { // queue has <= MAX_OFFSET rows
332 // For small queues, using OFFSET will overshoot and return no rows more often.
333 // Instead, this uses job_random to pick a row (possibly checking both directions).
334 $ineq = $gte ? '>=' : '<=';
335 $dir = $gte ? 'ASC' : 'DESC';
336 $row = $dbw->selectRow( 'job', self::selectFields(), // find a random job
337 array(
338 'job_cmd' => $this->type,
339 'job_token' => '', // unclaimed
340 "job_random {$ineq} {$dbw->addQuotes( $rand )}" ),
341 __METHOD__,
342 array( 'ORDER BY' => "job_random {$dir}" )
343 );
344 if ( !$row && !$invertedDirection ) {
345 $gte = !$gte;
346 $invertedDirection = true;
347 continue; // try the other direction
348 }
349 } else { // table *may* have >= MAX_OFFSET rows
350 // Bug 42614: "ORDER BY job_random" with a job_random inequality causes high CPU
351 // in MySQL if there are many rows for some reason. This uses a small OFFSET
352 // instead of job_random for reducing excess claim retries.
353 $row = $dbw->selectRow( 'job', self::selectFields(), // find a random job
354 array(
355 'job_cmd' => $this->type,
356 'job_token' => '', // unclaimed
357 ),
358 __METHOD__,
359 array( 'OFFSET' => mt_rand( 0, self::MAX_OFFSET ) )
360 );
361 if ( !$row ) {
362 $tinyQueue = true; // we know the queue must have <= MAX_OFFSET rows
363 $this->cache->set( $this->getCacheKey( 'small' ), 1, 30 );
364 continue; // use job_random
365 }
366 }
367
368 if ( $row ) { // claim the job
369 $dbw->update( 'job', // update by PK
370 array(
371 'job_token' => $uuid,
372 'job_token_timestamp' => $dbw->timestamp(),
373 'job_attempts = job_attempts+1' ),
374 array( 'job_cmd' => $this->type, 'job_id' => $row->job_id, 'job_token' => '' ),
375 __METHOD__
376 );
377 // This might get raced out by another runner when claiming the previously
378 // selected row. The use of job_random should minimize this problem, however.
379 if ( !$dbw->affectedRows() ) {
380 $row = false; // raced out
381 }
382 } else {
383 break; // nothing to do
384 }
385 } while ( !$row );
386
387 return $row;
388 }
389
390 /**
391 * Reserve a row with a single UPDATE without holding row locks over RTTs...
392 *
393 * @param string $uuid 32 char hex string
394 * @return stdClass|bool Row|false
395 */
396 protected function claimOldest( $uuid ) {
397 $dbw = $this->getMasterDB();
398
399 $row = false; // the row acquired
400 do {
401 if ( $dbw->getType() === 'mysql' ) {
402 // Per http://bugs.mysql.com/bug.php?id=6980, we can't use subqueries on the
403 // same table being changed in an UPDATE query in MySQL (gives Error: 1093).
404 // Oracle and Postgre have no such limitation. However, MySQL offers an
405 // alternative here by supporting ORDER BY + LIMIT for UPDATE queries.
406 $dbw->query( "UPDATE {$dbw->tableName( 'job' )} " .
407 "SET " .
408 "job_token = {$dbw->addQuotes( $uuid ) }, " .
409 "job_token_timestamp = {$dbw->addQuotes( $dbw->timestamp() )}, " .
410 "job_attempts = job_attempts+1 " .
411 "WHERE ( " .
412 "job_cmd = {$dbw->addQuotes( $this->type )} " .
413 "AND job_token = {$dbw->addQuotes( '' )} " .
414 ") ORDER BY job_id ASC LIMIT 1",
415 __METHOD__
416 );
417 } else {
418 // Use a subquery to find the job, within an UPDATE to claim it.
419 // This uses as much of the DB wrapper functions as possible.
420 $dbw->update( 'job',
421 array(
422 'job_token' => $uuid,
423 'job_token_timestamp' => $dbw->timestamp(),
424 'job_attempts = job_attempts+1' ),
425 array( 'job_id = (' .
426 $dbw->selectSQLText( 'job', 'job_id',
427 array( 'job_cmd' => $this->type, 'job_token' => '' ),
428 __METHOD__,
429 array( 'ORDER BY' => 'job_id ASC', 'LIMIT' => 1 ) ) .
430 ')'
431 ),
432 __METHOD__
433 );
434 }
435 // Fetch any row that we just reserved...
436 if ( $dbw->affectedRows() ) {
437 $row = $dbw->selectRow( 'job', self::selectFields(),
438 array( 'job_cmd' => $this->type, 'job_token' => $uuid ), __METHOD__
439 );
440 if ( !$row ) { // raced out by duplicate job removal
441 wfDebug( "Row deleted as duplicate by another process.\n" );
442 }
443 } else {
444 break; // nothing to do
445 }
446 } while ( !$row );
447
448 return $row;
449 }
450
451 /**
452 * @see JobQueue::doAck()
453 * @param Job $job
454 * @throws MWException
455 * @return Job|bool
456 */
457 protected function doAck( Job $job ) {
458 if ( !isset( $job->metadata['id'] ) ) {
459 throw new MWException( "Job of type '{$job->getType()}' has no ID." );
460 }
461
462 $dbw = $this->getMasterDB();
463 try {
464 $dbw->commit( __METHOD__, 'flush' ); // flush existing transaction
465 $autoTrx = $dbw->getFlag( DBO_TRX ); // get current setting
466 $dbw->clearFlag( DBO_TRX ); // make each query its own transaction
467 $scopedReset = new ScopedCallback( function () use ( $dbw, $autoTrx ) {
468 $dbw->setFlag( $autoTrx ? DBO_TRX : 0 ); // restore old setting
469 } );
470
471 // Delete a row with a single DELETE without holding row locks over RTTs...
472 $dbw->delete( 'job',
473 array( 'job_cmd' => $this->type, 'job_id' => $job->metadata['id'] ), __METHOD__ );
474
475 JobQueue::incrStats( 'job-ack', $this->type );
476 } catch ( DBError $e ) {
477 $this->throwDBException( $e );
478 }
479
480 return true;
481 }
482
483 /**
484 * @see JobQueue::doDeduplicateRootJob()
485 * @param Job $job
486 * @throws MWException
487 * @return bool
488 */
489 protected function doDeduplicateRootJob( Job $job ) {
490 $params = $job->getParams();
491 if ( !isset( $params['rootJobSignature'] ) ) {
492 throw new MWException( "Cannot register root job; missing 'rootJobSignature'." );
493 } elseif ( !isset( $params['rootJobTimestamp'] ) ) {
494 throw new MWException( "Cannot register root job; missing 'rootJobTimestamp'." );
495 }
496 $key = $this->getRootJobCacheKey( $params['rootJobSignature'] );
497 // Callers should call batchInsert() and then this function so that if the insert
498 // fails, the de-duplication registration will be aborted. Since the insert is
499 // deferred till "transaction idle", do the same here, so that the ordering is
500 // maintained. Having only the de-duplication registration succeed would cause
501 // jobs to become no-ops without any actual jobs that made them redundant.
502 $dbw = $this->getMasterDB();
503 $cache = $this->dupCache;
504 $dbw->onTransactionIdle( function () use ( $cache, $params, $key, $dbw ) {
505 $timestamp = $cache->get( $key ); // current last timestamp of this job
506 if ( $timestamp && $timestamp >= $params['rootJobTimestamp'] ) {
507 return true; // a newer version of this root job was enqueued
508 }
509
510 // Update the timestamp of the last root job started at the location...
511 return $cache->set( $key, $params['rootJobTimestamp'], JobQueueDB::ROOTJOB_TTL );
512 } );
513
514 return true;
515 }
516
517 /**
518 * @see JobQueue::doDelete()
519 * @return bool
520 */
521 protected function doDelete() {
522 $dbw = $this->getMasterDB();
523 try {
524 $dbw->delete( 'job', array( 'job_cmd' => $this->type ) );
525 } catch ( DBError $e ) {
526 $this->throwDBException( $e );
527 }
528
529 return true;
530 }
531
532 /**
533 * @see JobQueue::doWaitForBackups()
534 * @return void
535 */
536 protected function doWaitForBackups() {
537 wfWaitForSlaves( false, $this->wiki, $this->cluster ?: false );
538 }
539
540 /**
541 * @return array
542 */
543 protected function doGetPeriodicTasks() {
544 return array(
545 'recycleAndDeleteStaleJobs' => array(
546 'callback' => array( $this, 'recycleAndDeleteStaleJobs' ),
547 'period' => ceil( $this->claimTTL / 2 )
548 )
549 );
550 }
551
552 /**
553 * @return void
554 */
555 protected function doFlushCaches() {
556 foreach ( array( 'size', 'acquiredcount' ) as $type ) {
557 $this->cache->delete( $this->getCacheKey( $type ) );
558 }
559 }
560
561 /**
562 * @see JobQueue::getAllQueuedJobs()
563 * @return Iterator
564 */
565 public function getAllQueuedJobs() {
566 $dbr = $this->getSlaveDB();
567 try {
568 return new MappedIterator(
569 $dbr->select( 'job', self::selectFields(),
570 array( 'job_cmd' => $this->getType(), 'job_token' => '' ) ),
571 function ( $row ) use ( $dbr ) {
572 $job = Job::factory(
573 $row->job_cmd,
574 Title::makeTitle( $row->job_namespace, $row->job_title ),
575 strlen( $row->job_params ) ? unserialize( $row->job_params ) : false
576 );
577 $job->metadata['id'] = $row->job_id;
578 return $job;
579 }
580 );
581 } catch ( DBError $e ) {
582 $this->throwDBException( $e );
583 }
584 }
585
586 public function getCoalesceLocationInternal() {
587 return $this->cluster
588 ? "DBCluster:{$this->cluster}:{$this->wiki}"
589 : "LBFactory:{$this->wiki}";
590 }
591
592 protected function doGetSiblingQueuesWithJobs( array $types ) {
593 $dbr = $this->getSlaveDB();
594 $res = $dbr->select( 'job', 'DISTINCT job_cmd',
595 array( 'job_cmd' => $types ), __METHOD__ );
596
597 $types = array();
598 foreach ( $res as $row ) {
599 $types[] = $row->job_cmd;
600 }
601
602 return $types;
603 }
604
605 protected function doGetSiblingQueueSizes( array $types ) {
606 $dbr = $this->getSlaveDB();
607 $res = $dbr->select( 'job', array( 'job_cmd', 'COUNT(*) AS count' ),
608 array( 'job_cmd' => $types ), __METHOD__, array( 'GROUP BY' => 'job_cmd' ) );
609
610 $sizes = array();
611 foreach ( $res as $row ) {
612 $sizes[$row->job_cmd] = (int)$row->count;
613 }
614
615 return $sizes;
616 }
617
618 /**
619 * Recycle or destroy any jobs that have been claimed for too long
620 *
621 * @return int Number of jobs recycled/deleted
622 */
623 public function recycleAndDeleteStaleJobs() {
624 $now = time();
625 $count = 0; // affected rows
626 $dbw = $this->getMasterDB();
627
628 try {
629 if ( !$dbw->lock( "jobqueue-recycle-{$this->type}", __METHOD__, 1 ) ) {
630 return $count; // already in progress
631 }
632
633 // Remove claims on jobs acquired for too long if enabled...
634 if ( $this->claimTTL > 0 ) {
635 $claimCutoff = $dbw->timestamp( $now - $this->claimTTL );
636 // Get the IDs of jobs that have be claimed but not finished after too long.
637 // These jobs can be recycled into the queue by expiring the claim. Selecting
638 // the IDs first means that the UPDATE can be done by primary key (less deadlocks).
639 $res = $dbw->select( 'job', 'job_id',
640 array(
641 'job_cmd' => $this->type,
642 "job_token != {$dbw->addQuotes( '' )}", // was acquired
643 "job_token_timestamp < {$dbw->addQuotes( $claimCutoff )}", // stale
644 "job_attempts < {$dbw->addQuotes( $this->maxTries )}" ), // retries left
645 __METHOD__
646 );
647 $ids = array_map(
648 function ( $o ) {
649 return $o->job_id;
650 }, iterator_to_array( $res )
651 );
652 if ( count( $ids ) ) {
653 // Reset job_token for these jobs so that other runners will pick them up.
654 // Set the timestamp to the current time, as it is useful to now that the job
655 // was already tried before (the timestamp becomes the "released" time).
656 $dbw->update( 'job',
657 array(
658 'job_token' => '',
659 'job_token_timestamp' => $dbw->timestamp( $now ) ), // time of release
660 array(
661 'job_id' => $ids ),
662 __METHOD__
663 );
664 $affected = $dbw->affectedRows();
665 $count += $affected;
666 JobQueue::incrStats( 'job-recycle', $this->type, $affected );
667 $this->aggr->notifyQueueNonEmpty( $this->wiki, $this->type );
668 }
669 }
670
671 // Just destroy any stale jobs...
672 $pruneCutoff = $dbw->timestamp( $now - self::MAX_AGE_PRUNE );
673 $conds = array(
674 'job_cmd' => $this->type,
675 "job_token != {$dbw->addQuotes( '' )}", // was acquired
676 "job_token_timestamp < {$dbw->addQuotes( $pruneCutoff )}" // stale
677 );
678 if ( $this->claimTTL > 0 ) { // only prune jobs attempted too many times...
679 $conds[] = "job_attempts >= {$dbw->addQuotes( $this->maxTries )}";
680 }
681 // Get the IDs of jobs that are considered stale and should be removed. Selecting
682 // the IDs first means that the UPDATE can be done by primary key (less deadlocks).
683 $res = $dbw->select( 'job', 'job_id', $conds, __METHOD__ );
684 $ids = array_map(
685 function ( $o ) {
686 return $o->job_id;
687 }, iterator_to_array( $res )
688 );
689 if ( count( $ids ) ) {
690 $dbw->delete( 'job', array( 'job_id' => $ids ), __METHOD__ );
691 $affected = $dbw->affectedRows();
692 $count += $affected;
693 JobQueue::incrStats( 'job-abandon', $this->type, $affected );
694 }
695
696 $dbw->unlock( "jobqueue-recycle-{$this->type}", __METHOD__ );
697 } catch ( DBError $e ) {
698 $this->throwDBException( $e );
699 }
700
701 return $count;
702 }
703
704 /**
705 * @param IJobSpecification $job
706 * @return array
707 */
708 protected function insertFields( IJobSpecification $job ) {
709 $dbw = $this->getMasterDB();
710
711 return array(
712 // Fields that describe the nature of the job
713 'job_cmd' => $job->getType(),
714 'job_namespace' => $job->getTitle()->getNamespace(),
715 'job_title' => $job->getTitle()->getDBkey(),
716 'job_params' => self::makeBlob( $job->getParams() ),
717 // Additional job metadata
718 'job_id' => $dbw->nextSequenceValue( 'job_job_id_seq' ),
719 'job_timestamp' => $dbw->timestamp(),
720 'job_sha1' => wfBaseConvert(
721 sha1( serialize( $job->getDeduplicationInfo() ) ),
722 16, 36, 31
723 ),
724 'job_random' => mt_rand( 0, self::MAX_JOB_RANDOM )
725 );
726 }
727
728 /**
729 * @throws JobQueueConnectionError
730 * @return DBConnRef
731 */
732 protected function getSlaveDB() {
733 try {
734 return $this->getDB( DB_SLAVE );
735 } catch ( DBConnectionError $e ) {
736 throw new JobQueueConnectionError( "DBConnectionError:" . $e->getMessage() );
737 }
738 }
739
740 /**
741 * @throws JobQueueConnectionError
742 * @return DBConnRef
743 */
744 protected function getMasterDB() {
745 try {
746 return $this->getDB( DB_MASTER );
747 } catch ( DBConnectionError $e ) {
748 throw new JobQueueConnectionError( "DBConnectionError:" . $e->getMessage() );
749 }
750 }
751
752 /**
753 * @param int $index (DB_SLAVE/DB_MASTER)
754 * @return DBConnRef
755 */
756 protected function getDB( $index ) {
757 $lb = ( $this->cluster !== false )
758 ? wfGetLBFactory()->getExternalLB( $this->cluster, $this->wiki )
759 : wfGetLB( $this->wiki );
760
761 return $lb->getConnectionRef( $index, array(), $this->wiki );
762 }
763
764 /**
765 * @param string $property
766 * @return string
767 */
768 private function getCacheKey( $property ) {
769 list( $db, $prefix ) = wfSplitWikiID( $this->wiki );
770 $cluster = is_string( $this->cluster ) ? $this->cluster : 'main';
771
772 return wfForeignMemcKey( $db, $prefix, 'jobqueue', $cluster, $this->type, $property );
773 }
774
775 /**
776 * @param array|bool $params
777 * @return string
778 */
779 protected static function makeBlob( $params ) {
780 if ( $params !== false ) {
781 return serialize( $params );
782 } else {
783 return '';
784 }
785 }
786
787 /**
788 * @param string $blob
789 * @return bool|mixed
790 */
791 protected static function extractBlob( $blob ) {
792 if ( (string)$blob !== '' ) {
793 return unserialize( $blob );
794 } else {
795 return false;
796 }
797 }
798
799 /**
800 * @param DBError $e
801 * @throws JobQueueError
802 */
803 protected function throwDBException( DBError $e ) {
804 throw new JobQueueError( get_class( $e ) . ": " . $e->getMessage() );
805 }
806
807 /**
808 * Return the list of job fields that should be selected.
809 * @since 1.23
810 * @return array
811 */
812 public static function selectFields() {
813 return array(
814 'job_id',
815 'job_cmd',
816 'job_namespace',
817 'job_title',
818 'job_timestamp',
819 'job_params',
820 'job_random',
821 'job_attempts',
822 'job_token',
823 'job_token_timestamp',
824 'job_sha1',
825 );
826 }
827 }