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