3 * Object caching using a SQL database.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
25 * Class to store objects in the database
29 class SqlBagOStuff
extends BagOStuff
{
31 protected $serverInfos;
33 protected $serverNames;
35 protected $numServers;
37 protected $lastExpireAll = 0;
39 protected $purgePeriod = 100;
41 protected $shards = 1;
43 protected $tableName = 'objectcache';
45 protected $slaveOnly = false;
47 protected $syncTimeout = 3;
51 /** @var array UNIX timestamps */
52 protected $connFailureTimes = array();
53 /** @var array Exceptions */
54 protected $connFailureErrors = array();
57 * Constructor. Parameters are:
58 * - server: A server info structure in the format required by each
59 * element in $wgDBServers.
61 * - servers: An array of server info structures describing a set of
62 * database servers to distribute keys to. If this is
63 * specified, the "server" option will be ignored.
65 * - purgePeriod: The average number of object cache requests in between
66 * garbage collection operations, where expired entries
67 * are removed from the database. Or in other words, the
68 * reciprocal of the probability of purging on any given
69 * request. If this is set to zero, purging will never be
72 * - tableName: The table name to use, default is "objectcache".
74 * - shards: The number of tables to use for data storage on each server.
75 * If this is more than 1, table names will be formed in the style
76 * objectcacheNNN where NNN is the shard index, between 0 and
77 * shards-1. The number of digits will be the minimum number
78 * required to hold the largest shard index. Data will be
79 * distributed across all tables by key hash. This is for
80 * MySQL bugs 61735 and 61736.
81 * - slaveOnly: Whether to only use slave DBs and avoid triggering
82 * garbage collection logic of expired items. This only
83 * makes sense if the primary DB is used and only if get()
84 * calls will be used. This is used by ReplicatedBagOStuff.
85 * - syncTimeout: Max seconds to wait for slaves to catch up for WRITE_SYNC.
87 * @param array $params
89 public function __construct( $params ) {
90 parent
::__construct( $params );
91 if ( isset( $params['servers'] ) ) {
92 $this->serverInfos
= $params['servers'];
93 $this->numServers
= count( $this->serverInfos
);
94 $this->serverNames
= array();
95 foreach ( $this->serverInfos
as $i => $info ) {
96 $this->serverNames
[$i] = isset( $info['host'] ) ?
$info['host'] : "#$i";
98 } elseif ( isset( $params['server'] ) ) {
99 $this->serverInfos
= array( $params['server'] );
100 $this->numServers
= count( $this->serverInfos
);
102 $this->serverInfos
= false;
103 $this->numServers
= 1;
105 if ( isset( $params['purgePeriod'] ) ) {
106 $this->purgePeriod
= intval( $params['purgePeriod'] );
108 if ( isset( $params['tableName'] ) ) {
109 $this->tableName
= $params['tableName'];
111 if ( isset( $params['shards'] ) ) {
112 $this->shards
= intval( $params['shards'] );
114 if ( isset( $params['syncTimeout'] ) ) {
115 $this->syncTimeout
= $params['syncTimeout'];
117 $this->slaveOnly
= !empty( $params['slaveOnly'] );
121 * Get a connection to the specified database
123 * @param int $serverIndex
125 * @throws MWException
127 protected function getDB( $serverIndex ) {
128 if ( !isset( $this->conns
[$serverIndex] ) ) {
129 if ( $serverIndex >= $this->numServers
) {
130 throw new MWException( __METHOD__
. ": Invalid server index \"$serverIndex\"" );
133 # Don't keep timing out trying to connect for each call if the DB is down
134 if ( isset( $this->connFailureErrors
[$serverIndex] )
135 && ( time() - $this->connFailureTimes
[$serverIndex] ) < 60
137 throw $this->connFailureErrors
[$serverIndex];
140 # If server connection info was given, use that
141 if ( $this->serverInfos
) {
142 $info = $this->serverInfos
[$serverIndex];
143 $type = isset( $info['type'] ) ?
$info['type'] : 'mysql';
144 $host = isset( $info['host'] ) ?
$info['host'] : '[unknown]';
145 $this->logger
->debug( __CLASS__
. ": connecting to $host" );
146 // Use a blank trx profiler to ignore expections as this is a cache
147 $info['trxProfiler'] = new TransactionProfiler();
148 $db = DatabaseBase
::factory( $type, $info );
149 $db->clearFlag( DBO_TRX
);
151 // We must keep a separate connection to MySQL in order to avoid deadlocks
152 // However, SQLite has an opposite behavior. And PostgreSQL needs to know
153 // if we are in transaction or not (@TODO: find some work-around).
154 $index = $this->slaveOnly ? DB_SLAVE
: DB_MASTER
;
155 if ( wfGetDB( $index )->getType() == 'mysql' ) {
156 $lb = wfGetLBFactory()->newMainLB();
157 $db = $lb->getConnection( $index );
158 $db->clearFlag( DBO_TRX
); // auto-commit mode
160 $db = wfGetDB( $index );
163 $this->logger
->debug( sprintf( "Connection %s will be used for SqlBagOStuff", $db ) );
164 $this->conns
[$serverIndex] = $db;
167 return $this->conns
[$serverIndex];
171 * Get the server index and table name for a given key
173 * @return array Server index and table name
175 protected function getTableByKey( $key ) {
176 if ( $this->shards
> 1 ) {
177 $hash = hexdec( substr( md5( $key ), 0, 8 ) ) & 0x7fffffff;
178 $tableIndex = $hash %
$this->shards
;
182 if ( $this->numServers
> 1 ) {
183 $sortedServers = $this->serverNames
;
184 ArrayUtils
::consistentHashSort( $sortedServers, $key );
185 reset( $sortedServers );
186 $serverIndex = key( $sortedServers );
190 return array( $serverIndex, $this->getTableNameByShard( $tableIndex ) );
194 * Get the table name for a given shard index
198 protected function getTableNameByShard( $index ) {
199 if ( $this->shards
> 1 ) {
200 $decimals = strlen( $this->shards
- 1 );
201 return $this->tableName
.
202 sprintf( "%0{$decimals}d", $index );
204 return $this->tableName
;
208 protected function doGet( $key, $flags = 0 ) {
211 return $this->getWithToken( $key, $casToken, $flags );
214 protected function getWithToken( $key, &$casToken, $flags = 0 ) {
215 $values = $this->getMulti( array( $key ) );
216 if ( array_key_exists( $key, $values ) ) {
217 $casToken = $values[$key];
218 return $values[$key];
223 public function getMulti( array $keys, $flags = 0 ) {
224 $values = array(); // array of (key => value)
226 $keysByTable = array();
227 foreach ( $keys as $key ) {
228 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
229 $keysByTable[$serverIndex][$tableName][] = $key;
232 $this->garbageCollect(); // expire old entries if any
235 foreach ( $keysByTable as $serverIndex => $serverKeys ) {
237 $db = $this->getDB( $serverIndex );
238 foreach ( $serverKeys as $tableName => $tableKeys ) {
239 $res = $db->select( $tableName,
240 array( 'keyname', 'value', 'exptime' ),
241 array( 'keyname' => $tableKeys ),
243 // Approximate write-on-the-fly BagOStuff API via blocking.
244 // This approximation fails if a ROLLBACK happens (which is rare).
245 // We do not want to flush the TRX as that can break callers.
246 $db->trxLevel() ?
array( 'LOCK IN SHARE MODE' ) : array()
248 if ( $res === false ) {
251 foreach ( $res as $row ) {
252 $row->serverIndex
= $serverIndex;
253 $row->tableName
= $tableName;
254 $dataRows[$row->keyname
] = $row;
257 } catch ( DBError
$e ) {
258 $this->handleReadError( $e, $serverIndex );
262 foreach ( $keys as $key ) {
263 if ( isset( $dataRows[$key] ) ) { // HIT?
264 $row = $dataRows[$key];
265 $this->debug( "get: retrieved data; expiry time is " . $row->exptime
);
267 $db = $this->getDB( $row->serverIndex
);
268 if ( $this->isExpired( $db, $row->exptime
) ) { // MISS
269 $this->debug( "get: key has expired" );
271 $values[$key] = $this->unserialize( $db->decodeBlob( $row->value
) );
273 } catch ( DBQueryError
$e ) {
274 $this->handleWriteError( $e, $row->serverIndex
);
277 $this->debug( 'get: no matching rows' );
284 public function setMulti( array $data, $expiry = 0 ) {
285 $keysByTable = array();
286 foreach ( $data as $key => $value ) {
287 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
288 $keysByTable[$serverIndex][$tableName][] = $key;
291 $this->garbageCollect(); // expire old entries if any
294 $exptime = (int)$expiry;
295 foreach ( $keysByTable as $serverIndex => $serverKeys ) {
297 $db = $this->getDB( $serverIndex );
298 } catch ( DBError
$e ) {
299 $this->handleWriteError( $e, $serverIndex );
304 if ( $exptime < 0 ) {
308 if ( $exptime == 0 ) {
309 $encExpiry = $this->getMaxDateTime( $db );
311 $exptime = $this->convertExpiry( $exptime );
312 $encExpiry = $db->timestamp( $exptime );
314 foreach ( $serverKeys as $tableName => $tableKeys ) {
316 foreach ( $tableKeys as $key ) {
319 'value' => $db->encodeBlob( $this->serialize( $data[$key] ) ),
320 'exptime' => $encExpiry,
331 } catch ( DBError
$e ) {
332 $this->handleWriteError( $e, $serverIndex );
343 public function set( $key, $value, $exptime = 0, $flags = 0 ) {
344 $ok = $this->setMulti( array( $key => $value ), $exptime );
345 if ( ( $flags & self
::WRITE_SYNC
) == self
::WRITE_SYNC
) {
346 $ok = $ok && $this->waitForSlaves();
352 protected function cas( $casToken, $key, $value, $exptime = 0 ) {
353 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
355 $db = $this->getDB( $serverIndex );
356 $exptime = intval( $exptime );
358 if ( $exptime < 0 ) {
362 if ( $exptime == 0 ) {
363 $encExpiry = $this->getMaxDateTime( $db );
365 $exptime = $this->convertExpiry( $exptime );
366 $encExpiry = $db->timestamp( $exptime );
368 // (bug 24425) use a replace if the db supports it instead of
369 // delete/insert to avoid clashes with conflicting keynames
374 'value' => $db->encodeBlob( $this->serialize( $value ) ),
375 'exptime' => $encExpiry
379 'value' => $db->encodeBlob( $this->serialize( $casToken ) )
383 } catch ( DBQueryError
$e ) {
384 $this->handleWriteError( $e, $serverIndex );
389 return (bool)$db->affectedRows();
392 public function delete( $key ) {
393 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
395 $db = $this->getDB( $serverIndex );
398 array( 'keyname' => $key ),
400 } catch ( DBError
$e ) {
401 $this->handleWriteError( $e, $serverIndex );
408 public function incr( $key, $step = 1 ) {
409 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
411 $db = $this->getDB( $serverIndex );
412 $step = intval( $step );
413 $row = $db->selectRow(
415 array( 'value', 'exptime' ),
416 array( 'keyname' => $key ),
418 array( 'FOR UPDATE' ) );
419 if ( $row === false ) {
424 $db->delete( $tableName, array( 'keyname' => $key ), __METHOD__
);
425 if ( $this->isExpired( $db, $row->exptime
) ) {
426 // Expired, do not reinsert
431 $oldValue = intval( $this->unserialize( $db->decodeBlob( $row->value
) ) );
432 $newValue = $oldValue +
$step;
433 $db->insert( $tableName,
436 'value' => $db->encodeBlob( $this->serialize( $newValue ) ),
437 'exptime' => $row->exptime
438 ), __METHOD__
, 'IGNORE' );
440 if ( $db->affectedRows() == 0 ) {
441 // Race condition. See bug 28611
444 } catch ( DBError
$e ) {
445 $this->handleWriteError( $e, $serverIndex );
452 public function merge( $key, $callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
453 if ( !is_callable( $callback ) ) {
454 throw new Exception( "Got invalid callback." );
457 $ok = $this->mergeViaCas( $key, $callback, $exptime, $attempts );
458 if ( ( $flags & self
::WRITE_SYNC
) == self
::WRITE_SYNC
) {
459 $ok = $ok && $this->waitForSlaves();
466 * @param IDatabase $db
467 * @param string $exptime
470 protected function isExpired( $db, $exptime ) {
471 return $exptime != $this->getMaxDateTime( $db ) && wfTimestamp( TS_UNIX
, $exptime ) < time();
475 * @param IDatabase $db
478 protected function getMaxDateTime( $db ) {
479 if ( time() > 0x7fffffff ) {
480 return $db->timestamp( 1 << 62 );
482 return $db->timestamp( 0x7fffffff );
486 protected function garbageCollect() {
487 if ( !$this->purgePeriod ||
$this->slaveOnly
) {
491 // Only purge on one in every $this->purgePeriod requests.
492 if ( $this->purgePeriod
!== 1 && mt_rand( 0, $this->purgePeriod
- 1 ) ) {
496 // Avoid repeating the delete within a few seconds
497 if ( $now > ( $this->lastExpireAll +
1 ) ) {
498 $this->lastExpireAll
= $now;
503 public function expireAll() {
504 $this->deleteObjectsExpiringBefore( wfTimestampNow() );
508 * Delete objects from the database which expire before a certain date.
509 * @param string $timestamp
510 * @param bool|callable $progressCallback
513 public function deleteObjectsExpiringBefore( $timestamp, $progressCallback = false ) {
514 for ( $serverIndex = 0; $serverIndex < $this->numServers
; $serverIndex++
) {
516 $db = $this->getDB( $serverIndex );
517 $dbTimestamp = $db->timestamp( $timestamp );
518 $totalSeconds = false;
519 $baseConds = array( 'exptime < ' . $db->addQuotes( $dbTimestamp ) );
520 for ( $i = 0; $i < $this->shards
; $i++
) {
524 if ( $maxExpTime !== false ) {
525 $conds[] = 'exptime > ' . $db->addQuotes( $maxExpTime );
528 $this->getTableNameByShard( $i ),
529 array( 'keyname', 'exptime' ),
532 array( 'LIMIT' => 100, 'ORDER BY' => 'exptime' ) );
533 if ( $rows === false ||
!$rows->numRows() ) {
537 $row = $rows->current();
538 $minExpTime = $row->exptime
;
539 if ( $totalSeconds === false ) {
540 $totalSeconds = wfTimestamp( TS_UNIX
, $timestamp )
541 - wfTimestamp( TS_UNIX
, $minExpTime );
543 foreach ( $rows as $row ) {
544 $keys[] = $row->keyname
;
545 $maxExpTime = $row->exptime
;
549 $this->getTableNameByShard( $i ),
551 'exptime >= ' . $db->addQuotes( $minExpTime ),
552 'exptime < ' . $db->addQuotes( $dbTimestamp ),
557 if ( $progressCallback ) {
558 if ( intval( $totalSeconds ) === 0 ) {
561 $remainingSeconds = wfTimestamp( TS_UNIX
, $timestamp )
562 - wfTimestamp( TS_UNIX
, $maxExpTime );
563 if ( $remainingSeconds > $totalSeconds ) {
564 $totalSeconds = $remainingSeconds;
566 $processedSeconds = $totalSeconds - $remainingSeconds;
567 $percent = ( $i +
$processedSeconds / $totalSeconds )
568 / $this->shards
* 100;
570 $percent = ( $percent / $this->numServers
)
571 +
( $serverIndex / $this->numServers
* 100 );
572 call_user_func( $progressCallback, $percent );
576 } catch ( DBError
$e ) {
577 $this->handleWriteError( $e, $serverIndex );
585 * Delete content of shard tables in every server.
586 * Return true if the operation is successful, false otherwise.
589 public function deleteAll() {
590 for ( $serverIndex = 0; $serverIndex < $this->numServers
; $serverIndex++
) {
592 $db = $this->getDB( $serverIndex );
593 for ( $i = 0; $i < $this->shards
; $i++
) {
594 $db->delete( $this->getTableNameByShard( $i ), '*', __METHOD__
);
596 } catch ( DBError
$e ) {
597 $this->handleWriteError( $e, $serverIndex );
605 * Serialize an object and, if possible, compress the representation.
606 * On typical message and page data, this can provide a 3X decrease
607 * in storage requirements.
612 protected function serialize( &$data ) {
613 $serial = serialize( $data );
615 if ( function_exists( 'gzdeflate' ) ) {
616 return gzdeflate( $serial );
623 * Unserialize and, if necessary, decompress an object.
624 * @param string $serial
627 protected function unserialize( $serial ) {
628 if ( function_exists( 'gzinflate' ) ) {
629 MediaWiki\
suppressWarnings();
630 $decomp = gzinflate( $serial );
631 MediaWiki\restoreWarnings
();
633 if ( false !== $decomp ) {
638 $ret = unserialize( $serial );
644 * Handle a DBError which occurred during a read operation.
646 * @param DBError $exception
647 * @param int $serverIndex
649 protected function handleReadError( DBError
$exception, $serverIndex ) {
650 if ( $exception instanceof DBConnectionError
) {
651 $this->markServerDown( $exception, $serverIndex );
653 $this->logger
->error( "DBError: {$exception->getMessage()}" );
654 if ( $exception instanceof DBConnectionError
) {
655 $this->setLastError( BagOStuff
::ERR_UNREACHABLE
);
656 $this->logger
->debug( __METHOD__
. ": ignoring connection error" );
658 $this->setLastError( BagOStuff
::ERR_UNEXPECTED
);
659 $this->logger
->debug( __METHOD__
. ": ignoring query error" );
664 * Handle a DBQueryError which occurred during a write operation.
666 * @param DBError $exception
667 * @param int $serverIndex
669 protected function handleWriteError( DBError
$exception, $serverIndex ) {
670 if ( $exception instanceof DBConnectionError
) {
671 $this->markServerDown( $exception, $serverIndex );
673 if ( $exception->db
&& $exception->db
->wasReadOnlyError() ) {
674 if ( $exception->db
->trxLevel() ) {
676 $exception->db
->rollback( __METHOD__
);
677 } catch ( DBError
$e ) {
682 $this->logger
->error( "DBError: {$exception->getMessage()}" );
683 if ( $exception instanceof DBConnectionError
) {
684 $this->setLastError( BagOStuff
::ERR_UNREACHABLE
);
685 $this->logger
->debug( __METHOD__
. ": ignoring connection error" );
687 $this->setLastError( BagOStuff
::ERR_UNEXPECTED
);
688 $this->logger
->debug( __METHOD__
. ": ignoring query error" );
693 * Mark a server down due to a DBConnectionError exception
695 * @param DBError $exception
696 * @param int $serverIndex
698 protected function markServerDown( $exception, $serverIndex ) {
699 unset( $this->conns
[$serverIndex] ); // bug T103435
701 if ( isset( $this->connFailureTimes
[$serverIndex] ) ) {
702 if ( time() - $this->connFailureTimes
[$serverIndex] >= 60 ) {
703 unset( $this->connFailureTimes
[$serverIndex] );
704 unset( $this->connFailureErrors
[$serverIndex] );
706 $this->logger
->debug( __METHOD__
. ": Server #$serverIndex already down" );
711 $this->logger
->info( __METHOD__
. ": Server #$serverIndex down until " . ( $now +
60 ) );
712 $this->connFailureTimes
[$serverIndex] = $now;
713 $this->connFailureErrors
[$serverIndex] = $exception;
717 * Create shard tables. For use from eval.php.
719 public function createTables() {
720 for ( $serverIndex = 0; $serverIndex < $this->numServers
; $serverIndex++
) {
721 $db = $this->getDB( $serverIndex );
722 if ( $db->getType() !== 'mysql' ) {
723 throw new MWException( __METHOD__
. ' is not supported on this DB server' );
726 for ( $i = 0; $i < $this->shards
; $i++
) {
728 'CREATE TABLE ' . $db->tableName( $this->getTableNameByShard( $i ) ) .
729 ' LIKE ' . $db->tableName( 'objectcache' ),
735 protected function waitForSlaves() {
736 if ( !$this->serverInfos
) {
737 // Main LB is used; wait for any slaves to catch up
739 wfGetLBFactory()->waitForReplication( array( 'wiki' => wfWikiID() ) );
741 } catch ( DBReplicationWaitError
$e ) {
745 // Custom DB server list; probably doesn't use replication