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