Merge "Add ss_active_users in SiteStats::isSane"
[mediawiki.git] / includes / job / JobQueueDB.php
blob56da4f3d8d6bb32308b955e582451841b6513d8d
1 <?php
2 /**
3 * Database-backed job queue code.
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.
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.
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
20 * @file
21 * @author Aaron Schulz
24 /**
25 * Class to handle job queues stored in the DB
27 * @ingroup JobQueue
28 * @since 1.21
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
37 /** @var BagOStuff */
38 protected $cache;
40 protected $cluster = false; // string; name of an external DB cluster
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
50 protected function __construct( array $params ) {
51 global $wgMemc;
53 parent::__construct( $params );
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;
60 protected function supportedOrders() {
61 return array( 'random', 'timestamp', 'fifo' );
64 protected function optimalOrder() {
65 return 'random';
68 /**
69 * @see JobQueue::doIsEmpty()
70 * @return bool
72 protected function doIsEmpty() {
73 $key = $this->getCacheKey( 'empty' );
75 $isEmpty = $this->cache->get( $key );
76 if ( $isEmpty === 'true' ) {
77 return true;
78 } elseif ( $isEmpty === 'false' ) {
79 return false;
82 list( $dbr, $scope ) = $this->getSlaveDB();
83 $found = $dbr->selectField( // unclaimed job
84 'job', '1', array( 'job_cmd' => $this->type, 'job_token' => '' ), __METHOD__
86 $this->cache->add( $key, $found ? 'false' : 'true', self::CACHE_TTL_LONG );
88 return !$found;
91 /**
92 * @see JobQueue::doGetSize()
93 * @return integer
95 protected function doGetSize() {
96 $key = $this->getCacheKey( 'size' );
98 $size = $this->cache->get( $key );
99 if ( is_int( $size ) ) {
100 return $size;
103 list( $dbr, $scope ) = $this->getSlaveDB();
104 $size = (int)$dbr->selectField( 'job', 'COUNT(*)',
105 array( 'job_cmd' => $this->type, 'job_token' => '' ),
106 __METHOD__
108 $this->cache->set( $key, $size, self::CACHE_TTL_SHORT );
110 return $size;
114 * @see JobQueue::doGetAcquiredCount()
115 * @return integer
117 protected function doGetAcquiredCount() {
118 if ( $this->claimTTL <= 0 ) {
119 return 0; // no acknowledgements
122 $key = $this->getCacheKey( 'acquiredcount' );
124 $count = $this->cache->get( $key );
125 if ( is_int( $count ) ) {
126 return $count;
129 list( $dbr, $scope ) = $this->getSlaveDB();
130 $count = (int)$dbr->selectField( 'job', 'COUNT(*)',
131 array( 'job_cmd' => $this->type, "job_token != {$dbr->addQuotes( '' )}" ),
132 __METHOD__
134 $this->cache->set( $key, $count, self::CACHE_TTL_SHORT );
136 return $count;
140 * @see JobQueue::doGetAbandonedCount()
141 * @return integer
142 * @throws MWException
144 protected function doGetAbandonedCount() {
145 global $wgMemc;
147 if ( $this->claimTTL <= 0 ) {
148 return 0; // no acknowledgements
151 $key = $this->getCacheKey( 'abandonedcount' );
153 $count = $wgMemc->get( $key );
154 if ( is_int( $count ) ) {
155 return $count;
158 list( $dbr, $scope ) = $this->getSlaveDB();
159 $count = (int)$dbr->selectField( 'job', 'COUNT(*)',
160 array(
161 'job_cmd' => $this->type,
162 "job_token != {$dbr->addQuotes( '' )}",
163 "job_attempts >= " . $dbr->addQuotes( $this->maxTries )
165 __METHOD__
167 $wgMemc->set( $key, $count, self::CACHE_TTL_SHORT );
169 return $count;
173 * @see JobQueue::doBatchPush()
174 * @param array $jobs
175 * @param $flags
176 * @throws DBError|Exception
177 * @return bool
179 protected function doBatchPush( array $jobs, $flags ) {
180 list( $dbw, $scope ) = $this->getMasterDB();
182 $that = $this;
183 $method = __METHOD__;
184 $dbw->onTransactionIdle(
185 function() use ( $dbw, $that, $jobs, $flags, $method, $scope ) {
186 $that->doBatchPushInternal( $dbw, $jobs, $flags, $method );
190 return true;
194 * This function should *not* be called outside of JobQueueDB
196 * @param DatabaseBase $dbw
197 * @param array $jobs
198 * @param int $flags
199 * @param string $method
200 * @return boolean
201 * @throws type
203 public function doBatchPushInternal( DatabaseBase $dbw, array $jobs, $flags, $method ) {
204 if ( !count( $jobs ) ) {
205 return true;
208 $rowSet = array(); // (sha1 => job) map for jobs that are de-duplicated
209 $rowList = array(); // list of jobs for jobs that are 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;
219 if ( $flags & self::QOS_ATOMIC ) {
220 $dbw->begin( $method ); // wrap all the job additions in one transaction
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
231 $method
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
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 );
244 JobQueue::incrStats( 'job-insert', $this->type, count( $rows ) );
245 JobQueue::incrStats( 'job-insert-duplicate', $this->type,
246 count( $rowSet ) + count( $rowList ) - count( $rows ) );
247 } catch ( DBError $e ) {
248 if ( $flags & self::QOS_ATOMIC ) {
249 $dbw->rollback( $method );
251 throw $e;
253 if ( $flags & self::QOS_ATOMIC ) {
254 $dbw->commit( $method );
257 $this->cache->set( $this->getCacheKey( 'empty' ), 'false', JobQueueDB::CACHE_TTL_LONG );
259 return true;
263 * @see JobQueue::doPop()
264 * @return Job|bool
266 protected function doPop() {
267 if ( $this->cache->get( $this->getCacheKey( 'empty' ) ) === 'true' ) {
268 return false; // queue is empty
271 list( $dbw, $scope ) = $this->getMasterDB();
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 } );
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 );
290 // Check if we found a row to reserve...
291 if ( !$row ) {
292 $this->cache->set( $this->getCacheKey( 'empty' ), 'true', self::CACHE_TTL_LONG );
293 break; // nothing to do
295 JobQueue::incrStats( 'job-pop', $this->type );
296 // Get the job object from the row...
297 $title = Title::makeTitleSafe( $row->job_namespace, $row->job_title );
298 if ( !$title ) {
299 $dbw->delete( 'job', array( 'job_id' => $row->job_id ), __METHOD__ );
300 wfDebug( "Row has invalid title '{$row->job_title}'." );
301 continue; // try again
303 $job = Job::factory( $row->job_cmd, $title,
304 self::extractBlob( $row->job_params ), $row->job_id );
305 $job->metadata['id'] = $row->job_id;
306 $job->id = $row->job_id; // XXX: work around broken subclasses
307 break; // done
308 } while ( true );
310 return $job;
314 * Reserve a row with a single UPDATE without holding row locks over RTTs...
316 * @param string $uuid 32 char hex string
317 * @param $rand integer Random unsigned integer (31 bits)
318 * @param bool $gte Search for job_random >= $random (otherwise job_random <= $random)
319 * @return Row|false
321 protected function claimRandom( $uuid, $rand, $gte ) {
322 list( $dbw, $scope ) = $this->getMasterDB();
323 // Check cache to see if the queue has <= OFFSET items
324 $tinyQueue = $this->cache->get( $this->getCacheKey( 'small' ) );
326 $row = false; // the row acquired
327 $invertedDirection = false; // whether one job_random direction was already scanned
328 // This uses a replication safe method for acquiring jobs. One could use UPDATE+LIMIT
329 // instead, but that either uses ORDER BY (in which case it deadlocks in MySQL) or is
330 // not replication safe. Due to http://bugs.mysql.com/bug.php?id=6980, subqueries cannot
331 // be used here with MySQL.
332 do {
333 if ( $tinyQueue ) { // queue has <= MAX_OFFSET rows
334 // For small queues, using OFFSET will overshoot and return no rows more often.
335 // Instead, this uses job_random to pick a row (possibly checking both directions).
336 $ineq = $gte ? '>=' : '<=';
337 $dir = $gte ? 'ASC' : 'DESC';
338 $row = $dbw->selectRow( 'job', '*', // find a random job
339 array(
340 'job_cmd' => $this->type,
341 'job_token' => '', // unclaimed
342 "job_random {$ineq} {$dbw->addQuotes( $rand )}" ),
343 __METHOD__,
344 array( 'ORDER BY' => "job_random {$dir}" )
346 if ( !$row && !$invertedDirection ) {
347 $gte = !$gte;
348 $invertedDirection = true;
349 continue; // try the other direction
351 } else { // table *may* have >= MAX_OFFSET rows
352 // Bug 42614: "ORDER BY job_random" with a job_random inequality causes high CPU
353 // in MySQL if there are many rows for some reason. This uses a small OFFSET
354 // instead of job_random for reducing excess claim retries.
355 $row = $dbw->selectRow( 'job', '*', // find a random job
356 array(
357 'job_cmd' => $this->type,
358 'job_token' => '', // unclaimed
360 __METHOD__,
361 array( 'OFFSET' => mt_rand( 0, self::MAX_OFFSET ) )
363 if ( !$row ) {
364 $tinyQueue = true; // we know the queue must have <= MAX_OFFSET rows
365 $this->cache->set( $this->getCacheKey( 'small' ), 1, 30 );
366 continue; // use job_random
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__
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
383 } else {
384 break; // nothing to do
386 } while ( !$row );
388 return $row;
392 * Reserve a row with a single UPDATE without holding row locks over RTTs...
394 * @param string $uuid 32 char hex string
395 * @return Row|false
397 protected function claimOldest( $uuid ) {
398 list( $dbw, $scope ) = $this->getMasterDB();
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__
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 ) ) .
433 __METHOD__
436 // Fetch any row that we just reserved...
437 if ( $dbw->affectedRows() ) {
438 $row = $dbw->selectRow( 'job', '*',
439 array( 'job_cmd' => $this->type, 'job_token' => $uuid ), __METHOD__
441 if ( !$row ) { // raced out by duplicate job removal
442 wfDebug( "Row deleted as duplicate by another process." );
444 } else {
445 break; // nothing to do
447 } while ( !$row );
449 return $row;
453 * @see JobQueue::doAck()
454 * @param Job $job
455 * @throws MWException
456 * @return Job|bool
458 protected function doAck( Job $job ) {
459 if ( !isset( $job->metadata['id'] ) ) {
460 throw new MWException( "Job of type '{$job->getType()}' has no ID." );
463 list( $dbw, $scope ) = $this->getMasterDB();
464 $dbw->commit( __METHOD__, 'flush' ); // flush existing transaction
465 $autoTrx = $dbw->getFlag( DBO_TRX ); // get current setting
466 $dbw->clearFlag( DBO_TRX ); // make each query its own transaction
467 $scopedReset = new ScopedCallback( function() use ( $dbw, $autoTrx ) {
468 $dbw->setFlag( $autoTrx ? DBO_TRX : 0 ); // restore old setting
469 } );
471 // Delete a row with a single DELETE without holding row locks over RTTs...
472 $dbw->delete( 'job',
473 array( 'job_cmd' => $this->type, 'job_id' => $job->metadata['id'] ), __METHOD__ );
475 return true;
479 * @see JobQueue::doDeduplicateRootJob()
480 * @param Job $job
481 * @throws MWException
482 * @return bool
484 protected function doDeduplicateRootJob( Job $job ) {
485 $params = $job->getParams();
486 if ( !isset( $params['rootJobSignature'] ) ) {
487 throw new MWException( "Cannot register root job; missing 'rootJobSignature'." );
488 } elseif ( !isset( $params['rootJobTimestamp'] ) ) {
489 throw new MWException( "Cannot register root job; missing 'rootJobTimestamp'." );
491 $key = $this->getRootJobCacheKey( $params['rootJobSignature'] );
492 // Callers should call batchInsert() and then this function so that if the insert
493 // fails, the de-duplication registration will be aborted. Since the insert is
494 // deferred till "transaction idle", do the same here, so that the ordering is
495 // maintained. Having only the de-duplication registration succeed would cause
496 // jobs to become no-ops without any actual jobs that made them redundant.
497 list( $dbw, $scope ) = $this->getMasterDB();
498 $cache = $this->cache;
499 $dbw->onTransactionIdle( function() use ( $cache, $params, $key, $scope ) {
500 $timestamp = $cache->get( $key ); // current last timestamp of this job
501 if ( $timestamp && $timestamp >= $params['rootJobTimestamp'] ) {
502 return true; // a newer version of this root job was enqueued
505 // Update the timestamp of the last root job started at the location...
506 return $cache->set( $key, $params['rootJobTimestamp'], JobQueueDB::ROOTJOB_TTL );
507 } );
509 return true;
513 * @see JobQueue::doDelete()
514 * @return bool
516 protected function doDelete() {
517 list( $dbw, $scope ) = $this->getMasterDB();
519 $dbw->delete( 'job', array( 'job_cmd' => $this->type ) );
520 return true;
524 * @see JobQueue::doWaitForBackups()
525 * @return void
527 protected function doWaitForBackups() {
528 wfWaitForSlaves();
532 * @return Array
534 protected function doGetPeriodicTasks() {
535 return array(
536 'recycleAndDeleteStaleJobs' => array(
537 'callback' => array( $this, 'recycleAndDeleteStaleJobs' ),
538 'period' => ceil( $this->claimTTL / 2 )
544 * @return void
546 protected function doFlushCaches() {
547 foreach ( array( 'empty', 'size', 'acquiredcount' ) as $type ) {
548 $this->cache->delete( $this->getCacheKey( $type ) );
553 * @see JobQueue::getAllQueuedJobs()
554 * @return Iterator
556 public function getAllQueuedJobs() {
557 list( $dbr, $scope ) = $this->getSlaveDB();
558 return new MappedIterator(
559 $dbr->select( 'job', '*', array( 'job_cmd' => $this->getType(), 'job_token' => '' ) ),
560 function( $row ) use ( $scope ) {
561 $job = Job::factory(
562 $row->job_cmd,
563 Title::makeTitle( $row->job_namespace, $row->job_title ),
564 strlen( $row->job_params ) ? unserialize( $row->job_params ) : false,
565 $row->job_id
567 $job->metadata['id'] = $row->job_id;
568 $job->id = $row->job_id; // XXX: work around broken subclasses
569 return $job;
575 * Recycle or destroy any jobs that have been claimed for too long
577 * @return integer Number of jobs recycled/deleted
579 public function recycleAndDeleteStaleJobs() {
580 $now = time();
581 list( $dbw, $scope ) = $this->getMasterDB();
582 $count = 0; // affected rows
584 if ( !$dbw->lock( "jobqueue-recycle-{$this->type}", __METHOD__, 1 ) ) {
585 return $count; // already in progress
588 // Remove claims on jobs acquired for too long if enabled...
589 if ( $this->claimTTL > 0 ) {
590 $claimCutoff = $dbw->timestamp( $now - $this->claimTTL );
591 // Get the IDs of jobs that have be claimed but not finished after too long.
592 // These jobs can be recycled into the queue by expiring the claim. Selecting
593 // the IDs first means that the UPDATE can be done by primary key (less deadlocks).
594 $res = $dbw->select( 'job', 'job_id',
595 array(
596 'job_cmd' => $this->type,
597 "job_token != {$dbw->addQuotes( '' )}", // was acquired
598 "job_token_timestamp < {$dbw->addQuotes( $claimCutoff )}", // stale
599 "job_attempts < {$dbw->addQuotes( $this->maxTries )}" ), // retries left
600 __METHOD__
602 $ids = array_map(
603 function( $o ) {
604 return $o->job_id;
605 }, iterator_to_array( $res )
607 if ( count( $ids ) ) {
608 // Reset job_token for these jobs so that other runners will pick them up.
609 // Set the timestamp to the current time, as it is useful to now that the job
610 // was already tried before (the timestamp becomes the "released" time).
611 $dbw->update( 'job',
612 array(
613 'job_token' => '',
614 'job_token_timestamp' => $dbw->timestamp( $now ) ), // time of release
615 array(
616 'job_id' => $ids ),
617 __METHOD__
619 $count += $dbw->affectedRows();
620 JobQueue::incrStats( 'job-recycle', $this->type, $dbw->affectedRows() );
621 $this->cache->set( $this->getCacheKey( 'empty' ), 'false', self::CACHE_TTL_LONG );
625 // Just destroy any stale jobs...
626 $pruneCutoff = $dbw->timestamp( $now - self::MAX_AGE_PRUNE );
627 $conds = array(
628 'job_cmd' => $this->type,
629 "job_token != {$dbw->addQuotes( '' )}", // was acquired
630 "job_token_timestamp < {$dbw->addQuotes( $pruneCutoff )}" // stale
632 if ( $this->claimTTL > 0 ) { // only prune jobs attempted too many times...
633 $conds[] = "job_attempts >= {$dbw->addQuotes( $this->maxTries )}";
635 // Get the IDs of jobs that are considered stale and should be removed. Selecting
636 // the IDs first means that the UPDATE can be done by primary key (less deadlocks).
637 $res = $dbw->select( 'job', 'job_id', $conds, __METHOD__ );
638 $ids = array_map(
639 function( $o ) {
640 return $o->job_id;
641 }, iterator_to_array( $res )
643 if ( count( $ids ) ) {
644 $dbw->delete( 'job', array( 'job_id' => $ids ), __METHOD__ );
645 $count += $dbw->affectedRows();
646 JobQueue::incrStats( 'job-abandon', $this->type, $dbw->affectedRows() );
649 $dbw->unlock( "jobqueue-recycle-{$this->type}", __METHOD__ );
651 return $count;
655 * @return Array (DatabaseBase, ScopedCallback)
657 protected function getSlaveDB() {
658 return $this->getDB( DB_SLAVE );
662 * @return Array (DatabaseBase, ScopedCallback)
664 protected function getMasterDB() {
665 return $this->getDB( DB_MASTER );
669 * @param $index integer (DB_SLAVE/DB_MASTER)
670 * @return Array (DatabaseBase, ScopedCallback)
672 protected function getDB( $index ) {
673 $lb = ( $this->cluster !== false )
674 ? wfGetLBFactory()->getExternalLB( $this->cluster, $this->wiki )
675 : wfGetLB( $this->wiki );
676 $conn = $lb->getConnection( $index, array(), $this->wiki );
677 return array(
678 $conn,
679 new ScopedCallback( function() use ( $lb, $conn ) {
680 $lb->reuseConnection( $conn );
686 * @param $job Job
687 * @return array
689 protected function insertFields( Job $job ) {
690 list( $dbw, $scope ) = $this->getMasterDB();
691 return array(
692 // Fields that describe the nature of the job
693 'job_cmd' => $job->getType(),
694 'job_namespace' => $job->getTitle()->getNamespace(),
695 'job_title' => $job->getTitle()->getDBkey(),
696 'job_params' => self::makeBlob( $job->getParams() ),
697 // Additional job metadata
698 'job_id' => $dbw->nextSequenceValue( 'job_job_id_seq' ),
699 'job_timestamp' => $dbw->timestamp(),
700 'job_sha1' => wfBaseConvert(
701 sha1( serialize( $job->getDeduplicationInfo() ) ),
702 16, 36, 31
704 'job_random' => mt_rand( 0, self::MAX_JOB_RANDOM )
709 * @return string
711 private function getCacheKey( $property ) {
712 list( $db, $prefix ) = wfSplitWikiID( $this->wiki );
713 $cluster = is_string( $this->cluster ) ? $this->cluster : 'main';
714 return wfForeignMemcKey( $db, $prefix, 'jobqueue', $cluster, $this->type, $property );
718 * @param $params
719 * @return string
721 protected static function makeBlob( $params ) {
722 if ( $params !== false ) {
723 return serialize( $params );
724 } else {
725 return '';
730 * @param $blob
731 * @return bool|mixed
733 protected static function extractBlob( $blob ) {
734 if ( (string)$blob !== '' ) {
735 return unserialize( $blob );
736 } else {
737 return false;