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 Wikimedia\Rdbms\DBError
;
27 use Wikimedia\Rdbms\DBQueryError
;
28 use Wikimedia\Rdbms\DBConnectionError
;
29 use \MediaWiki\MediaWikiServices
;
30 use \Wikimedia\WaitConditionLoop
;
31 use \Wikimedia\Rdbms\TransactionProfiler
;
32 use Wikimedia\Rdbms\LoadBalancer
;
35 * Class to store objects in the database
39 class SqlBagOStuff
extends BagOStuff
{
40 /** @var array[] (server index => server config) */
41 protected $serverInfos;
42 /** @var string[] (server index => tag/host name) */
43 protected $serverTags;
45 protected $numServers;
47 protected $lastExpireAll = 0;
49 protected $purgePeriod = 100;
51 protected $shards = 1;
53 protected $tableName = 'objectcache';
55 protected $replicaOnly = false;
57 protected $syncTimeout = 3;
59 /** @var LoadBalancer|null */
60 protected $separateMainLB;
63 /** @var array UNIX timestamps */
64 protected $connFailureTimes = [];
65 /** @var array Exceptions */
66 protected $connFailureErrors = [];
69 * Constructor. Parameters are:
70 * - server: A server info structure in the format required by each
71 * element in $wgDBServers.
73 * - servers: An array of server info structures describing a set of database servers
74 * to distribute keys to. If this is specified, the "server" option will be
75 * ignored. If string keys are used, then they will be used for consistent
76 * hashing *instead* of the host name (from the server config). This is useful
77 * when a cluster is replicated to another site (with different host names)
78 * but each server has a corresponding replica in the other cluster.
80 * - purgePeriod: The average number of object cache requests in between
81 * garbage collection operations, where expired entries
82 * are removed from the database. Or in other words, the
83 * reciprocal of the probability of purging on any given
84 * request. If this is set to zero, purging will never be
87 * - tableName: The table name to use, default is "objectcache".
89 * - shards: The number of tables to use for data storage on each server.
90 * If this is more than 1, table names will be formed in the style
91 * objectcacheNNN where NNN is the shard index, between 0 and
92 * shards-1. The number of digits will be the minimum number
93 * required to hold the largest shard index. Data will be
94 * distributed across all tables by key hash. This is for
95 * MySQL bugs 61735 and 61736.
96 * - slaveOnly: Whether to only use replica DBs and avoid triggering
97 * garbage collection logic of expired items. This only
98 * makes sense if the primary DB is used and only if get()
99 * calls will be used. This is used by ReplicatedBagOStuff.
100 * - syncTimeout: Max seconds to wait for replica DBs to catch up for WRITE_SYNC.
102 * @param array $params
104 public function __construct( $params ) {
105 parent
::__construct( $params );
107 $this->attrMap
[self
::ATTR_EMULATION
] = self
::QOS_EMULATION_SQL
;
108 $this->attrMap
[self
::ATTR_SYNCWRITES
] = self
::QOS_SYNCWRITES_NONE
;
110 if ( isset( $params['servers'] ) ) {
111 $this->serverInfos
= [];
112 $this->serverTags
= [];
113 $this->numServers
= count( $params['servers'] );
115 foreach ( $params['servers'] as $tag => $info ) {
116 $this->serverInfos
[$index] = $info;
117 if ( is_string( $tag ) ) {
118 $this->serverTags
[$index] = $tag;
120 $this->serverTags
[$index] = isset( $info['host'] ) ?
$info['host'] : "#$index";
124 } elseif ( isset( $params['server'] ) ) {
125 $this->serverInfos
= [ $params['server'] ];
126 $this->numServers
= count( $this->serverInfos
);
128 // Default to using the main wiki's database servers
129 $this->serverInfos
= false;
130 $this->numServers
= 1;
131 $this->attrMap
[self
::ATTR_SYNCWRITES
] = self
::QOS_SYNCWRITES_BE
;
133 if ( isset( $params['purgePeriod'] ) ) {
134 $this->purgePeriod
= intval( $params['purgePeriod'] );
136 if ( isset( $params['tableName'] ) ) {
137 $this->tableName
= $params['tableName'];
139 if ( isset( $params['shards'] ) ) {
140 $this->shards
= intval( $params['shards'] );
142 if ( isset( $params['syncTimeout'] ) ) {
143 $this->syncTimeout
= $params['syncTimeout'];
145 $this->replicaOnly
= !empty( $params['slaveOnly'] );
148 protected function getSeparateMainLB() {
151 if ( $this->usesMainDB() && $wgDBtype !== 'sqlite' ) {
152 if ( !$this->separateMainLB
) {
153 // We must keep a separate connection to MySQL in order to avoid deadlocks
154 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
155 $this->separateMainLB
= $lbFactory->newMainLB();
157 return $this->separateMainLB
;
159 // However, SQLite has an opposite behavior due to DB-level locking
165 * Get a connection to the specified database
167 * @param int $serverIndex
169 * @throws MWException
171 protected function getDB( $serverIndex ) {
172 if ( !isset( $this->conns
[$serverIndex] ) ) {
173 if ( $serverIndex >= $this->numServers
) {
174 throw new MWException( __METHOD__
. ": Invalid server index \"$serverIndex\"" );
177 # Don't keep timing out trying to connect for each call if the DB is down
178 if ( isset( $this->connFailureErrors
[$serverIndex] )
179 && ( time() - $this->connFailureTimes
[$serverIndex] ) < 60
181 throw $this->connFailureErrors
[$serverIndex];
184 # If server connection info was given, use that
185 if ( $this->serverInfos
) {
186 $info = $this->serverInfos
[$serverIndex];
187 $type = isset( $info['type'] ) ?
$info['type'] : 'mysql';
188 $host = isset( $info['host'] ) ?
$info['host'] : '[unknown]';
189 $this->logger
->debug( __CLASS__
. ": connecting to $host" );
190 // Use a blank trx profiler to ignore expections as this is a cache
191 $info['trxProfiler'] = new TransactionProfiler();
192 $db = Database
::factory( $type, $info );
193 $db->clearFlag( DBO_TRX
);
195 $index = $this->replicaOnly ? DB_REPLICA
: DB_MASTER
;
196 if ( $this->getSeparateMainLB() ) {
197 $db = $this->getSeparateMainLB()->getConnection( $index );
198 $db->clearFlag( DBO_TRX
); // auto-commit mode
200 $db = wfGetDB( $index );
201 // Can't mess with transaction rounds (DBO_TRX) :(
204 $this->logger
->debug( sprintf( "Connection %s will be used for SqlBagOStuff", $db ) );
205 $this->conns
[$serverIndex] = $db;
208 return $this->conns
[$serverIndex];
212 * Get the server index and table name for a given key
214 * @return array Server index and table name
216 protected function getTableByKey( $key ) {
217 if ( $this->shards
> 1 ) {
218 $hash = hexdec( substr( md5( $key ), 0, 8 ) ) & 0x7fffffff;
219 $tableIndex = $hash %
$this->shards
;
223 if ( $this->numServers
> 1 ) {
224 $sortedServers = $this->serverTags
;
225 ArrayUtils
::consistentHashSort( $sortedServers, $key );
226 reset( $sortedServers );
227 $serverIndex = key( $sortedServers );
231 return [ $serverIndex, $this->getTableNameByShard( $tableIndex ) ];
235 * Get the table name for a given shard index
239 protected function getTableNameByShard( $index ) {
240 if ( $this->shards
> 1 ) {
241 $decimals = strlen( $this->shards
- 1 );
242 return $this->tableName
.
243 sprintf( "%0{$decimals}d", $index );
245 return $this->tableName
;
249 protected function doGet( $key, $flags = 0 ) {
252 return $this->getWithToken( $key, $casToken, $flags );
255 protected function getWithToken( $key, &$casToken, $flags = 0 ) {
256 $values = $this->getMulti( [ $key ] );
257 if ( array_key_exists( $key, $values ) ) {
258 $casToken = $values[$key];
259 return $values[$key];
264 public function getMulti( array $keys, $flags = 0 ) {
265 $values = []; // array of (key => value)
268 foreach ( $keys as $key ) {
269 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
270 $keysByTable[$serverIndex][$tableName][] = $key;
273 $this->garbageCollect(); // expire old entries if any
276 foreach ( $keysByTable as $serverIndex => $serverKeys ) {
278 $db = $this->getDB( $serverIndex );
279 foreach ( $serverKeys as $tableName => $tableKeys ) {
280 $res = $db->select( $tableName,
281 [ 'keyname', 'value', 'exptime' ],
282 [ 'keyname' => $tableKeys ],
284 // Approximate write-on-the-fly BagOStuff API via blocking.
285 // This approximation fails if a ROLLBACK happens (which is rare).
286 // We do not want to flush the TRX as that can break callers.
287 $db->trxLevel() ?
[ 'LOCK IN SHARE MODE' ] : []
289 if ( $res === false ) {
292 foreach ( $res as $row ) {
293 $row->serverIndex
= $serverIndex;
294 $row->tableName
= $tableName;
295 $dataRows[$row->keyname
] = $row;
298 } catch ( DBError
$e ) {
299 $this->handleReadError( $e, $serverIndex );
303 foreach ( $keys as $key ) {
304 if ( isset( $dataRows[$key] ) ) { // HIT?
305 $row = $dataRows[$key];
306 $this->debug( "get: retrieved data; expiry time is " . $row->exptime
);
309 $db = $this->getDB( $row->serverIndex
);
310 if ( $this->isExpired( $db, $row->exptime
) ) { // MISS
311 $this->debug( "get: key has expired" );
313 $values[$key] = $this->unserialize( $db->decodeBlob( $row->value
) );
315 } catch ( DBQueryError
$e ) {
316 $this->handleWriteError( $e, $db, $row->serverIndex
);
319 $this->debug( 'get: no matching rows' );
326 public function setMulti( array $data, $expiry = 0 ) {
328 foreach ( $data as $key => $value ) {
329 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
330 $keysByTable[$serverIndex][$tableName][] = $key;
333 $this->garbageCollect(); // expire old entries if any
336 $exptime = (int)$expiry;
337 foreach ( $keysByTable as $serverIndex => $serverKeys ) {
340 $db = $this->getDB( $serverIndex );
341 } catch ( DBError
$e ) {
342 $this->handleWriteError( $e, $db, $serverIndex );
347 if ( $exptime < 0 ) {
351 if ( $exptime == 0 ) {
352 $encExpiry = $this->getMaxDateTime( $db );
354 $exptime = $this->convertExpiry( $exptime );
355 $encExpiry = $db->timestamp( $exptime );
357 foreach ( $serverKeys as $tableName => $tableKeys ) {
359 foreach ( $tableKeys as $key ) {
362 'value' => $db->encodeBlob( $this->serialize( $data[$key] ) ),
363 'exptime' => $encExpiry,
374 } catch ( DBError
$e ) {
375 $this->handleWriteError( $e, $db, $serverIndex );
386 public function set( $key, $value, $exptime = 0, $flags = 0 ) {
387 $ok = $this->setMulti( [ $key => $value ], $exptime );
388 if ( ( $flags & self
::WRITE_SYNC
) == self
::WRITE_SYNC
) {
389 $ok = $this->waitForReplication() && $ok;
395 protected function cas( $casToken, $key, $value, $exptime = 0 ) {
396 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
399 $db = $this->getDB( $serverIndex );
400 $exptime = intval( $exptime );
402 if ( $exptime < 0 ) {
406 if ( $exptime == 0 ) {
407 $encExpiry = $this->getMaxDateTime( $db );
409 $exptime = $this->convertExpiry( $exptime );
410 $encExpiry = $db->timestamp( $exptime );
412 // (T26425) use a replace if the db supports it instead of
413 // delete/insert to avoid clashes with conflicting keynames
418 'value' => $db->encodeBlob( $this->serialize( $value ) ),
419 'exptime' => $encExpiry
423 'value' => $db->encodeBlob( $this->serialize( $casToken ) )
427 } catch ( DBQueryError
$e ) {
428 $this->handleWriteError( $e, $db, $serverIndex );
433 return (bool)$db->affectedRows();
436 public function delete( $key ) {
437 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
440 $db = $this->getDB( $serverIndex );
443 [ 'keyname' => $key ],
445 } catch ( DBError
$e ) {
446 $this->handleWriteError( $e, $db, $serverIndex );
453 public function incr( $key, $step = 1 ) {
454 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
457 $db = $this->getDB( $serverIndex );
458 $step = intval( $step );
459 $row = $db->selectRow(
461 [ 'value', 'exptime' ],
462 [ 'keyname' => $key ],
465 if ( $row === false ) {
470 $db->delete( $tableName, [ 'keyname' => $key ], __METHOD__
);
471 if ( $this->isExpired( $db, $row->exptime
) ) {
472 // Expired, do not reinsert
477 $oldValue = intval( $this->unserialize( $db->decodeBlob( $row->value
) ) );
478 $newValue = $oldValue +
$step;
479 $db->insert( $tableName,
482 'value' => $db->encodeBlob( $this->serialize( $newValue ) ),
483 'exptime' => $row->exptime
484 ], __METHOD__
, 'IGNORE' );
486 if ( $db->affectedRows() == 0 ) {
487 // Race condition. See T30611
490 } catch ( DBError
$e ) {
491 $this->handleWriteError( $e, $db, $serverIndex );
498 public function merge( $key, callable
$callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
499 $ok = $this->mergeViaCas( $key, $callback, $exptime, $attempts );
500 if ( ( $flags & self
::WRITE_SYNC
) == self
::WRITE_SYNC
) {
501 $ok = $this->waitForReplication() && $ok;
507 public function changeTTL( $key, $expiry = 0 ) {
508 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
511 $db = $this->getDB( $serverIndex );
514 [ 'exptime' => $db->timestamp( $this->convertExpiry( $expiry ) ) ],
515 [ 'keyname' => $key, 'exptime > ' . $db->addQuotes( $db->timestamp( time() ) ) ],
518 if ( $db->affectedRows() == 0 ) {
521 } catch ( DBError
$e ) {
522 $this->handleWriteError( $e, $db, $serverIndex );
530 * @param IDatabase $db
531 * @param string $exptime
534 protected function isExpired( $db, $exptime ) {
535 return $exptime != $this->getMaxDateTime( $db ) && wfTimestamp( TS_UNIX
, $exptime ) < time();
539 * @param IDatabase $db
542 protected function getMaxDateTime( $db ) {
543 if ( time() > 0x7fffffff ) {
544 return $db->timestamp( 1 << 62 );
546 return $db->timestamp( 0x7fffffff );
550 protected function garbageCollect() {
551 if ( !$this->purgePeriod ||
$this->replicaOnly
) {
555 // Only purge on one in every $this->purgePeriod requests.
556 if ( $this->purgePeriod
!== 1 && mt_rand( 0, $this->purgePeriod
- 1 ) ) {
560 // Avoid repeating the delete within a few seconds
561 if ( $now > ( $this->lastExpireAll +
1 ) ) {
562 $this->lastExpireAll
= $now;
567 public function expireAll() {
568 $this->deleteObjectsExpiringBefore( wfTimestampNow() );
572 * Delete objects from the database which expire before a certain date.
573 * @param string $timestamp
574 * @param bool|callable $progressCallback
577 public function deleteObjectsExpiringBefore( $timestamp, $progressCallback = false ) {
578 for ( $serverIndex = 0; $serverIndex < $this->numServers
; $serverIndex++
) {
581 $db = $this->getDB( $serverIndex );
582 $dbTimestamp = $db->timestamp( $timestamp );
583 $totalSeconds = false;
584 $baseConds = [ 'exptime < ' . $db->addQuotes( $dbTimestamp ) ];
585 for ( $i = 0; $i < $this->shards
; $i++
) {
589 if ( $maxExpTime !== false ) {
590 $conds[] = 'exptime >= ' . $db->addQuotes( $maxExpTime );
593 $this->getTableNameByShard( $i ),
594 [ 'keyname', 'exptime' ],
597 [ 'LIMIT' => 100, 'ORDER BY' => 'exptime' ] );
598 if ( $rows === false ||
!$rows->numRows() ) {
602 $row = $rows->current();
603 $minExpTime = $row->exptime
;
604 if ( $totalSeconds === false ) {
605 $totalSeconds = wfTimestamp( TS_UNIX
, $timestamp )
606 - wfTimestamp( TS_UNIX
, $minExpTime );
608 foreach ( $rows as $row ) {
609 $keys[] = $row->keyname
;
610 $maxExpTime = $row->exptime
;
614 $this->getTableNameByShard( $i ),
616 'exptime >= ' . $db->addQuotes( $minExpTime ),
617 'exptime < ' . $db->addQuotes( $dbTimestamp ),
622 if ( $progressCallback ) {
623 if ( intval( $totalSeconds ) === 0 ) {
626 $remainingSeconds = wfTimestamp( TS_UNIX
, $timestamp )
627 - wfTimestamp( TS_UNIX
, $maxExpTime );
628 if ( $remainingSeconds > $totalSeconds ) {
629 $totalSeconds = $remainingSeconds;
631 $processedSeconds = $totalSeconds - $remainingSeconds;
632 $percent = ( $i +
$processedSeconds / $totalSeconds )
633 / $this->shards
* 100;
635 $percent = ( $percent / $this->numServers
)
636 +
( $serverIndex / $this->numServers
* 100 );
637 call_user_func( $progressCallback, $percent );
641 } catch ( DBError
$e ) {
642 $this->handleWriteError( $e, $db, $serverIndex );
650 * Delete content of shard tables in every server.
651 * Return true if the operation is successful, false otherwise.
654 public function deleteAll() {
655 for ( $serverIndex = 0; $serverIndex < $this->numServers
; $serverIndex++
) {
658 $db = $this->getDB( $serverIndex );
659 for ( $i = 0; $i < $this->shards
; $i++
) {
660 $db->delete( $this->getTableNameByShard( $i ), '*', __METHOD__
);
662 } catch ( DBError
$e ) {
663 $this->handleWriteError( $e, $db, $serverIndex );
671 * Serialize an object and, if possible, compress the representation.
672 * On typical message and page data, this can provide a 3X decrease
673 * in storage requirements.
678 protected function serialize( &$data ) {
679 $serial = serialize( $data );
681 if ( function_exists( 'gzdeflate' ) ) {
682 return gzdeflate( $serial );
689 * Unserialize and, if necessary, decompress an object.
690 * @param string $serial
693 protected function unserialize( $serial ) {
694 if ( function_exists( 'gzinflate' ) ) {
695 MediaWiki\
suppressWarnings();
696 $decomp = gzinflate( $serial );
697 MediaWiki\restoreWarnings
();
699 if ( false !== $decomp ) {
704 $ret = unserialize( $serial );
710 * Handle a DBError which occurred during a read operation.
712 * @param DBError $exception
713 * @param int $serverIndex
715 protected function handleReadError( DBError
$exception, $serverIndex ) {
716 if ( $exception instanceof DBConnectionError
) {
717 $this->markServerDown( $exception, $serverIndex );
719 $this->logger
->error( "DBError: {$exception->getMessage()}" );
720 if ( $exception instanceof DBConnectionError
) {
721 $this->setLastError( BagOStuff
::ERR_UNREACHABLE
);
722 $this->logger
->debug( __METHOD__
. ": ignoring connection error" );
724 $this->setLastError( BagOStuff
::ERR_UNEXPECTED
);
725 $this->logger
->debug( __METHOD__
. ": ignoring query error" );
730 * Handle a DBQueryError which occurred during a write operation.
732 * @param DBError $exception
733 * @param IDatabase|null $db DB handle or null if connection failed
734 * @param int $serverIndex
737 protected function handleWriteError( DBError
$exception, IDatabase
$db = null, $serverIndex ) {
739 $this->markServerDown( $exception, $serverIndex );
740 } elseif ( $db->wasReadOnlyError() ) {
741 if ( $db->trxLevel() && $this->usesMainDB() ) {
742 // Errors like deadlocks and connection drops already cause rollback.
743 // For consistency, we have no choice but to throw an error and trigger
744 // complete rollback if the main DB is also being used as the cache DB.
749 $this->logger
->error( "DBError: {$exception->getMessage()}" );
750 if ( $exception instanceof DBConnectionError
) {
751 $this->setLastError( BagOStuff
::ERR_UNREACHABLE
);
752 $this->logger
->debug( __METHOD__
. ": ignoring connection error" );
754 $this->setLastError( BagOStuff
::ERR_UNEXPECTED
);
755 $this->logger
->debug( __METHOD__
. ": ignoring query error" );
760 * Mark a server down due to a DBConnectionError exception
762 * @param DBError $exception
763 * @param int $serverIndex
765 protected function markServerDown( DBError
$exception, $serverIndex ) {
766 unset( $this->conns
[$serverIndex] ); // bug T103435
768 if ( isset( $this->connFailureTimes
[$serverIndex] ) ) {
769 if ( time() - $this->connFailureTimes
[$serverIndex] >= 60 ) {
770 unset( $this->connFailureTimes
[$serverIndex] );
771 unset( $this->connFailureErrors
[$serverIndex] );
773 $this->logger
->debug( __METHOD__
. ": Server #$serverIndex already down" );
778 $this->logger
->info( __METHOD__
. ": Server #$serverIndex down until " . ( $now +
60 ) );
779 $this->connFailureTimes
[$serverIndex] = $now;
780 $this->connFailureErrors
[$serverIndex] = $exception;
784 * Create shard tables. For use from eval.php.
786 public function createTables() {
787 for ( $serverIndex = 0; $serverIndex < $this->numServers
; $serverIndex++
) {
788 $db = $this->getDB( $serverIndex );
789 if ( $db->getType() !== 'mysql' ) {
790 throw new MWException( __METHOD__
. ' is not supported on this DB server' );
793 for ( $i = 0; $i < $this->shards
; $i++
) {
795 'CREATE TABLE ' . $db->tableName( $this->getTableNameByShard( $i ) ) .
796 ' LIKE ' . $db->tableName( 'objectcache' ),
803 * @return bool Whether the main DB is used, e.g. wfGetDB( DB_MASTER )
805 protected function usesMainDB() {
806 return !$this->serverInfos
;
809 protected function waitForReplication() {
810 if ( !$this->usesMainDB() ) {
811 // Custom DB server list; probably doesn't use replication
815 $lb = $this->getSeparateMainLB()
816 ?
: MediaWikiServices
::getInstance()->getDBLoadBalancer();
818 if ( $lb->getServerCount() <= 1 ) {
819 return true; // no replica DBs
822 // Main LB is used; wait for any replica DBs to catch up
823 $masterPos = $lb->getMasterPos();
825 $loop = new WaitConditionLoop(
826 function () use ( $lb, $masterPos ) {
827 return $lb->waitForAll( $masterPos, 1 );
833 return ( $loop->invoke() === $loop::CONDITION_REACHED
);