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