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