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