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