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