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