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