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