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\IDatabase
;
25 use \MediaWiki\MediaWikiServices
;
26 use \Wikimedia\WaitConditionLoop
;
27 use \Wikimedia\Rdbms\TransactionProfiler
;
28 use Wikimedia\Rdbms\LoadBalancer
;
31 * Class to store objects in the database
35 class SqlBagOStuff
extends BagOStuff
{
36 /** @var array[] (server index => server config) */
37 protected $serverInfos;
38 /** @var string[] (server index => tag/host name) */
39 protected $serverTags;
41 protected $numServers;
43 protected $lastExpireAll = 0;
45 protected $purgePeriod = 100;
47 protected $shards = 1;
49 protected $tableName = 'objectcache';
51 protected $replicaOnly = false;
53 protected $syncTimeout = 3;
55 /** @var LoadBalancer|null */
56 protected $separateMainLB;
59 /** @var array UNIX timestamps */
60 protected $connFailureTimes = [];
61 /** @var array Exceptions */
62 protected $connFailureErrors = [];
65 * Constructor. Parameters are:
66 * - server: A server info structure in the format required by each
67 * element in $wgDBServers.
69 * - servers: An array of server info structures describing a set of database servers
70 * to distribute keys to. If this is specified, the "server" option will be
71 * ignored. If string keys are used, then they will be used for consistent
72 * hashing *instead* of the host name (from the server config). This is useful
73 * when a cluster is replicated to another site (with different host names)
74 * but each server has a corresponding replica in the other cluster.
76 * - purgePeriod: The average number of object cache requests in between
77 * garbage collection operations, where expired entries
78 * are removed from the database. Or in other words, the
79 * reciprocal of the probability of purging on any given
80 * request. If this is set to zero, purging will never be
83 * - tableName: The table name to use, default is "objectcache".
85 * - shards: The number of tables to use for data storage on each server.
86 * If this is more than 1, table names will be formed in the style
87 * objectcacheNNN where NNN is the shard index, between 0 and
88 * shards-1. The number of digits will be the minimum number
89 * required to hold the largest shard index. Data will be
90 * distributed across all tables by key hash. This is for
91 * MySQL bugs 61735 and 61736.
92 * - slaveOnly: Whether to only use replica DBs and avoid triggering
93 * garbage collection logic of expired items. This only
94 * makes sense if the primary DB is used and only if get()
95 * calls will be used. This is used by ReplicatedBagOStuff.
96 * - syncTimeout: Max seconds to wait for replica DBs to catch up for WRITE_SYNC.
98 * @param array $params
100 public function __construct( $params ) {
101 parent
::__construct( $params );
103 $this->attrMap
[self
::ATTR_EMULATION
] = self
::QOS_EMULATION_SQL
;
104 $this->attrMap
[self
::ATTR_SYNCWRITES
] = self
::QOS_SYNCWRITES_NONE
;
106 if ( isset( $params['servers'] ) ) {
107 $this->serverInfos
= [];
108 $this->serverTags
= [];
109 $this->numServers
= count( $params['servers'] );
111 foreach ( $params['servers'] as $tag => $info ) {
112 $this->serverInfos
[$index] = $info;
113 if ( is_string( $tag ) ) {
114 $this->serverTags
[$index] = $tag;
116 $this->serverTags
[$index] = isset( $info['host'] ) ?
$info['host'] : "#$index";
120 } elseif ( isset( $params['server'] ) ) {
121 $this->serverInfos
= [ $params['server'] ];
122 $this->numServers
= count( $this->serverInfos
);
124 // Default to using the main wiki's database servers
125 $this->serverInfos
= false;
126 $this->numServers
= 1;
127 $this->attrMap
[self
::ATTR_SYNCWRITES
] = self
::QOS_SYNCWRITES_BE
;
129 if ( isset( $params['purgePeriod'] ) ) {
130 $this->purgePeriod
= intval( $params['purgePeriod'] );
132 if ( isset( $params['tableName'] ) ) {
133 $this->tableName
= $params['tableName'];
135 if ( isset( $params['shards'] ) ) {
136 $this->shards
= intval( $params['shards'] );
138 if ( isset( $params['syncTimeout'] ) ) {
139 $this->syncTimeout
= $params['syncTimeout'];
141 $this->replicaOnly
= !empty( $params['slaveOnly'] );
144 protected function getSeparateMainLB() {
147 if ( $wgDBtype === 'mysql' && $this->usesMainDB() ) {
148 if ( !$this->separateMainLB
) {
149 // We must keep a separate connection to MySQL in order to avoid deadlocks
150 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
151 $this->separateMainLB
= $lbFactory->newMainLB();
153 return $this->separateMainLB
;
155 // However, SQLite has an opposite behavior. And PostgreSQL needs to know
156 // if we are in transaction or not (@TODO: find some PostgreSQL work-around).
162 * Get a connection to the specified database
164 * @param int $serverIndex
166 * @throws MWException
168 protected function getDB( $serverIndex ) {
169 if ( !isset( $this->conns
[$serverIndex] ) ) {
170 if ( $serverIndex >= $this->numServers
) {
171 throw new MWException( __METHOD__
. ": Invalid server index \"$serverIndex\"" );
174 # Don't keep timing out trying to connect for each call if the DB is down
175 if ( isset( $this->connFailureErrors
[$serverIndex] )
176 && ( time() - $this->connFailureTimes
[$serverIndex] ) < 60
178 throw $this->connFailureErrors
[$serverIndex];
181 # If server connection info was given, use that
182 if ( $this->serverInfos
) {
183 $info = $this->serverInfos
[$serverIndex];
184 $type = isset( $info['type'] ) ?
$info['type'] : 'mysql';
185 $host = isset( $info['host'] ) ?
$info['host'] : '[unknown]';
186 $this->logger
->debug( __CLASS__
. ": connecting to $host" );
187 // Use a blank trx profiler to ignore expections as this is a cache
188 $info['trxProfiler'] = new TransactionProfiler();
189 $db = Database
::factory( $type, $info );
190 $db->clearFlag( DBO_TRX
);
192 $index = $this->replicaOnly ? DB_REPLICA
: DB_MASTER
;
193 if ( $this->getSeparateMainLB() ) {
194 $db = $this->getSeparateMainLB()->getConnection( $index );
195 $db->clearFlag( DBO_TRX
); // auto-commit mode
197 $db = wfGetDB( $index );
198 // Can't mess with transaction rounds (DBO_TRX) :(
201 $this->logger
->debug( sprintf( "Connection %s will be used for SqlBagOStuff", $db ) );
202 $this->conns
[$serverIndex] = $db;
205 return $this->conns
[$serverIndex];
209 * Get the server index and table name for a given key
211 * @return array Server index and table name
213 protected function getTableByKey( $key ) {
214 if ( $this->shards
> 1 ) {
215 $hash = hexdec( substr( md5( $key ), 0, 8 ) ) & 0x7fffffff;
216 $tableIndex = $hash %
$this->shards
;
220 if ( $this->numServers
> 1 ) {
221 $sortedServers = $this->serverTags
;
222 ArrayUtils
::consistentHashSort( $sortedServers, $key );
223 reset( $sortedServers );
224 $serverIndex = key( $sortedServers );
228 return [ $serverIndex, $this->getTableNameByShard( $tableIndex ) ];
232 * Get the table name for a given shard index
236 protected function getTableNameByShard( $index ) {
237 if ( $this->shards
> 1 ) {
238 $decimals = strlen( $this->shards
- 1 );
239 return $this->tableName
.
240 sprintf( "%0{$decimals}d", $index );
242 return $this->tableName
;
246 protected function doGet( $key, $flags = 0 ) {
249 return $this->getWithToken( $key, $casToken, $flags );
252 protected function getWithToken( $key, &$casToken, $flags = 0 ) {
253 $values = $this->getMulti( [ $key ] );
254 if ( array_key_exists( $key, $values ) ) {
255 $casToken = $values[$key];
256 return $values[$key];
261 public function getMulti( array $keys, $flags = 0 ) {
262 $values = []; // array of (key => value)
265 foreach ( $keys as $key ) {
266 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
267 $keysByTable[$serverIndex][$tableName][] = $key;
270 $this->garbageCollect(); // expire old entries if any
273 foreach ( $keysByTable as $serverIndex => $serverKeys ) {
275 $db = $this->getDB( $serverIndex );
276 foreach ( $serverKeys as $tableName => $tableKeys ) {
277 $res = $db->select( $tableName,
278 [ 'keyname', 'value', 'exptime' ],
279 [ 'keyname' => $tableKeys ],
281 // Approximate write-on-the-fly BagOStuff API via blocking.
282 // This approximation fails if a ROLLBACK happens (which is rare).
283 // We do not want to flush the TRX as that can break callers.
284 $db->trxLevel() ?
[ 'LOCK IN SHARE MODE' ] : []
286 if ( $res === false ) {
289 foreach ( $res as $row ) {
290 $row->serverIndex
= $serverIndex;
291 $row->tableName
= $tableName;
292 $dataRows[$row->keyname
] = $row;
295 } catch ( DBError
$e ) {
296 $this->handleReadError( $e, $serverIndex );
300 foreach ( $keys as $key ) {
301 if ( isset( $dataRows[$key] ) ) { // HIT?
302 $row = $dataRows[$key];
303 $this->debug( "get: retrieved data; expiry time is " . $row->exptime
);
306 $db = $this->getDB( $row->serverIndex
);
307 if ( $this->isExpired( $db, $row->exptime
) ) { // MISS
308 $this->debug( "get: key has expired" );
310 $values[$key] = $this->unserialize( $db->decodeBlob( $row->value
) );
312 } catch ( DBQueryError
$e ) {
313 $this->handleWriteError( $e, $db, $row->serverIndex
);
316 $this->debug( 'get: no matching rows' );
323 public function setMulti( array $data, $expiry = 0 ) {
325 foreach ( $data as $key => $value ) {
326 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
327 $keysByTable[$serverIndex][$tableName][] = $key;
330 $this->garbageCollect(); // expire old entries if any
333 $exptime = (int)$expiry;
334 foreach ( $keysByTable as $serverIndex => $serverKeys ) {
337 $db = $this->getDB( $serverIndex );
338 } catch ( DBError
$e ) {
339 $this->handleWriteError( $e, $db, $serverIndex );
344 if ( $exptime < 0 ) {
348 if ( $exptime == 0 ) {
349 $encExpiry = $this->getMaxDateTime( $db );
351 $exptime = $this->convertExpiry( $exptime );
352 $encExpiry = $db->timestamp( $exptime );
354 foreach ( $serverKeys as $tableName => $tableKeys ) {
356 foreach ( $tableKeys as $key ) {
359 'value' => $db->encodeBlob( $this->serialize( $data[$key] ) ),
360 'exptime' => $encExpiry,
371 } catch ( DBError
$e ) {
372 $this->handleWriteError( $e, $db, $serverIndex );
383 public function set( $key, $value, $exptime = 0, $flags = 0 ) {
384 $ok = $this->setMulti( [ $key => $value ], $exptime );
385 if ( ( $flags & self
::WRITE_SYNC
) == self
::WRITE_SYNC
) {
386 $ok = $this->waitForReplication() && $ok;
392 protected function cas( $casToken, $key, $value, $exptime = 0 ) {
393 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
396 $db = $this->getDB( $serverIndex );
397 $exptime = intval( $exptime );
399 if ( $exptime < 0 ) {
403 if ( $exptime == 0 ) {
404 $encExpiry = $this->getMaxDateTime( $db );
406 $exptime = $this->convertExpiry( $exptime );
407 $encExpiry = $db->timestamp( $exptime );
409 // (T26425) use a replace if the db supports it instead of
410 // delete/insert to avoid clashes with conflicting keynames
415 'value' => $db->encodeBlob( $this->serialize( $value ) ),
416 'exptime' => $encExpiry
420 'value' => $db->encodeBlob( $this->serialize( $casToken ) )
424 } catch ( DBQueryError
$e ) {
425 $this->handleWriteError( $e, $db, $serverIndex );
430 return (bool)$db->affectedRows();
433 public function delete( $key ) {
434 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
437 $db = $this->getDB( $serverIndex );
440 [ 'keyname' => $key ],
442 } catch ( DBError
$e ) {
443 $this->handleWriteError( $e, $db, $serverIndex );
450 public function incr( $key, $step = 1 ) {
451 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
454 $db = $this->getDB( $serverIndex );
455 $step = intval( $step );
456 $row = $db->selectRow(
458 [ 'value', 'exptime' ],
459 [ 'keyname' => $key ],
462 if ( $row === false ) {
467 $db->delete( $tableName, [ 'keyname' => $key ], __METHOD__
);
468 if ( $this->isExpired( $db, $row->exptime
) ) {
469 // Expired, do not reinsert
474 $oldValue = intval( $this->unserialize( $db->decodeBlob( $row->value
) ) );
475 $newValue = $oldValue +
$step;
476 $db->insert( $tableName,
479 'value' => $db->encodeBlob( $this->serialize( $newValue ) ),
480 'exptime' => $row->exptime
481 ], __METHOD__
, 'IGNORE' );
483 if ( $db->affectedRows() == 0 ) {
484 // Race condition. See T30611
487 } catch ( DBError
$e ) {
488 $this->handleWriteError( $e, $db, $serverIndex );
495 public function merge( $key, callable
$callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
496 $ok = $this->mergeViaCas( $key, $callback, $exptime, $attempts );
497 if ( ( $flags & self
::WRITE_SYNC
) == self
::WRITE_SYNC
) {
498 $ok = $this->waitForReplication() && $ok;
504 public function changeTTL( $key, $expiry = 0 ) {
505 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
508 $db = $this->getDB( $serverIndex );
511 [ 'exptime' => $db->timestamp( $this->convertExpiry( $expiry ) ) ],
512 [ 'keyname' => $key, 'exptime > ' . $db->addQuotes( $db->timestamp( time() ) ) ],
515 if ( $db->affectedRows() == 0 ) {
518 } catch ( DBError
$e ) {
519 $this->handleWriteError( $e, $db, $serverIndex );
527 * @param IDatabase $db
528 * @param string $exptime
531 protected function isExpired( $db, $exptime ) {
532 return $exptime != $this->getMaxDateTime( $db ) && wfTimestamp( TS_UNIX
, $exptime ) < time();
536 * @param IDatabase $db
539 protected function getMaxDateTime( $db ) {
540 if ( time() > 0x7fffffff ) {
541 return $db->timestamp( 1 << 62 );
543 return $db->timestamp( 0x7fffffff );
547 protected function garbageCollect() {
548 if ( !$this->purgePeriod ||
$this->replicaOnly
) {
552 // Only purge on one in every $this->purgePeriod requests.
553 if ( $this->purgePeriod
!== 1 && mt_rand( 0, $this->purgePeriod
- 1 ) ) {
557 // Avoid repeating the delete within a few seconds
558 if ( $now > ( $this->lastExpireAll +
1 ) ) {
559 $this->lastExpireAll
= $now;
564 public function expireAll() {
565 $this->deleteObjectsExpiringBefore( wfTimestampNow() );
569 * Delete objects from the database which expire before a certain date.
570 * @param string $timestamp
571 * @param bool|callable $progressCallback
574 public function deleteObjectsExpiringBefore( $timestamp, $progressCallback = false ) {
575 for ( $serverIndex = 0; $serverIndex < $this->numServers
; $serverIndex++
) {
578 $db = $this->getDB( $serverIndex );
579 $dbTimestamp = $db->timestamp( $timestamp );
580 $totalSeconds = false;
581 $baseConds = [ 'exptime < ' . $db->addQuotes( $dbTimestamp ) ];
582 for ( $i = 0; $i < $this->shards
; $i++
) {
586 if ( $maxExpTime !== false ) {
587 $conds[] = 'exptime > ' . $db->addQuotes( $maxExpTime );
590 $this->getTableNameByShard( $i ),
591 [ 'keyname', 'exptime' ],
594 [ 'LIMIT' => 100, 'ORDER BY' => 'exptime' ] );
595 if ( $rows === false ||
!$rows->numRows() ) {
599 $row = $rows->current();
600 $minExpTime = $row->exptime
;
601 if ( $totalSeconds === false ) {
602 $totalSeconds = wfTimestamp( TS_UNIX
, $timestamp )
603 - wfTimestamp( TS_UNIX
, $minExpTime );
605 foreach ( $rows as $row ) {
606 $keys[] = $row->keyname
;
607 $maxExpTime = $row->exptime
;
611 $this->getTableNameByShard( $i ),
613 'exptime >= ' . $db->addQuotes( $minExpTime ),
614 'exptime < ' . $db->addQuotes( $dbTimestamp ),
619 if ( $progressCallback ) {
620 if ( intval( $totalSeconds ) === 0 ) {
623 $remainingSeconds = wfTimestamp( TS_UNIX
, $timestamp )
624 - wfTimestamp( TS_UNIX
, $maxExpTime );
625 if ( $remainingSeconds > $totalSeconds ) {
626 $totalSeconds = $remainingSeconds;
628 $processedSeconds = $totalSeconds - $remainingSeconds;
629 $percent = ( $i +
$processedSeconds / $totalSeconds )
630 / $this->shards
* 100;
632 $percent = ( $percent / $this->numServers
)
633 +
( $serverIndex / $this->numServers
* 100 );
634 call_user_func( $progressCallback, $percent );
638 } catch ( DBError
$e ) {
639 $this->handleWriteError( $e, $db, $serverIndex );
647 * Delete content of shard tables in every server.
648 * Return true if the operation is successful, false otherwise.
651 public function deleteAll() {
652 for ( $serverIndex = 0; $serverIndex < $this->numServers
; $serverIndex++
) {
655 $db = $this->getDB( $serverIndex );
656 for ( $i = 0; $i < $this->shards
; $i++
) {
657 $db->delete( $this->getTableNameByShard( $i ), '*', __METHOD__
);
659 } catch ( DBError
$e ) {
660 $this->handleWriteError( $e, $db, $serverIndex );
668 * Serialize an object and, if possible, compress the representation.
669 * On typical message and page data, this can provide a 3X decrease
670 * in storage requirements.
675 protected function serialize( &$data ) {
676 $serial = serialize( $data );
678 if ( function_exists( 'gzdeflate' ) ) {
679 return gzdeflate( $serial );
686 * Unserialize and, if necessary, decompress an object.
687 * @param string $serial
690 protected function unserialize( $serial ) {
691 if ( function_exists( 'gzinflate' ) ) {
692 MediaWiki\
suppressWarnings();
693 $decomp = gzinflate( $serial );
694 MediaWiki\restoreWarnings
();
696 if ( false !== $decomp ) {
701 $ret = unserialize( $serial );
707 * Handle a DBError which occurred during a read operation.
709 * @param DBError $exception
710 * @param int $serverIndex
712 protected function handleReadError( DBError
$exception, $serverIndex ) {
713 if ( $exception instanceof DBConnectionError
) {
714 $this->markServerDown( $exception, $serverIndex );
716 $this->logger
->error( "DBError: {$exception->getMessage()}" );
717 if ( $exception instanceof DBConnectionError
) {
718 $this->setLastError( BagOStuff
::ERR_UNREACHABLE
);
719 $this->logger
->debug( __METHOD__
. ": ignoring connection error" );
721 $this->setLastError( BagOStuff
::ERR_UNEXPECTED
);
722 $this->logger
->debug( __METHOD__
. ": ignoring query error" );
727 * Handle a DBQueryError which occurred during a write operation.
729 * @param DBError $exception
730 * @param IDatabase|null $db DB handle or null if connection failed
731 * @param int $serverIndex
734 protected function handleWriteError( DBError
$exception, IDatabase
$db = null, $serverIndex ) {
736 $this->markServerDown( $exception, $serverIndex );
737 } elseif ( $db->wasReadOnlyError() ) {
738 if ( $db->trxLevel() && $this->usesMainDB() ) {
739 // Errors like deadlocks and connection drops already cause rollback.
740 // For consistency, we have no choice but to throw an error and trigger
741 // complete rollback if the main DB is also being used as the cache DB.
746 $this->logger
->error( "DBError: {$exception->getMessage()}" );
747 if ( $exception instanceof DBConnectionError
) {
748 $this->setLastError( BagOStuff
::ERR_UNREACHABLE
);
749 $this->logger
->debug( __METHOD__
. ": ignoring connection error" );
751 $this->setLastError( BagOStuff
::ERR_UNEXPECTED
);
752 $this->logger
->debug( __METHOD__
. ": ignoring query error" );
757 * Mark a server down due to a DBConnectionError exception
759 * @param DBError $exception
760 * @param int $serverIndex
762 protected function markServerDown( DBError
$exception, $serverIndex ) {
763 unset( $this->conns
[$serverIndex] ); // bug T103435
765 if ( isset( $this->connFailureTimes
[$serverIndex] ) ) {
766 if ( time() - $this->connFailureTimes
[$serverIndex] >= 60 ) {
767 unset( $this->connFailureTimes
[$serverIndex] );
768 unset( $this->connFailureErrors
[$serverIndex] );
770 $this->logger
->debug( __METHOD__
. ": Server #$serverIndex already down" );
775 $this->logger
->info( __METHOD__
. ": Server #$serverIndex down until " . ( $now +
60 ) );
776 $this->connFailureTimes
[$serverIndex] = $now;
777 $this->connFailureErrors
[$serverIndex] = $exception;
781 * Create shard tables. For use from eval.php.
783 public function createTables() {
784 for ( $serverIndex = 0; $serverIndex < $this->numServers
; $serverIndex++
) {
785 $db = $this->getDB( $serverIndex );
786 if ( $db->getType() !== 'mysql' ) {
787 throw new MWException( __METHOD__
. ' is not supported on this DB server' );
790 for ( $i = 0; $i < $this->shards
; $i++
) {
792 'CREATE TABLE ' . $db->tableName( $this->getTableNameByShard( $i ) ) .
793 ' LIKE ' . $db->tableName( 'objectcache' ),
800 * @return bool Whether the main DB is used, e.g. wfGetDB( DB_MASTER )
802 protected function usesMainDB() {
803 return !$this->serverInfos
;
806 protected function waitForReplication() {
807 if ( !$this->usesMainDB() ) {
808 // Custom DB server list; probably doesn't use replication
812 $lb = $this->getSeparateMainLB()
813 ?
: MediaWikiServices
::getInstance()->getDBLoadBalancer();
815 if ( $lb->getServerCount() <= 1 ) {
816 return true; // no replica DBs
819 // Main LB is used; wait for any replica DBs to catch up
820 $masterPos = $lb->getMasterPos();
822 $loop = new WaitConditionLoop(
823 function () use ( $lb, $masterPos ) {
824 return $lb->waitForAll( $masterPos, 1 );
830 return ( $loop->invoke() === $loop::CONDITION_REACHED
);