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