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