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