Merge "protect.js: Reorder function declararion to avoid forward reference"
[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->setMetadata( 'id', $row->job_id );
321 $job->setMetadata( '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 $id = $job->getMetadata( 'id' );
488 if ( $id === null ) {
489 throw new MWException( "Job of type '{$job->getType()}' has no ID." );
490 }
491
492 $dbw = $this->getMasterDB();
493 /** @noinspection PhpUnusedLocalVariableInspection */
494 $scope = $this->getScopedNoTrxFlag( $dbw );
495 try {
496 // Delete a row with a single DELETE without holding row locks over RTTs...
497 $dbw->delete(
498 'job',
499 [ 'job_cmd' => $this->type, 'job_id' => $id ],
500 __METHOD__
501 );
502
503 JobQueue::incrStats( 'acks', $this->type );
504 } catch ( DBError $e ) {
505 $this->throwDBException( $e );
506 }
507 }
508
509 /**
510 * @see JobQueue::doDeduplicateRootJob()
511 * @param IJobSpecification $job
512 * @throws MWException
513 * @return bool
514 */
515 protected function doDeduplicateRootJob( IJobSpecification $job ) {
516 $params = $job->getParams();
517 if ( !isset( $params['rootJobSignature'] ) ) {
518 throw new MWException( "Cannot register root job; missing 'rootJobSignature'." );
519 } elseif ( !isset( $params['rootJobTimestamp'] ) ) {
520 throw new MWException( "Cannot register root job; missing 'rootJobTimestamp'." );
521 }
522 $key = $this->getRootJobCacheKey( $params['rootJobSignature'] );
523 // Callers should call JobQueueGroup::push() before this method so that if the insert
524 // fails, the de-duplication registration will be aborted. Since the insert is
525 // deferred till "transaction idle", do the same here, so that the ordering is
526 // maintained. Having only the de-duplication registration succeed would cause
527 // jobs to become no-ops without any actual jobs that made them redundant.
528 $dbw = $this->getMasterDB();
529 /** @noinspection PhpUnusedLocalVariableInspection */
530 $scope = $this->getScopedNoTrxFlag( $dbw );
531
532 $cache = $this->dupCache;
533 $dbw->onTransactionCommitOrIdle(
534 function () use ( $cache, $params, $key ) {
535 $timestamp = $cache->get( $key ); // current last timestamp of this job
536 if ( $timestamp && $timestamp >= $params['rootJobTimestamp'] ) {
537 return true; // a newer version of this root job was enqueued
538 }
539
540 // Update the timestamp of the last root job started at the location...
541 return $cache->set( $key, $params['rootJobTimestamp'], JobQueueDB::ROOTJOB_TTL );
542 },
543 __METHOD__
544 );
545
546 return true;
547 }
548
549 /**
550 * @see JobQueue::doDelete()
551 * @return bool
552 */
553 protected function doDelete() {
554 $dbw = $this->getMasterDB();
555 /** @noinspection PhpUnusedLocalVariableInspection */
556 $scope = $this->getScopedNoTrxFlag( $dbw );
557 try {
558 $dbw->delete( 'job', [ 'job_cmd' => $this->type ] );
559 } catch ( DBError $e ) {
560 $this->throwDBException( $e );
561 }
562
563 return true;
564 }
565
566 /**
567 * @see JobQueue::doWaitForBackups()
568 * @return void
569 */
570 protected function doWaitForBackups() {
571 if ( $this->server ) {
572 return; // not using LBFactory instance
573 }
574
575 $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
576 $lbFactory->waitForReplication( [
577 'domain' => $this->domain,
578 'cluster' => is_string( $this->cluster ) ? $this->cluster : false
579 ] );
580 }
581
582 /**
583 * @return void
584 */
585 protected function doFlushCaches() {
586 foreach ( [ 'size', 'acquiredcount' ] as $type ) {
587 $this->cache->delete( $this->getCacheKey( $type ) );
588 }
589 }
590
591 /**
592 * @see JobQueue::getAllQueuedJobs()
593 * @return Iterator
594 */
595 public function getAllQueuedJobs() {
596 return $this->getJobIterator( [ 'job_cmd' => $this->getType(), 'job_token' => '' ] );
597 }
598
599 /**
600 * @see JobQueue::getAllAcquiredJobs()
601 * @return Iterator
602 */
603 public function getAllAcquiredJobs() {
604 return $this->getJobIterator( [ 'job_cmd' => $this->getType(), "job_token > ''" ] );
605 }
606
607 /**
608 * @param array $conds Query conditions
609 * @return Iterator
610 */
611 protected function getJobIterator( array $conds ) {
612 $dbr = $this->getReplicaDB();
613 /** @noinspection PhpUnusedLocalVariableInspection */
614 $scope = $this->getScopedNoTrxFlag( $dbr );
615 try {
616 return new MappedIterator(
617 $dbr->select( 'job', self::selectFields(), $conds ),
618 function ( $row ) {
619 $job = Job::factory(
620 $row->job_cmd,
621 Title::makeTitle( $row->job_namespace, $row->job_title ),
622 strlen( $row->job_params ) ? unserialize( $row->job_params ) : []
623 );
624 $job->setMetadata( 'id', $row->job_id );
625 $job->setMetadata( 'timestamp', $row->job_timestamp );
626
627 return $job;
628 }
629 );
630 } catch ( DBError $e ) {
631 $this->throwDBException( $e );
632 }
633 }
634
635 public function getCoalesceLocationInternal() {
636 if ( $this->server ) {
637 return null; // not using the LBFactory instance
638 }
639
640 return is_string( $this->cluster )
641 ? "DBCluster:{$this->cluster}:{$this->domain}"
642 : "LBFactory:{$this->domain}";
643 }
644
645 protected function doGetSiblingQueuesWithJobs( array $types ) {
646 $dbr = $this->getReplicaDB();
647 /** @noinspection PhpUnusedLocalVariableInspection */
648 $scope = $this->getScopedNoTrxFlag( $dbr );
649 // @note: this does not check whether the jobs are claimed or not.
650 // This is useful so JobQueueGroup::pop() also sees queues that only
651 // have stale jobs. This lets recycleAndDeleteStaleJobs() re-enqueue
652 // failed jobs so that they can be popped again for that edge case.
653 $res = $dbr->select( 'job', 'DISTINCT job_cmd',
654 [ 'job_cmd' => $types ], __METHOD__ );
655
656 $types = [];
657 foreach ( $res as $row ) {
658 $types[] = $row->job_cmd;
659 }
660
661 return $types;
662 }
663
664 protected function doGetSiblingQueueSizes( array $types ) {
665 $dbr = $this->getReplicaDB();
666 /** @noinspection PhpUnusedLocalVariableInspection */
667 $scope = $this->getScopedNoTrxFlag( $dbr );
668
669 $res = $dbr->select( 'job', [ 'job_cmd', 'COUNT(*) AS count' ],
670 [ 'job_cmd' => $types ], __METHOD__, [ 'GROUP BY' => 'job_cmd' ] );
671
672 $sizes = [];
673 foreach ( $res as $row ) {
674 $sizes[$row->job_cmd] = (int)$row->count;
675 }
676
677 return $sizes;
678 }
679
680 /**
681 * Recycle or destroy any jobs that have been claimed for too long
682 *
683 * @return int Number of jobs recycled/deleted
684 */
685 public function recycleAndDeleteStaleJobs() {
686 $now = time();
687 $count = 0; // affected rows
688 $dbw = $this->getMasterDB();
689 /** @noinspection PhpUnusedLocalVariableInspection */
690 $scope = $this->getScopedNoTrxFlag( $dbw );
691
692 try {
693 if ( !$dbw->lock( "jobqueue-recycle-{$this->type}", __METHOD__, 1 ) ) {
694 return $count; // already in progress
695 }
696
697 // Remove claims on jobs acquired for too long if enabled...
698 if ( $this->claimTTL > 0 ) {
699 $claimCutoff = $dbw->timestamp( $now - $this->claimTTL );
700 // Get the IDs of jobs that have be claimed but not finished after too long.
701 // These jobs can be recycled into the queue by expiring the claim. Selecting
702 // the IDs first means that the UPDATE can be done by primary key (less deadlocks).
703 $res = $dbw->select( 'job', 'job_id',
704 [
705 'job_cmd' => $this->type,
706 "job_token != {$dbw->addQuotes( '' )}", // was acquired
707 "job_token_timestamp < {$dbw->addQuotes( $claimCutoff )}", // stale
708 "job_attempts < {$dbw->addQuotes( $this->maxTries )}" ], // retries left
709 __METHOD__
710 );
711 $ids = array_map(
712 function ( $o ) {
713 return $o->job_id;
714 }, iterator_to_array( $res )
715 );
716 if ( count( $ids ) ) {
717 // Reset job_token for these jobs so that other runners will pick them up.
718 // Set the timestamp to the current time, as it is useful to now that the job
719 // was already tried before (the timestamp becomes the "released" time).
720 $dbw->update( 'job',
721 [
722 'job_token' => '',
723 'job_token_timestamp' => $dbw->timestamp( $now ) ], // time of release
724 [
725 'job_id' => $ids ],
726 __METHOD__
727 );
728 $affected = $dbw->affectedRows();
729 $count += $affected;
730 JobQueue::incrStats( 'recycles', $this->type, $affected );
731 }
732 }
733
734 // Just destroy any stale jobs...
735 $pruneCutoff = $dbw->timestamp( $now - self::MAX_AGE_PRUNE );
736 $conds = [
737 'job_cmd' => $this->type,
738 "job_token != {$dbw->addQuotes( '' )}", // was acquired
739 "job_token_timestamp < {$dbw->addQuotes( $pruneCutoff )}" // stale
740 ];
741 if ( $this->claimTTL > 0 ) { // only prune jobs attempted too many times...
742 $conds[] = "job_attempts >= {$dbw->addQuotes( $this->maxTries )}";
743 }
744 // Get the IDs of jobs that are considered stale and should be removed. Selecting
745 // the IDs first means that the UPDATE can be done by primary key (less deadlocks).
746 $res = $dbw->select( 'job', 'job_id', $conds, __METHOD__ );
747 $ids = array_map(
748 function ( $o ) {
749 return $o->job_id;
750 }, iterator_to_array( $res )
751 );
752 if ( count( $ids ) ) {
753 $dbw->delete( 'job', [ 'job_id' => $ids ], __METHOD__ );
754 $affected = $dbw->affectedRows();
755 $count += $affected;
756 JobQueue::incrStats( 'abandons', $this->type, $affected );
757 }
758
759 $dbw->unlock( "jobqueue-recycle-{$this->type}", __METHOD__ );
760 } catch ( DBError $e ) {
761 $this->throwDBException( $e );
762 }
763
764 return $count;
765 }
766
767 /**
768 * @param IJobSpecification $job
769 * @param IDatabase $db
770 * @return array
771 */
772 protected function insertFields( IJobSpecification $job, IDatabase $db ) {
773 return [
774 // Fields that describe the nature of the job
775 'job_cmd' => $job->getType(),
776 'job_namespace' => $job->getTitle()->getNamespace(),
777 'job_title' => $job->getTitle()->getDBkey(),
778 'job_params' => self::makeBlob( $job->getParams() ),
779 // Additional job metadata
780 'job_timestamp' => $db->timestamp(),
781 'job_sha1' => Wikimedia\base_convert(
782 sha1( serialize( $job->getDeduplicationInfo() ) ),
783 16, 36, 31
784 ),
785 'job_random' => mt_rand( 0, self::MAX_JOB_RANDOM )
786 ];
787 }
788
789 /**
790 * @throws JobQueueConnectionError
791 * @return IDatabase
792 */
793 protected function getReplicaDB() {
794 try {
795 return $this->getDB( DB_REPLICA );
796 } catch ( DBConnectionError $e ) {
797 throw new JobQueueConnectionError( "DBConnectionError:" . $e->getMessage() );
798 }
799 }
800
801 /**
802 * @throws JobQueueConnectionError
803 * @return IDatabase
804 */
805 protected function getMasterDB() {
806 try {
807 return $this->getDB( DB_MASTER );
808 } catch ( DBConnectionError $e ) {
809 throw new JobQueueConnectionError( "DBConnectionError:" . $e->getMessage() );
810 }
811 }
812
813 /**
814 * @param int $index (DB_REPLICA/DB_MASTER)
815 * @return IDatabase
816 */
817 protected function getDB( $index ) {
818 if ( $this->server ) {
819 if ( $this->conn instanceof IDatabase ) {
820 return $this->conn;
821 } elseif ( $this->conn instanceof DBError ) {
822 throw $this->conn;
823 }
824
825 try {
826 $this->conn = Database::factory( $this->server['type'], $this->server );
827 } catch ( DBError $e ) {
828 $this->conn = $e;
829 throw $e;
830 }
831
832 return $this->conn;
833 } else {
834 $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
835 $lb = is_string( $this->cluster )
836 ? $lbFactory->getExternalLB( $this->cluster )
837 : $lbFactory->getMainLB( $this->domain );
838
839 return ( $lb->getServerType( $lb->getWriterIndex() ) !== 'sqlite' )
840 // Keep a separate connection to avoid contention and deadlocks;
841 // However, SQLite has the opposite behavior due to DB-level locking.
842 ? $lb->getConnectionRef( $index, [], $this->domain, $lb::CONN_TRX_AUTOCOMMIT )
843 // Jobs insertion will be defered until the PRESEND stage to reduce contention.
844 : $lb->getConnectionRef( $index, [], $this->domain );
845 }
846 }
847
848 /**
849 * @param IDatabase $db
850 * @return ScopedCallback
851 */
852 private function getScopedNoTrxFlag( IDatabase $db ) {
853 $autoTrx = $db->getFlag( DBO_TRX ); // get current setting
854 $db->clearFlag( DBO_TRX ); // make each query its own transaction
855
856 return new ScopedCallback( function () use ( $db, $autoTrx ) {
857 if ( $autoTrx ) {
858 $db->setFlag( DBO_TRX ); // restore old setting
859 }
860 } );
861 }
862
863 /**
864 * @param string $property
865 * @return string
866 */
867 private function getCacheKey( $property ) {
868 $cluster = is_string( $this->cluster ) ? $this->cluster : 'main';
869
870 return $this->cache->makeGlobalKey(
871 'jobqueue',
872 $this->domain,
873 $cluster,
874 $this->type,
875 $property
876 );
877 }
878
879 /**
880 * @param array|bool $params
881 * @return string
882 */
883 protected static function makeBlob( $params ) {
884 if ( $params !== false ) {
885 return serialize( $params );
886 } else {
887 return '';
888 }
889 }
890
891 /**
892 * @param string $blob
893 * @return bool|mixed
894 */
895 protected static function extractBlob( $blob ) {
896 if ( (string)$blob !== '' ) {
897 return unserialize( $blob );
898 } else {
899 return false;
900 }
901 }
902
903 /**
904 * @param DBError $e
905 * @throws JobQueueError
906 */
907 protected function throwDBException( DBError $e ) {
908 throw new JobQueueError( get_class( $e ) . ": " . $e->getMessage() );
909 }
910
911 /**
912 * Return the list of job fields that should be selected.
913 * @since 1.23
914 * @return array
915 */
916 public static function selectFields() {
917 return [
918 'job_id',
919 'job_cmd',
920 'job_namespace',
921 'job_title',
922 'job_timestamp',
923 'job_params',
924 'job_random',
925 'job_attempts',
926 'job_token',
927 'job_token_timestamp',
928 'job_sha1',
929 ];
930 }
931 }