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