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