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