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 \MediaWiki\MediaWikiServices
;
25 use \Wikimedia\WaitConditionLoop
;
28 * Class to store objects in the database
32 class SqlBagOStuff
extends BagOStuff
{
33 /** @var array[] (server index => server config) */
34 protected $serverInfos;
35 /** @var string[] (server index => tag/host name) */
36 protected $serverTags;
38 protected $numServers;
40 protected $lastExpireAll = 0;
42 protected $purgePeriod = 100;
44 protected $shards = 1;
46 protected $tableName = 'objectcache';
48 protected $replicaOnly = false;
50 protected $syncTimeout = 3;
52 /** @var LoadBalancer|null */
53 protected $separateMainLB;
56 /** @var array UNIX timestamps */
57 protected $connFailureTimes = [];
58 /** @var array Exceptions */
59 protected $connFailureErrors = [];
62 * Constructor. Parameters are:
63 * - server: A server info structure in the format required by each
64 * element in $wgDBServers.
66 * - servers: An array of server info structures describing a set of database servers
67 * to distribute keys to. If this is specified, the "server" option will be
68 * ignored. If string keys are used, then they will be used for consistent
69 * hashing *instead* of the host name (from the server config). This is useful
70 * when a cluster is replicated to another site (with different host names)
71 * but each server has a corresponding replica in the other cluster.
73 * - purgePeriod: The average number of object cache requests in between
74 * garbage collection operations, where expired entries
75 * are removed from the database. Or in other words, the
76 * reciprocal of the probability of purging on any given
77 * request. If this is set to zero, purging will never be
80 * - tableName: The table name to use, default is "objectcache".
82 * - shards: The number of tables to use for data storage on each server.
83 * If this is more than 1, table names will be formed in the style
84 * objectcacheNNN where NNN is the shard index, between 0 and
85 * shards-1. The number of digits will be the minimum number
86 * required to hold the largest shard index. Data will be
87 * distributed across all tables by key hash. This is for
88 * MySQL bugs 61735 and 61736.
89 * - slaveOnly: Whether to only use replica DBs and avoid triggering
90 * garbage collection logic of expired items. This only
91 * makes sense if the primary DB is used and only if get()
92 * calls will be used. This is used by ReplicatedBagOStuff.
93 * - syncTimeout: Max seconds to wait for replica DBs to catch up for WRITE_SYNC.
95 * @param array $params
97 public function __construct( $params ) {
98 parent
::__construct( $params );
100 $this->attrMap
[self
::ATTR_EMULATION
] = self
::QOS_EMULATION_SQL
;
101 $this->attrMap
[self
::ATTR_SYNCWRITES
] = self
::QOS_SYNCWRITES_NONE
;
103 if ( isset( $params['servers'] ) ) {
104 $this->serverInfos
= [];
105 $this->serverTags
= [];
106 $this->numServers
= count( $params['servers'] );
108 foreach ( $params['servers'] as $tag => $info ) {
109 $this->serverInfos
[$index] = $info;
110 if ( is_string( $tag ) ) {
111 $this->serverTags
[$index] = $tag;
113 $this->serverTags
[$index] = isset( $info['host'] ) ?
$info['host'] : "#$index";
117 } elseif ( isset( $params['server'] ) ) {
118 $this->serverInfos
= [ $params['server'] ];
119 $this->numServers
= count( $this->serverInfos
);
121 // Default to using the main wiki's database servers
122 $this->serverInfos
= false;
123 $this->numServers
= 1;
124 $this->attrMap
[self
::ATTR_SYNCWRITES
] = self
::QOS_SYNCWRITES_BE
;
126 if ( isset( $params['purgePeriod'] ) ) {
127 $this->purgePeriod
= intval( $params['purgePeriod'] );
129 if ( isset( $params['tableName'] ) ) {
130 $this->tableName
= $params['tableName'];
132 if ( isset( $params['shards'] ) ) {
133 $this->shards
= intval( $params['shards'] );
135 if ( isset( $params['syncTimeout'] ) ) {
136 $this->syncTimeout
= $params['syncTimeout'];
138 $this->replicaOnly
= !empty( $params['slaveOnly'] );
141 protected function getSeparateMainLB() {
144 if ( $wgDBtype === 'mysql' && $this->usesMainDB() ) {
145 if ( !$this->separateMainLB
) {
146 // We must keep a separate connection to MySQL in order to avoid deadlocks
147 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
148 $this->separateMainLB
= $lbFactory->newMainLB();
150 return $this->separateMainLB
;
152 // However, SQLite has an opposite behavior. And PostgreSQL needs to know
153 // if we are in transaction or not (@TODO: find some PostgreSQL work-around).
159 * Get a connection to the specified database
161 * @param int $serverIndex
163 * @throws MWException
165 protected function getDB( $serverIndex ) {
166 if ( !isset( $this->conns
[$serverIndex] ) ) {
167 if ( $serverIndex >= $this->numServers
) {
168 throw new MWException( __METHOD__
. ": Invalid server index \"$serverIndex\"" );
171 # Don't keep timing out trying to connect for each call if the DB is down
172 if ( isset( $this->connFailureErrors
[$serverIndex] )
173 && ( time() - $this->connFailureTimes
[$serverIndex] ) < 60
175 throw $this->connFailureErrors
[$serverIndex];
178 # If server connection info was given, use that
179 if ( $this->serverInfos
) {
180 $info = $this->serverInfos
[$serverIndex];
181 $type = isset( $info['type'] ) ?
$info['type'] : 'mysql';
182 $host = isset( $info['host'] ) ?
$info['host'] : '[unknown]';
183 $this->logger
->debug( __CLASS__
. ": connecting to $host" );
184 // Use a blank trx profiler to ignore expections as this is a cache
185 $info['trxProfiler'] = new TransactionProfiler();
186 $db = Database
::factory( $type, $info );
187 $db->clearFlag( DBO_TRX
);
189 $index = $this->replicaOnly ? DB_REPLICA
: DB_MASTER
;
190 if ( $this->getSeparateMainLB() ) {
191 $db = $this->getSeparateMainLB()->getConnection( $index );
192 $db->clearFlag( DBO_TRX
); // auto-commit mode
194 $db = wfGetDB( $index );
195 // Can't mess with transaction rounds (DBO_TRX) :(
198 $this->logger
->debug( sprintf( "Connection %s will be used for SqlBagOStuff", $db ) );
199 $this->conns
[$serverIndex] = $db;
202 return $this->conns
[$serverIndex];
206 * Get the server index and table name for a given key
208 * @return array Server index and table name
210 protected function getTableByKey( $key ) {
211 if ( $this->shards
> 1 ) {
212 $hash = hexdec( substr( md5( $key ), 0, 8 ) ) & 0x7fffffff;
213 $tableIndex = $hash %
$this->shards
;
217 if ( $this->numServers
> 1 ) {
218 $sortedServers = $this->serverTags
;
219 ArrayUtils
::consistentHashSort( $sortedServers, $key );
220 reset( $sortedServers );
221 $serverIndex = key( $sortedServers );
225 return [ $serverIndex, $this->getTableNameByShard( $tableIndex ) ];
229 * Get the table name for a given shard index
233 protected function getTableNameByShard( $index ) {
234 if ( $this->shards
> 1 ) {
235 $decimals = strlen( $this->shards
- 1 );
236 return $this->tableName
.
237 sprintf( "%0{$decimals}d", $index );
239 return $this->tableName
;
243 protected function doGet( $key, $flags = 0 ) {
246 return $this->getWithToken( $key, $casToken, $flags );
249 protected function getWithToken( $key, &$casToken, $flags = 0 ) {
250 $values = $this->getMulti( [ $key ] );
251 if ( array_key_exists( $key, $values ) ) {
252 $casToken = $values[$key];
253 return $values[$key];
258 public function getMulti( array $keys, $flags = 0 ) {
259 $values = []; // array of (key => value)
262 foreach ( $keys as $key ) {
263 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
264 $keysByTable[$serverIndex][$tableName][] = $key;
267 $this->garbageCollect(); // expire old entries if any
270 foreach ( $keysByTable as $serverIndex => $serverKeys ) {
272 $db = $this->getDB( $serverIndex );
273 foreach ( $serverKeys as $tableName => $tableKeys ) {
274 $res = $db->select( $tableName,
275 [ 'keyname', 'value', 'exptime' ],
276 [ 'keyname' => $tableKeys ],
278 // Approximate write-on-the-fly BagOStuff API via blocking.
279 // This approximation fails if a ROLLBACK happens (which is rare).
280 // We do not want to flush the TRX as that can break callers.
281 $db->trxLevel() ?
[ 'LOCK IN SHARE MODE' ] : []
283 if ( $res === false ) {
286 foreach ( $res as $row ) {
287 $row->serverIndex
= $serverIndex;
288 $row->tableName
= $tableName;
289 $dataRows[$row->keyname
] = $row;
292 } catch ( DBError
$e ) {
293 $this->handleReadError( $e, $serverIndex );
297 foreach ( $keys as $key ) {
298 if ( isset( $dataRows[$key] ) ) { // HIT?
299 $row = $dataRows[$key];
300 $this->debug( "get: retrieved data; expiry time is " . $row->exptime
);
303 $db = $this->getDB( $row->serverIndex
);
304 if ( $this->isExpired( $db, $row->exptime
) ) { // MISS
305 $this->debug( "get: key has expired" );
307 $values[$key] = $this->unserialize( $db->decodeBlob( $row->value
) );
309 } catch ( DBQueryError
$e ) {
310 $this->handleWriteError( $e, $db, $row->serverIndex
);
313 $this->debug( 'get: no matching rows' );
320 public function setMulti( array $data, $expiry = 0 ) {
322 foreach ( $data as $key => $value ) {
323 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
324 $keysByTable[$serverIndex][$tableName][] = $key;
327 $this->garbageCollect(); // expire old entries if any
330 $exptime = (int)$expiry;
331 foreach ( $keysByTable as $serverIndex => $serverKeys ) {
334 $db = $this->getDB( $serverIndex );
335 } catch ( DBError
$e ) {
336 $this->handleWriteError( $e, $db, $serverIndex );
341 if ( $exptime < 0 ) {
345 if ( $exptime == 0 ) {
346 $encExpiry = $this->getMaxDateTime( $db );
348 $exptime = $this->convertExpiry( $exptime );
349 $encExpiry = $db->timestamp( $exptime );
351 foreach ( $serverKeys as $tableName => $tableKeys ) {
353 foreach ( $tableKeys as $key ) {
356 'value' => $db->encodeBlob( $this->serialize( $data[$key] ) ),
357 'exptime' => $encExpiry,
368 } catch ( DBError
$e ) {
369 $this->handleWriteError( $e, $db, $serverIndex );
380 public function set( $key, $value, $exptime = 0, $flags = 0 ) {
381 $ok = $this->setMulti( [ $key => $value ], $exptime );
382 if ( ( $flags & self
::WRITE_SYNC
) == self
::WRITE_SYNC
) {
383 $ok = $this->waitForReplication() && $ok;
389 protected function cas( $casToken, $key, $value, $exptime = 0 ) {
390 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
393 $db = $this->getDB( $serverIndex );
394 $exptime = intval( $exptime );
396 if ( $exptime < 0 ) {
400 if ( $exptime == 0 ) {
401 $encExpiry = $this->getMaxDateTime( $db );
403 $exptime = $this->convertExpiry( $exptime );
404 $encExpiry = $db->timestamp( $exptime );
406 // (bug 24425) use a replace if the db supports it instead of
407 // delete/insert to avoid clashes with conflicting keynames
412 'value' => $db->encodeBlob( $this->serialize( $value ) ),
413 'exptime' => $encExpiry
417 'value' => $db->encodeBlob( $this->serialize( $casToken ) )
421 } catch ( DBQueryError
$e ) {
422 $this->handleWriteError( $e, $db, $serverIndex );
427 return (bool)$db->affectedRows();
430 public function delete( $key ) {
431 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
434 $db = $this->getDB( $serverIndex );
437 [ 'keyname' => $key ],
439 } catch ( DBError
$e ) {
440 $this->handleWriteError( $e, $db, $serverIndex );
447 public function incr( $key, $step = 1 ) {
448 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
451 $db = $this->getDB( $serverIndex );
452 $step = intval( $step );
453 $row = $db->selectRow(
455 [ 'value', 'exptime' ],
456 [ 'keyname' => $key ],
459 if ( $row === false ) {
464 $db->delete( $tableName, [ 'keyname' => $key ], __METHOD__
);
465 if ( $this->isExpired( $db, $row->exptime
) ) {
466 // Expired, do not reinsert
471 $oldValue = intval( $this->unserialize( $db->decodeBlob( $row->value
) ) );
472 $newValue = $oldValue +
$step;
473 $db->insert( $tableName,
476 'value' => $db->encodeBlob( $this->serialize( $newValue ) ),
477 'exptime' => $row->exptime
478 ], __METHOD__
, 'IGNORE' );
480 if ( $db->affectedRows() == 0 ) {
481 // Race condition. See bug 28611
484 } catch ( DBError
$e ) {
485 $this->handleWriteError( $e, $db, $serverIndex );
492 public function merge( $key, callable
$callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
493 $ok = $this->mergeViaCas( $key, $callback, $exptime, $attempts );
494 if ( ( $flags & self
::WRITE_SYNC
) == self
::WRITE_SYNC
) {
495 $ok = $this->waitForReplication() && $ok;
501 public function changeTTL( $key, $expiry = 0 ) {
502 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
505 $db = $this->getDB( $serverIndex );
508 [ 'exptime' => $db->timestamp( $this->convertExpiry( $expiry ) ) ],
509 [ 'keyname' => $key, 'exptime > ' . $db->addQuotes( $db->timestamp( time() ) ) ],
512 if ( $db->affectedRows() == 0 ) {
515 } catch ( DBError
$e ) {
516 $this->handleWriteError( $e, $db, $serverIndex );
524 * @param IDatabase $db
525 * @param string $exptime
528 protected function isExpired( $db, $exptime ) {
529 return $exptime != $this->getMaxDateTime( $db ) && wfTimestamp( TS_UNIX
, $exptime ) < time();
533 * @param IDatabase $db
536 protected function getMaxDateTime( $db ) {
537 if ( time() > 0x7fffffff ) {
538 return $db->timestamp( 1 << 62 );
540 return $db->timestamp( 0x7fffffff );
544 protected function garbageCollect() {
545 if ( !$this->purgePeriod ||
$this->replicaOnly
) {
549 // Only purge on one in every $this->purgePeriod requests.
550 if ( $this->purgePeriod
!== 1 && mt_rand( 0, $this->purgePeriod
- 1 ) ) {
554 // Avoid repeating the delete within a few seconds
555 if ( $now > ( $this->lastExpireAll +
1 ) ) {
556 $this->lastExpireAll
= $now;
561 public function expireAll() {
562 $this->deleteObjectsExpiringBefore( wfTimestampNow() );
566 * Delete objects from the database which expire before a certain date.
567 * @param string $timestamp
568 * @param bool|callable $progressCallback
571 public function deleteObjectsExpiringBefore( $timestamp, $progressCallback = false ) {
572 for ( $serverIndex = 0; $serverIndex < $this->numServers
; $serverIndex++
) {
575 $db = $this->getDB( $serverIndex );
576 $dbTimestamp = $db->timestamp( $timestamp );
577 $totalSeconds = false;
578 $baseConds = [ 'exptime < ' . $db->addQuotes( $dbTimestamp ) ];
579 for ( $i = 0; $i < $this->shards
; $i++
) {
583 if ( $maxExpTime !== false ) {
584 $conds[] = 'exptime > ' . $db->addQuotes( $maxExpTime );
587 $this->getTableNameByShard( $i ),
588 [ 'keyname', 'exptime' ],
591 [ 'LIMIT' => 100, 'ORDER BY' => 'exptime' ] );
592 if ( $rows === false ||
!$rows->numRows() ) {
596 $row = $rows->current();
597 $minExpTime = $row->exptime
;
598 if ( $totalSeconds === false ) {
599 $totalSeconds = wfTimestamp( TS_UNIX
, $timestamp )
600 - wfTimestamp( TS_UNIX
, $minExpTime );
602 foreach ( $rows as $row ) {
603 $keys[] = $row->keyname
;
604 $maxExpTime = $row->exptime
;
608 $this->getTableNameByShard( $i ),
610 'exptime >= ' . $db->addQuotes( $minExpTime ),
611 'exptime < ' . $db->addQuotes( $dbTimestamp ),
616 if ( $progressCallback ) {
617 if ( intval( $totalSeconds ) === 0 ) {
620 $remainingSeconds = wfTimestamp( TS_UNIX
, $timestamp )
621 - wfTimestamp( TS_UNIX
, $maxExpTime );
622 if ( $remainingSeconds > $totalSeconds ) {
623 $totalSeconds = $remainingSeconds;
625 $processedSeconds = $totalSeconds - $remainingSeconds;
626 $percent = ( $i +
$processedSeconds / $totalSeconds )
627 / $this->shards
* 100;
629 $percent = ( $percent / $this->numServers
)
630 +
( $serverIndex / $this->numServers
* 100 );
631 call_user_func( $progressCallback, $percent );
635 } catch ( DBError
$e ) {
636 $this->handleWriteError( $e, $db, $serverIndex );
644 * Delete content of shard tables in every server.
645 * Return true if the operation is successful, false otherwise.
648 public function deleteAll() {
649 for ( $serverIndex = 0; $serverIndex < $this->numServers
; $serverIndex++
) {
652 $db = $this->getDB( $serverIndex );
653 for ( $i = 0; $i < $this->shards
; $i++
) {
654 $db->delete( $this->getTableNameByShard( $i ), '*', __METHOD__
);
656 } catch ( DBError
$e ) {
657 $this->handleWriteError( $e, $db, $serverIndex );
665 * Serialize an object and, if possible, compress the representation.
666 * On typical message and page data, this can provide a 3X decrease
667 * in storage requirements.
672 protected function serialize( &$data ) {
673 $serial = serialize( $data );
675 if ( function_exists( 'gzdeflate' ) ) {
676 return gzdeflate( $serial );
683 * Unserialize and, if necessary, decompress an object.
684 * @param string $serial
687 protected function unserialize( $serial ) {
688 if ( function_exists( 'gzinflate' ) ) {
689 MediaWiki\
suppressWarnings();
690 $decomp = gzinflate( $serial );
691 MediaWiki\restoreWarnings
();
693 if ( false !== $decomp ) {
698 $ret = unserialize( $serial );
704 * Handle a DBError which occurred during a read operation.
706 * @param DBError $exception
707 * @param int $serverIndex
709 protected function handleReadError( DBError
$exception, $serverIndex ) {
710 if ( $exception instanceof DBConnectionError
) {
711 $this->markServerDown( $exception, $serverIndex );
713 $this->logger
->error( "DBError: {$exception->getMessage()}" );
714 if ( $exception instanceof DBConnectionError
) {
715 $this->setLastError( BagOStuff
::ERR_UNREACHABLE
);
716 $this->logger
->debug( __METHOD__
. ": ignoring connection error" );
718 $this->setLastError( BagOStuff
::ERR_UNEXPECTED
);
719 $this->logger
->debug( __METHOD__
. ": ignoring query error" );
724 * Handle a DBQueryError which occurred during a write operation.
726 * @param DBError $exception
727 * @param IDatabase|null $db DB handle or null if connection failed
728 * @param int $serverIndex
731 protected function handleWriteError( DBError
$exception, IDatabase
$db = null, $serverIndex ) {
733 $this->markServerDown( $exception, $serverIndex );
734 } elseif ( $db->wasReadOnlyError() ) {
735 if ( $db->trxLevel() && $this->usesMainDB() ) {
736 // Errors like deadlocks and connection drops already cause rollback.
737 // For consistency, we have no choice but to throw an error and trigger
738 // complete rollback if the main DB is also being used as the cache DB.
743 $this->logger
->error( "DBError: {$exception->getMessage()}" );
744 if ( $exception instanceof DBConnectionError
) {
745 $this->setLastError( BagOStuff
::ERR_UNREACHABLE
);
746 $this->logger
->debug( __METHOD__
. ": ignoring connection error" );
748 $this->setLastError( BagOStuff
::ERR_UNEXPECTED
);
749 $this->logger
->debug( __METHOD__
. ": ignoring query error" );
754 * Mark a server down due to a DBConnectionError exception
756 * @param DBError $exception
757 * @param int $serverIndex
759 protected function markServerDown( DBError
$exception, $serverIndex ) {
760 unset( $this->conns
[$serverIndex] ); // bug T103435
762 if ( isset( $this->connFailureTimes
[$serverIndex] ) ) {
763 if ( time() - $this->connFailureTimes
[$serverIndex] >= 60 ) {
764 unset( $this->connFailureTimes
[$serverIndex] );
765 unset( $this->connFailureErrors
[$serverIndex] );
767 $this->logger
->debug( __METHOD__
. ": Server #$serverIndex already down" );
772 $this->logger
->info( __METHOD__
. ": Server #$serverIndex down until " . ( $now +
60 ) );
773 $this->connFailureTimes
[$serverIndex] = $now;
774 $this->connFailureErrors
[$serverIndex] = $exception;
778 * Create shard tables. For use from eval.php.
780 public function createTables() {
781 for ( $serverIndex = 0; $serverIndex < $this->numServers
; $serverIndex++
) {
782 $db = $this->getDB( $serverIndex );
783 if ( $db->getType() !== 'mysql' ) {
784 throw new MWException( __METHOD__
. ' is not supported on this DB server' );
787 for ( $i = 0; $i < $this->shards
; $i++
) {
789 'CREATE TABLE ' . $db->tableName( $this->getTableNameByShard( $i ) ) .
790 ' LIKE ' . $db->tableName( 'objectcache' ),
797 * @return bool Whether the main DB is used, e.g. wfGetDB( DB_MASTER )
799 protected function usesMainDB() {
800 return !$this->serverInfos
;
803 protected function waitForReplication() {
804 if ( !$this->usesMainDB() ) {
805 // Custom DB server list; probably doesn't use replication
809 $lb = $this->getSeparateMainLB()
810 ?
: MediaWikiServices
::getInstance()->getDBLoadBalancer();
812 if ( $lb->getServerCount() <= 1 ) {
813 return true; // no replica DBs
816 // Main LB is used; wait for any replica DBs to catch up
817 $masterPos = $lb->getMasterPos();
819 $loop = new WaitConditionLoop(
820 function () use ( $lb, $masterPos ) {
821 return $lb->waitForAll( $masterPos, 1 );
827 return ( $loop->invoke() === $loop::CONDITION_REACHED
);