Merge "Add extmetadata to the ForeignAPIFile iiprops"
[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 return true;
548 }
549
550 /**
551 * @see JobQueue::doWaitForBackups()
552 * @return void
553 */
554 protected function doWaitForBackups() {
555 wfWaitForSlaves();
556 }
557
558 /**
559 * @return Array
560 */
561 protected function doGetPeriodicTasks() {
562 return array(
563 'recycleAndDeleteStaleJobs' => array(
564 'callback' => array( $this, 'recycleAndDeleteStaleJobs' ),
565 'period' => ceil( $this->claimTTL / 2 )
566 )
567 );
568 }
569
570 /**
571 * @return void
572 */
573 protected function doFlushCaches() {
574 foreach ( array( 'empty', 'size', 'acquiredcount' ) as $type ) {
575 $this->cache->delete( $this->getCacheKey( $type ) );
576 }
577 }
578
579 /**
580 * @see JobQueue::getAllQueuedJobs()
581 * @return Iterator
582 */
583 public function getAllQueuedJobs() {
584 $dbr = $this->getSlaveDB();
585 try {
586 return new MappedIterator(
587 $dbr->select( 'job', '*',
588 array( 'job_cmd' => $this->getType(), 'job_token' => '' ) ),
589 function( $row ) use ( $dbr ) {
590 $job = Job::factory(
591 $row->job_cmd,
592 Title::makeTitle( $row->job_namespace, $row->job_title ),
593 strlen( $row->job_params ) ? unserialize( $row->job_params ) : false,
594 $row->job_id
595 );
596 $job->metadata['id'] = $row->job_id;
597 $job->id = $row->job_id; // XXX: work around broken subclasses
598 return $job;
599 }
600 );
601 } catch ( DBError $e ) {
602 $this->throwDBException( $e );
603 }
604 }
605
606 public function getCoalesceLocationInternal() {
607 return $this->cluster
608 ? "DBCluster:{$this->cluster}:{$this->wiki}"
609 : "LBFactory:{$this->wiki}";
610 }
611
612 protected function doGetSiblingQueuesWithJobs( array $types ) {
613 $dbr = $this->getSlaveDB();
614 $res = $dbr->select( 'job', 'DISTINCT job_cmd',
615 array( 'job_cmd' => $types ), __METHOD__ );
616
617 $types = array();
618 foreach ( $res as $row ) {
619 $types[] = $row->job_cmd;
620 }
621 return $types;
622 }
623
624 protected function doGetSiblingQueueSizes( array $types ) {
625 $dbr = $this->getSlaveDB();
626 $res = $dbr->select( 'job', array( 'job_cmd', 'COUNT(*) AS count' ),
627 array( 'job_cmd' => $types ), __METHOD__, array( 'GROUP BY' => 'job_cmd' ) );
628
629 $sizes = array();
630 foreach ( $res as $row ) {
631 $sizes[$row->job_cmd] = (int)$row->count;
632 }
633 return $sizes;
634 }
635
636 /**
637 * Recycle or destroy any jobs that have been claimed for too long
638 *
639 * @return integer Number of jobs recycled/deleted
640 */
641 public function recycleAndDeleteStaleJobs() {
642 $now = time();
643 $count = 0; // affected rows
644 $dbw = $this->getMasterDB();
645
646 try {
647 if ( !$dbw->lock( "jobqueue-recycle-{$this->type}", __METHOD__, 1 ) ) {
648 return $count; // already in progress
649 }
650
651 // Remove claims on jobs acquired for too long if enabled...
652 if ( $this->claimTTL > 0 ) {
653 $claimCutoff = $dbw->timestamp( $now - $this->claimTTL );
654 // Get the IDs of jobs that have be claimed but not finished after too long.
655 // These jobs can be recycled into the queue by expiring the claim. Selecting
656 // the IDs first means that the UPDATE can be done by primary key (less deadlocks).
657 $res = $dbw->select( 'job', 'job_id',
658 array(
659 'job_cmd' => $this->type,
660 "job_token != {$dbw->addQuotes( '' )}", // was acquired
661 "job_token_timestamp < {$dbw->addQuotes( $claimCutoff )}", // stale
662 "job_attempts < {$dbw->addQuotes( $this->maxTries )}" ), // retries left
663 __METHOD__
664 );
665 $ids = array_map(
666 function( $o ) {
667 return $o->job_id;
668 }, iterator_to_array( $res )
669 );
670 if ( count( $ids ) ) {
671 // Reset job_token for these jobs so that other runners will pick them up.
672 // Set the timestamp to the current time, as it is useful to now that the job
673 // was already tried before (the timestamp becomes the "released" time).
674 $dbw->update( 'job',
675 array(
676 'job_token' => '',
677 'job_token_timestamp' => $dbw->timestamp( $now ) ), // time of release
678 array(
679 'job_id' => $ids ),
680 __METHOD__
681 );
682 $count += $dbw->affectedRows();
683 JobQueue::incrStats( 'job-recycle', $this->type, $dbw->affectedRows() );
684 $this->cache->set( $this->getCacheKey( 'empty' ), 'false', self::CACHE_TTL_LONG );
685 }
686 }
687
688 // Just destroy any stale jobs...
689 $pruneCutoff = $dbw->timestamp( $now - self::MAX_AGE_PRUNE );
690 $conds = array(
691 'job_cmd' => $this->type,
692 "job_token != {$dbw->addQuotes( '' )}", // was acquired
693 "job_token_timestamp < {$dbw->addQuotes( $pruneCutoff )}" // stale
694 );
695 if ( $this->claimTTL > 0 ) { // only prune jobs attempted too many times...
696 $conds[] = "job_attempts >= {$dbw->addQuotes( $this->maxTries )}";
697 }
698 // Get the IDs of jobs that are considered stale and should be removed. Selecting
699 // the IDs first means that the UPDATE can be done by primary key (less deadlocks).
700 $res = $dbw->select( 'job', 'job_id', $conds, __METHOD__ );
701 $ids = array_map(
702 function( $o ) {
703 return $o->job_id;
704 }, iterator_to_array( $res )
705 );
706 if ( count( $ids ) ) {
707 $dbw->delete( 'job', array( 'job_id' => $ids ), __METHOD__ );
708 $count += $dbw->affectedRows();
709 JobQueue::incrStats( 'job-abandon', $this->type, $dbw->affectedRows() );
710 }
711
712 $dbw->unlock( "jobqueue-recycle-{$this->type}", __METHOD__ );
713 } catch ( DBError $e ) {
714 $this->throwDBException( $e );
715 }
716
717 return $count;
718 }
719
720 /**
721 * @param $job Job
722 * @return array
723 */
724 protected function insertFields( Job $job ) {
725 $dbw = $this->getMasterDB();
726 return array(
727 // Fields that describe the nature of the job
728 'job_cmd' => $job->getType(),
729 'job_namespace' => $job->getTitle()->getNamespace(),
730 'job_title' => $job->getTitle()->getDBkey(),
731 'job_params' => self::makeBlob( $job->getParams() ),
732 // Additional job metadata
733 'job_id' => $dbw->nextSequenceValue( 'job_job_id_seq' ),
734 'job_timestamp' => $dbw->timestamp(),
735 'job_sha1' => wfBaseConvert(
736 sha1( serialize( $job->getDeduplicationInfo() ) ),
737 16, 36, 31
738 ),
739 'job_random' => mt_rand( 0, self::MAX_JOB_RANDOM )
740 );
741 }
742
743 /**
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 * @return DBConnRef
756 */
757 protected function getMasterDB() {
758 try {
759 return $this->getDB( DB_MASTER );
760 } catch ( DBConnectionError $e ) {
761 throw new JobQueueConnectionError( "DBConnectionError:" . $e->getMessage() );
762 }
763 }
764
765 /**
766 * @param $index integer (DB_SLAVE/DB_MASTER)
767 * @return DBConnRef
768 */
769 protected function getDB( $index ) {
770 $lb = ( $this->cluster !== false )
771 ? wfGetLBFactory()->getExternalLB( $this->cluster, $this->wiki )
772 : wfGetLB( $this->wiki );
773 return $lb->getConnectionRef( $index, array(), $this->wiki );
774 }
775
776 /**
777 * @return string
778 */
779 private function getCacheKey( $property ) {
780 list( $db, $prefix ) = wfSplitWikiID( $this->wiki );
781 $cluster = is_string( $this->cluster ) ? $this->cluster : 'main';
782 return wfForeignMemcKey( $db, $prefix, 'jobqueue', $cluster, $this->type, $property );
783 }
784
785 /**
786 * @param $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 $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 }