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