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
24 use Wikimedia\Rdbms\Database
;
25 use Wikimedia\Rdbms\IDatabase
;
26 use \MediaWiki\MediaWikiServices
;
27 use \Wikimedia\WaitConditionLoop
;
28 use \Wikimedia\Rdbms\TransactionProfiler
;
29 use Wikimedia\Rdbms\LoadBalancer
;
32 * Class to store objects in the database
36 class SqlBagOStuff
extends BagOStuff
{
37 /** @var array[] (server index => server config) */
38 protected $serverInfos;
39 /** @var string[] (server index => tag/host name) */
40 protected $serverTags;
42 protected $numServers;
44 protected $lastExpireAll = 0;
46 protected $purgePeriod = 100;
48 protected $shards = 1;
50 protected $tableName = 'objectcache';
52 protected $replicaOnly = false;
54 protected $syncTimeout = 3;
56 /** @var LoadBalancer|null */
57 protected $separateMainLB;
60 /** @var array UNIX timestamps */
61 protected $connFailureTimes = [];
62 /** @var array Exceptions */
63 protected $connFailureErrors = [];
66 * Constructor. Parameters are:
67 * - server: A server info structure in the format required by each
68 * element in $wgDBServers.
70 * - servers: An array of server info structures describing a set of database servers
71 * to distribute keys to. If this is specified, the "server" option will be
72 * ignored. If string keys are used, then they will be used for consistent
73 * hashing *instead* of the host name (from the server config). This is useful
74 * when a cluster is replicated to another site (with different host names)
75 * but each server has a corresponding replica in the other cluster.
77 * - purgePeriod: The average number of object cache requests in between
78 * garbage collection operations, where expired entries
79 * are removed from the database. Or in other words, the
80 * reciprocal of the probability of purging on any given
81 * request. If this is set to zero, purging will never be
84 * - tableName: The table name to use, default is "objectcache".
86 * - shards: The number of tables to use for data storage on each server.
87 * If this is more than 1, table names will be formed in the style
88 * objectcacheNNN where NNN is the shard index, between 0 and
89 * shards-1. The number of digits will be the minimum number
90 * required to hold the largest shard index. Data will be
91 * distributed across all tables by key hash. This is for
92 * MySQL bugs 61735 and 61736.
93 * - slaveOnly: Whether to only use replica DBs and avoid triggering
94 * garbage collection logic of expired items. This only
95 * makes sense if the primary DB is used and only if get()
96 * calls will be used. This is used by ReplicatedBagOStuff.
97 * - syncTimeout: Max seconds to wait for replica DBs to catch up for WRITE_SYNC.
99 * @param array $params
101 public function __construct( $params ) {
102 parent
::__construct( $params );
104 $this->attrMap
[self
::ATTR_EMULATION
] = self
::QOS_EMULATION_SQL
;
105 $this->attrMap
[self
::ATTR_SYNCWRITES
] = self
::QOS_SYNCWRITES_NONE
;
107 if ( isset( $params['servers'] ) ) {
108 $this->serverInfos
= [];
109 $this->serverTags
= [];
110 $this->numServers
= count( $params['servers'] );
112 foreach ( $params['servers'] as $tag => $info ) {
113 $this->serverInfos
[$index] = $info;
114 if ( is_string( $tag ) ) {
115 $this->serverTags
[$index] = $tag;
117 $this->serverTags
[$index] = isset( $info['host'] ) ?
$info['host'] : "#$index";
121 } elseif ( isset( $params['server'] ) ) {
122 $this->serverInfos
= [ $params['server'] ];
123 $this->numServers
= count( $this->serverInfos
);
125 // Default to using the main wiki's database servers
126 $this->serverInfos
= false;
127 $this->numServers
= 1;
128 $this->attrMap
[self
::ATTR_SYNCWRITES
] = self
::QOS_SYNCWRITES_BE
;
130 if ( isset( $params['purgePeriod'] ) ) {
131 $this->purgePeriod
= intval( $params['purgePeriod'] );
133 if ( isset( $params['tableName'] ) ) {
134 $this->tableName
= $params['tableName'];
136 if ( isset( $params['shards'] ) ) {
137 $this->shards
= intval( $params['shards'] );
139 if ( isset( $params['syncTimeout'] ) ) {
140 $this->syncTimeout
= $params['syncTimeout'];
142 $this->replicaOnly
= !empty( $params['slaveOnly'] );
145 protected function getSeparateMainLB() {
148 if ( $wgDBtype === 'mysql' && $this->usesMainDB() ) {
149 if ( !$this->separateMainLB
) {
150 // We must keep a separate connection to MySQL in order to avoid deadlocks
151 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
152 $this->separateMainLB
= $lbFactory->newMainLB();
154 return $this->separateMainLB
;
156 // However, SQLite has an opposite behavior. And PostgreSQL needs to know
157 // if we are in transaction or not (@TODO: find some PostgreSQL work-around).
163 * Get a connection to the specified database
165 * @param int $serverIndex
167 * @throws MWException
169 protected function getDB( $serverIndex ) {
170 if ( !isset( $this->conns
[$serverIndex] ) ) {
171 if ( $serverIndex >= $this->numServers
) {
172 throw new MWException( __METHOD__
. ": Invalid server index \"$serverIndex\"" );
175 # Don't keep timing out trying to connect for each call if the DB is down
176 if ( isset( $this->connFailureErrors
[$serverIndex] )
177 && ( time() - $this->connFailureTimes
[$serverIndex] ) < 60
179 throw $this->connFailureErrors
[$serverIndex];
182 # If server connection info was given, use that
183 if ( $this->serverInfos
) {
184 $info = $this->serverInfos
[$serverIndex];
185 $type = isset( $info['type'] ) ?
$info['type'] : 'mysql';
186 $host = isset( $info['host'] ) ?
$info['host'] : '[unknown]';
187 $this->logger
->debug( __CLASS__
. ": connecting to $host" );
188 // Use a blank trx profiler to ignore expections as this is a cache
189 $info['trxProfiler'] = new TransactionProfiler();
190 $db = Database
::factory( $type, $info );
191 $db->clearFlag( DBO_TRX
);
193 $index = $this->replicaOnly ? DB_REPLICA
: DB_MASTER
;
194 if ( $this->getSeparateMainLB() ) {
195 $db = $this->getSeparateMainLB()->getConnection( $index );
196 $db->clearFlag( DBO_TRX
); // auto-commit mode
198 $db = wfGetDB( $index );
199 // Can't mess with transaction rounds (DBO_TRX) :(
202 $this->logger
->debug( sprintf( "Connection %s will be used for SqlBagOStuff", $db ) );
203 $this->conns
[$serverIndex] = $db;
206 return $this->conns
[$serverIndex];
210 * Get the server index and table name for a given key
212 * @return array Server index and table name
214 protected function getTableByKey( $key ) {
215 if ( $this->shards
> 1 ) {
216 $hash = hexdec( substr( md5( $key ), 0, 8 ) ) & 0x7fffffff;
217 $tableIndex = $hash %
$this->shards
;
221 if ( $this->numServers
> 1 ) {
222 $sortedServers = $this->serverTags
;
223 ArrayUtils
::consistentHashSort( $sortedServers, $key );
224 reset( $sortedServers );
225 $serverIndex = key( $sortedServers );
229 return [ $serverIndex, $this->getTableNameByShard( $tableIndex ) ];
233 * Get the table name for a given shard index
237 protected function getTableNameByShard( $index ) {
238 if ( $this->shards
> 1 ) {
239 $decimals = strlen( $this->shards
- 1 );
240 return $this->tableName
.
241 sprintf( "%0{$decimals}d", $index );
243 return $this->tableName
;
247 protected function doGet( $key, $flags = 0 ) {
250 return $this->getWithToken( $key, $casToken, $flags );
253 protected function getWithToken( $key, &$casToken, $flags = 0 ) {
254 $values = $this->getMulti( [ $key ] );
255 if ( array_key_exists( $key, $values ) ) {
256 $casToken = $values[$key];
257 return $values[$key];
262 public function getMulti( array $keys, $flags = 0 ) {
263 $values = []; // array of (key => value)
266 foreach ( $keys as $key ) {
267 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
268 $keysByTable[$serverIndex][$tableName][] = $key;
271 $this->garbageCollect(); // expire old entries if any
274 foreach ( $keysByTable as $serverIndex => $serverKeys ) {
276 $db = $this->getDB( $serverIndex );
277 foreach ( $serverKeys as $tableName => $tableKeys ) {
278 $res = $db->select( $tableName,
279 [ 'keyname', 'value', 'exptime' ],
280 [ 'keyname' => $tableKeys ],
282 // Approximate write-on-the-fly BagOStuff API via blocking.
283 // This approximation fails if a ROLLBACK happens (which is rare).
284 // We do not want to flush the TRX as that can break callers.
285 $db->trxLevel() ?
[ 'LOCK IN SHARE MODE' ] : []
287 if ( $res === false ) {
290 foreach ( $res as $row ) {
291 $row->serverIndex
= $serverIndex;
292 $row->tableName
= $tableName;
293 $dataRows[$row->keyname
] = $row;
296 } catch ( DBError
$e ) {
297 $this->handleReadError( $e, $serverIndex );
301 foreach ( $keys as $key ) {
302 if ( isset( $dataRows[$key] ) ) { // HIT?
303 $row = $dataRows[$key];
304 $this->debug( "get: retrieved data; expiry time is " . $row->exptime
);
307 $db = $this->getDB( $row->serverIndex
);
308 if ( $this->isExpired( $db, $row->exptime
) ) { // MISS
309 $this->debug( "get: key has expired" );
311 $values[$key] = $this->unserialize( $db->decodeBlob( $row->value
) );
313 } catch ( DBQueryError
$e ) {
314 $this->handleWriteError( $e, $db, $row->serverIndex
);
317 $this->debug( 'get: no matching rows' );
324 public function setMulti( array $data, $expiry = 0 ) {
326 foreach ( $data as $key => $value ) {
327 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
328 $keysByTable[$serverIndex][$tableName][] = $key;
331 $this->garbageCollect(); // expire old entries if any
334 $exptime = (int)$expiry;
335 foreach ( $keysByTable as $serverIndex => $serverKeys ) {
338 $db = $this->getDB( $serverIndex );
339 } catch ( DBError
$e ) {
340 $this->handleWriteError( $e, $db, $serverIndex );
345 if ( $exptime < 0 ) {
349 if ( $exptime == 0 ) {
350 $encExpiry = $this->getMaxDateTime( $db );
352 $exptime = $this->convertExpiry( $exptime );
353 $encExpiry = $db->timestamp( $exptime );
355 foreach ( $serverKeys as $tableName => $tableKeys ) {
357 foreach ( $tableKeys as $key ) {
360 'value' => $db->encodeBlob( $this->serialize( $data[$key] ) ),
361 'exptime' => $encExpiry,
372 } catch ( DBError
$e ) {
373 $this->handleWriteError( $e, $db, $serverIndex );
384 public function set( $key, $value, $exptime = 0, $flags = 0 ) {
385 $ok = $this->setMulti( [ $key => $value ], $exptime );
386 if ( ( $flags & self
::WRITE_SYNC
) == self
::WRITE_SYNC
) {
387 $ok = $this->waitForReplication() && $ok;
393 protected function cas( $casToken, $key, $value, $exptime = 0 ) {
394 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
397 $db = $this->getDB( $serverIndex );
398 $exptime = intval( $exptime );
400 if ( $exptime < 0 ) {
404 if ( $exptime == 0 ) {
405 $encExpiry = $this->getMaxDateTime( $db );
407 $exptime = $this->convertExpiry( $exptime );
408 $encExpiry = $db->timestamp( $exptime );
410 // (T26425) use a replace if the db supports it instead of
411 // delete/insert to avoid clashes with conflicting keynames
416 'value' => $db->encodeBlob( $this->serialize( $value ) ),
417 'exptime' => $encExpiry
421 'value' => $db->encodeBlob( $this->serialize( $casToken ) )
425 } catch ( DBQueryError
$e ) {
426 $this->handleWriteError( $e, $db, $serverIndex );
431 return (bool)$db->affectedRows();
434 public function delete( $key ) {
435 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
438 $db = $this->getDB( $serverIndex );
441 [ 'keyname' => $key ],
443 } catch ( DBError
$e ) {
444 $this->handleWriteError( $e, $db, $serverIndex );
451 public function incr( $key, $step = 1 ) {
452 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
455 $db = $this->getDB( $serverIndex );
456 $step = intval( $step );
457 $row = $db->selectRow(
459 [ 'value', 'exptime' ],
460 [ 'keyname' => $key ],
463 if ( $row === false ) {
468 $db->delete( $tableName, [ 'keyname' => $key ], __METHOD__
);
469 if ( $this->isExpired( $db, $row->exptime
) ) {
470 // Expired, do not reinsert
475 $oldValue = intval( $this->unserialize( $db->decodeBlob( $row->value
) ) );
476 $newValue = $oldValue +
$step;
477 $db->insert( $tableName,
480 'value' => $db->encodeBlob( $this->serialize( $newValue ) ),
481 'exptime' => $row->exptime
482 ], __METHOD__
, 'IGNORE' );
484 if ( $db->affectedRows() == 0 ) {
485 // Race condition. See T30611
488 } catch ( DBError
$e ) {
489 $this->handleWriteError( $e, $db, $serverIndex );
496 public function merge( $key, callable
$callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
497 $ok = $this->mergeViaCas( $key, $callback, $exptime, $attempts );
498 if ( ( $flags & self
::WRITE_SYNC
) == self
::WRITE_SYNC
) {
499 $ok = $this->waitForReplication() && $ok;
505 public function changeTTL( $key, $expiry = 0 ) {
506 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
509 $db = $this->getDB( $serverIndex );
512 [ 'exptime' => $db->timestamp( $this->convertExpiry( $expiry ) ) ],
513 [ 'keyname' => $key, 'exptime > ' . $db->addQuotes( $db->timestamp( time() ) ) ],
516 if ( $db->affectedRows() == 0 ) {
519 } catch ( DBError
$e ) {
520 $this->handleWriteError( $e, $db, $serverIndex );
528 * @param IDatabase $db
529 * @param string $exptime
532 protected function isExpired( $db, $exptime ) {
533 return $exptime != $this->getMaxDateTime( $db ) && wfTimestamp( TS_UNIX
, $exptime ) < time();
537 * @param IDatabase $db
540 protected function getMaxDateTime( $db ) {
541 if ( time() > 0x7fffffff ) {
542 return $db->timestamp( 1 << 62 );
544 return $db->timestamp( 0x7fffffff );
548 protected function garbageCollect() {
549 if ( !$this->purgePeriod ||
$this->replicaOnly
) {
553 // Only purge on one in every $this->purgePeriod requests.
554 if ( $this->purgePeriod
!== 1 && mt_rand( 0, $this->purgePeriod
- 1 ) ) {
558 // Avoid repeating the delete within a few seconds
559 if ( $now > ( $this->lastExpireAll +
1 ) ) {
560 $this->lastExpireAll
= $now;
565 public function expireAll() {
566 $this->deleteObjectsExpiringBefore( wfTimestampNow() );
570 * Delete objects from the database which expire before a certain date.
571 * @param string $timestamp
572 * @param bool|callable $progressCallback
575 public function deleteObjectsExpiringBefore( $timestamp, $progressCallback = false ) {
576 for ( $serverIndex = 0; $serverIndex < $this->numServers
; $serverIndex++
) {
579 $db = $this->getDB( $serverIndex );
580 $dbTimestamp = $db->timestamp( $timestamp );
581 $totalSeconds = false;
582 $baseConds = [ 'exptime < ' . $db->addQuotes( $dbTimestamp ) ];
583 for ( $i = 0; $i < $this->shards
; $i++
) {
587 if ( $maxExpTime !== false ) {
588 $conds[] = 'exptime > ' . $db->addQuotes( $maxExpTime );
591 $this->getTableNameByShard( $i ),
592 [ 'keyname', 'exptime' ],
595 [ 'LIMIT' => 100, 'ORDER BY' => 'exptime' ] );
596 if ( $rows === false ||
!$rows->numRows() ) {
600 $row = $rows->current();
601 $minExpTime = $row->exptime
;
602 if ( $totalSeconds === false ) {
603 $totalSeconds = wfTimestamp( TS_UNIX
, $timestamp )
604 - wfTimestamp( TS_UNIX
, $minExpTime );
606 foreach ( $rows as $row ) {
607 $keys[] = $row->keyname
;
608 $maxExpTime = $row->exptime
;
612 $this->getTableNameByShard( $i ),
614 'exptime >= ' . $db->addQuotes( $minExpTime ),
615 'exptime < ' . $db->addQuotes( $dbTimestamp ),
620 if ( $progressCallback ) {
621 if ( intval( $totalSeconds ) === 0 ) {
624 $remainingSeconds = wfTimestamp( TS_UNIX
, $timestamp )
625 - wfTimestamp( TS_UNIX
, $maxExpTime );
626 if ( $remainingSeconds > $totalSeconds ) {
627 $totalSeconds = $remainingSeconds;
629 $processedSeconds = $totalSeconds - $remainingSeconds;
630 $percent = ( $i +
$processedSeconds / $totalSeconds )
631 / $this->shards
* 100;
633 $percent = ( $percent / $this->numServers
)
634 +
( $serverIndex / $this->numServers
* 100 );
635 call_user_func( $progressCallback, $percent );
639 } catch ( DBError
$e ) {
640 $this->handleWriteError( $e, $db, $serverIndex );
648 * Delete content of shard tables in every server.
649 * Return true if the operation is successful, false otherwise.
652 public function deleteAll() {
653 for ( $serverIndex = 0; $serverIndex < $this->numServers
; $serverIndex++
) {
656 $db = $this->getDB( $serverIndex );
657 for ( $i = 0; $i < $this->shards
; $i++
) {
658 $db->delete( $this->getTableNameByShard( $i ), '*', __METHOD__
);
660 } catch ( DBError
$e ) {
661 $this->handleWriteError( $e, $db, $serverIndex );
669 * Serialize an object and, if possible, compress the representation.
670 * On typical message and page data, this can provide a 3X decrease
671 * in storage requirements.
676 protected function serialize( &$data ) {
677 $serial = serialize( $data );
679 if ( function_exists( 'gzdeflate' ) ) {
680 return gzdeflate( $serial );
687 * Unserialize and, if necessary, decompress an object.
688 * @param string $serial
691 protected function unserialize( $serial ) {
692 if ( function_exists( 'gzinflate' ) ) {
693 MediaWiki\
suppressWarnings();
694 $decomp = gzinflate( $serial );
695 MediaWiki\restoreWarnings
();
697 if ( false !== $decomp ) {
702 $ret = unserialize( $serial );
708 * Handle a DBError which occurred during a read operation.
710 * @param DBError $exception
711 * @param int $serverIndex
713 protected function handleReadError( DBError
$exception, $serverIndex ) {
714 if ( $exception instanceof DBConnectionError
) {
715 $this->markServerDown( $exception, $serverIndex );
717 $this->logger
->error( "DBError: {$exception->getMessage()}" );
718 if ( $exception instanceof DBConnectionError
) {
719 $this->setLastError( BagOStuff
::ERR_UNREACHABLE
);
720 $this->logger
->debug( __METHOD__
. ": ignoring connection error" );
722 $this->setLastError( BagOStuff
::ERR_UNEXPECTED
);
723 $this->logger
->debug( __METHOD__
. ": ignoring query error" );
728 * Handle a DBQueryError which occurred during a write operation.
730 * @param DBError $exception
731 * @param IDatabase|null $db DB handle or null if connection failed
732 * @param int $serverIndex
735 protected function handleWriteError( DBError
$exception, IDatabase
$db = null, $serverIndex ) {
737 $this->markServerDown( $exception, $serverIndex );
738 } elseif ( $db->wasReadOnlyError() ) {
739 if ( $db->trxLevel() && $this->usesMainDB() ) {
740 // Errors like deadlocks and connection drops already cause rollback.
741 // For consistency, we have no choice but to throw an error and trigger
742 // complete rollback if the main DB is also being used as the cache DB.
747 $this->logger
->error( "DBError: {$exception->getMessage()}" );
748 if ( $exception instanceof DBConnectionError
) {
749 $this->setLastError( BagOStuff
::ERR_UNREACHABLE
);
750 $this->logger
->debug( __METHOD__
. ": ignoring connection error" );
752 $this->setLastError( BagOStuff
::ERR_UNEXPECTED
);
753 $this->logger
->debug( __METHOD__
. ": ignoring query error" );
758 * Mark a server down due to a DBConnectionError exception
760 * @param DBError $exception
761 * @param int $serverIndex
763 protected function markServerDown( DBError
$exception, $serverIndex ) {
764 unset( $this->conns
[$serverIndex] ); // bug T103435
766 if ( isset( $this->connFailureTimes
[$serverIndex] ) ) {
767 if ( time() - $this->connFailureTimes
[$serverIndex] >= 60 ) {
768 unset( $this->connFailureTimes
[$serverIndex] );
769 unset( $this->connFailureErrors
[$serverIndex] );
771 $this->logger
->debug( __METHOD__
. ": Server #$serverIndex already down" );
776 $this->logger
->info( __METHOD__
. ": Server #$serverIndex down until " . ( $now +
60 ) );
777 $this->connFailureTimes
[$serverIndex] = $now;
778 $this->connFailureErrors
[$serverIndex] = $exception;
782 * Create shard tables. For use from eval.php.
784 public function createTables() {
785 for ( $serverIndex = 0; $serverIndex < $this->numServers
; $serverIndex++
) {
786 $db = $this->getDB( $serverIndex );
787 if ( $db->getType() !== 'mysql' ) {
788 throw new MWException( __METHOD__
. ' is not supported on this DB server' );
791 for ( $i = 0; $i < $this->shards
; $i++
) {
793 'CREATE TABLE ' . $db->tableName( $this->getTableNameByShard( $i ) ) .
794 ' LIKE ' . $db->tableName( 'objectcache' ),
801 * @return bool Whether the main DB is used, e.g. wfGetDB( DB_MASTER )
803 protected function usesMainDB() {
804 return !$this->serverInfos
;
807 protected function waitForReplication() {
808 if ( !$this->usesMainDB() ) {
809 // Custom DB server list; probably doesn't use replication
813 $lb = $this->getSeparateMainLB()
814 ?
: MediaWikiServices
::getInstance()->getDBLoadBalancer();
816 if ( $lb->getServerCount() <= 1 ) {
817 return true; // no replica DBs
820 // Main LB is used; wait for any replica DBs to catch up
821 $masterPos = $lb->getMasterPos();
823 $loop = new WaitConditionLoop(
824 function () use ( $lb, $masterPos ) {
825 return $lb->waitForAll( $masterPos, 1 );
831 return ( $loop->invoke() === $loop::CONDITION_REACHED
);