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
;
26 use \Wikimedia\Rdbms\TransactionProfiler
;
27 use Wikimedia\Rdbms\LoadBalancer
;
30 * Class to store objects in the database
34 class SqlBagOStuff
extends BagOStuff
{
35 /** @var array[] (server index => server config) */
36 protected $serverInfos;
37 /** @var string[] (server index => tag/host name) */
38 protected $serverTags;
40 protected $numServers;
42 protected $lastExpireAll = 0;
44 protected $purgePeriod = 100;
46 protected $shards = 1;
48 protected $tableName = 'objectcache';
50 protected $replicaOnly = false;
52 protected $syncTimeout = 3;
54 /** @var LoadBalancer|null */
55 protected $separateMainLB;
58 /** @var array UNIX timestamps */
59 protected $connFailureTimes = [];
60 /** @var array Exceptions */
61 protected $connFailureErrors = [];
64 * Constructor. Parameters are:
65 * - server: A server info structure in the format required by each
66 * element in $wgDBServers.
68 * - servers: An array of server info structures describing a set of database servers
69 * to distribute keys to. If this is specified, the "server" option will be
70 * ignored. If string keys are used, then they will be used for consistent
71 * hashing *instead* of the host name (from the server config). This is useful
72 * when a cluster is replicated to another site (with different host names)
73 * but each server has a corresponding replica in the other cluster.
75 * - purgePeriod: The average number of object cache requests in between
76 * garbage collection operations, where expired entries
77 * are removed from the database. Or in other words, the
78 * reciprocal of the probability of purging on any given
79 * request. If this is set to zero, purging will never be
82 * - tableName: The table name to use, default is "objectcache".
84 * - shards: The number of tables to use for data storage on each server.
85 * If this is more than 1, table names will be formed in the style
86 * objectcacheNNN where NNN is the shard index, between 0 and
87 * shards-1. The number of digits will be the minimum number
88 * required to hold the largest shard index. Data will be
89 * distributed across all tables by key hash. This is for
90 * MySQL bugs 61735 and 61736.
91 * - slaveOnly: Whether to only use replica DBs and avoid triggering
92 * garbage collection logic of expired items. This only
93 * makes sense if the primary DB is used and only if get()
94 * calls will be used. This is used by ReplicatedBagOStuff.
95 * - syncTimeout: Max seconds to wait for replica DBs to catch up for WRITE_SYNC.
97 * @param array $params
99 public function __construct( $params ) {
100 parent
::__construct( $params );
102 $this->attrMap
[self
::ATTR_EMULATION
] = self
::QOS_EMULATION_SQL
;
103 $this->attrMap
[self
::ATTR_SYNCWRITES
] = self
::QOS_SYNCWRITES_NONE
;
105 if ( isset( $params['servers'] ) ) {
106 $this->serverInfos
= [];
107 $this->serverTags
= [];
108 $this->numServers
= count( $params['servers'] );
110 foreach ( $params['servers'] as $tag => $info ) {
111 $this->serverInfos
[$index] = $info;
112 if ( is_string( $tag ) ) {
113 $this->serverTags
[$index] = $tag;
115 $this->serverTags
[$index] = isset( $info['host'] ) ?
$info['host'] : "#$index";
119 } elseif ( isset( $params['server'] ) ) {
120 $this->serverInfos
= [ $params['server'] ];
121 $this->numServers
= count( $this->serverInfos
);
123 // Default to using the main wiki's database servers
124 $this->serverInfos
= false;
125 $this->numServers
= 1;
126 $this->attrMap
[self
::ATTR_SYNCWRITES
] = self
::QOS_SYNCWRITES_BE
;
128 if ( isset( $params['purgePeriod'] ) ) {
129 $this->purgePeriod
= intval( $params['purgePeriod'] );
131 if ( isset( $params['tableName'] ) ) {
132 $this->tableName
= $params['tableName'];
134 if ( isset( $params['shards'] ) ) {
135 $this->shards
= intval( $params['shards'] );
137 if ( isset( $params['syncTimeout'] ) ) {
138 $this->syncTimeout
= $params['syncTimeout'];
140 $this->replicaOnly
= !empty( $params['slaveOnly'] );
143 protected function getSeparateMainLB() {
146 if ( $wgDBtype === 'mysql' && $this->usesMainDB() ) {
147 if ( !$this->separateMainLB
) {
148 // We must keep a separate connection to MySQL in order to avoid deadlocks
149 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
150 $this->separateMainLB
= $lbFactory->newMainLB();
152 return $this->separateMainLB
;
154 // However, SQLite has an opposite behavior. And PostgreSQL needs to know
155 // if we are in transaction or not (@TODO: find some PostgreSQL work-around).
161 * Get a connection to the specified database
163 * @param int $serverIndex
165 * @throws MWException
167 protected function getDB( $serverIndex ) {
168 if ( !isset( $this->conns
[$serverIndex] ) ) {
169 if ( $serverIndex >= $this->numServers
) {
170 throw new MWException( __METHOD__
. ": Invalid server index \"$serverIndex\"" );
173 # Don't keep timing out trying to connect for each call if the DB is down
174 if ( isset( $this->connFailureErrors
[$serverIndex] )
175 && ( time() - $this->connFailureTimes
[$serverIndex] ) < 60
177 throw $this->connFailureErrors
[$serverIndex];
180 # If server connection info was given, use that
181 if ( $this->serverInfos
) {
182 $info = $this->serverInfos
[$serverIndex];
183 $type = isset( $info['type'] ) ?
$info['type'] : 'mysql';
184 $host = isset( $info['host'] ) ?
$info['host'] : '[unknown]';
185 $this->logger
->debug( __CLASS__
. ": connecting to $host" );
186 // Use a blank trx profiler to ignore expections as this is a cache
187 $info['trxProfiler'] = new TransactionProfiler();
188 $db = Database
::factory( $type, $info );
189 $db->clearFlag( DBO_TRX
);
191 $index = $this->replicaOnly ? DB_REPLICA
: DB_MASTER
;
192 if ( $this->getSeparateMainLB() ) {
193 $db = $this->getSeparateMainLB()->getConnection( $index );
194 $db->clearFlag( DBO_TRX
); // auto-commit mode
196 $db = wfGetDB( $index );
197 // Can't mess with transaction rounds (DBO_TRX) :(
200 $this->logger
->debug( sprintf( "Connection %s will be used for SqlBagOStuff", $db ) );
201 $this->conns
[$serverIndex] = $db;
204 return $this->conns
[$serverIndex];
208 * Get the server index and table name for a given key
210 * @return array Server index and table name
212 protected function getTableByKey( $key ) {
213 if ( $this->shards
> 1 ) {
214 $hash = hexdec( substr( md5( $key ), 0, 8 ) ) & 0x7fffffff;
215 $tableIndex = $hash %
$this->shards
;
219 if ( $this->numServers
> 1 ) {
220 $sortedServers = $this->serverTags
;
221 ArrayUtils
::consistentHashSort( $sortedServers, $key );
222 reset( $sortedServers );
223 $serverIndex = key( $sortedServers );
227 return [ $serverIndex, $this->getTableNameByShard( $tableIndex ) ];
231 * Get the table name for a given shard index
235 protected function getTableNameByShard( $index ) {
236 if ( $this->shards
> 1 ) {
237 $decimals = strlen( $this->shards
- 1 );
238 return $this->tableName
.
239 sprintf( "%0{$decimals}d", $index );
241 return $this->tableName
;
245 protected function doGet( $key, $flags = 0 ) {
248 return $this->getWithToken( $key, $casToken, $flags );
251 protected function getWithToken( $key, &$casToken, $flags = 0 ) {
252 $values = $this->getMulti( [ $key ] );
253 if ( array_key_exists( $key, $values ) ) {
254 $casToken = $values[$key];
255 return $values[$key];
260 public function getMulti( array $keys, $flags = 0 ) {
261 $values = []; // array of (key => value)
264 foreach ( $keys as $key ) {
265 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
266 $keysByTable[$serverIndex][$tableName][] = $key;
269 $this->garbageCollect(); // expire old entries if any
272 foreach ( $keysByTable as $serverIndex => $serverKeys ) {
274 $db = $this->getDB( $serverIndex );
275 foreach ( $serverKeys as $tableName => $tableKeys ) {
276 $res = $db->select( $tableName,
277 [ 'keyname', 'value', 'exptime' ],
278 [ 'keyname' => $tableKeys ],
280 // Approximate write-on-the-fly BagOStuff API via blocking.
281 // This approximation fails if a ROLLBACK happens (which is rare).
282 // We do not want to flush the TRX as that can break callers.
283 $db->trxLevel() ?
[ 'LOCK IN SHARE MODE' ] : []
285 if ( $res === false ) {
288 foreach ( $res as $row ) {
289 $row->serverIndex
= $serverIndex;
290 $row->tableName
= $tableName;
291 $dataRows[$row->keyname
] = $row;
294 } catch ( DBError
$e ) {
295 $this->handleReadError( $e, $serverIndex );
299 foreach ( $keys as $key ) {
300 if ( isset( $dataRows[$key] ) ) { // HIT?
301 $row = $dataRows[$key];
302 $this->debug( "get: retrieved data; expiry time is " . $row->exptime
);
305 $db = $this->getDB( $row->serverIndex
);
306 if ( $this->isExpired( $db, $row->exptime
) ) { // MISS
307 $this->debug( "get: key has expired" );
309 $values[$key] = $this->unserialize( $db->decodeBlob( $row->value
) );
311 } catch ( DBQueryError
$e ) {
312 $this->handleWriteError( $e, $db, $row->serverIndex
);
315 $this->debug( 'get: no matching rows' );
322 public function setMulti( array $data, $expiry = 0 ) {
324 foreach ( $data as $key => $value ) {
325 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
326 $keysByTable[$serverIndex][$tableName][] = $key;
329 $this->garbageCollect(); // expire old entries if any
332 $exptime = (int)$expiry;
333 foreach ( $keysByTable as $serverIndex => $serverKeys ) {
336 $db = $this->getDB( $serverIndex );
337 } catch ( DBError
$e ) {
338 $this->handleWriteError( $e, $db, $serverIndex );
343 if ( $exptime < 0 ) {
347 if ( $exptime == 0 ) {
348 $encExpiry = $this->getMaxDateTime( $db );
350 $exptime = $this->convertExpiry( $exptime );
351 $encExpiry = $db->timestamp( $exptime );
353 foreach ( $serverKeys as $tableName => $tableKeys ) {
355 foreach ( $tableKeys as $key ) {
358 'value' => $db->encodeBlob( $this->serialize( $data[$key] ) ),
359 'exptime' => $encExpiry,
370 } catch ( DBError
$e ) {
371 $this->handleWriteError( $e, $db, $serverIndex );
382 public function set( $key, $value, $exptime = 0, $flags = 0 ) {
383 $ok = $this->setMulti( [ $key => $value ], $exptime );
384 if ( ( $flags & self
::WRITE_SYNC
) == self
::WRITE_SYNC
) {
385 $ok = $this->waitForReplication() && $ok;
391 protected function cas( $casToken, $key, $value, $exptime = 0 ) {
392 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
395 $db = $this->getDB( $serverIndex );
396 $exptime = intval( $exptime );
398 if ( $exptime < 0 ) {
402 if ( $exptime == 0 ) {
403 $encExpiry = $this->getMaxDateTime( $db );
405 $exptime = $this->convertExpiry( $exptime );
406 $encExpiry = $db->timestamp( $exptime );
408 // (bug 24425) use a replace if the db supports it instead of
409 // delete/insert to avoid clashes with conflicting keynames
414 'value' => $db->encodeBlob( $this->serialize( $value ) ),
415 'exptime' => $encExpiry
419 'value' => $db->encodeBlob( $this->serialize( $casToken ) )
423 } catch ( DBQueryError
$e ) {
424 $this->handleWriteError( $e, $db, $serverIndex );
429 return (bool)$db->affectedRows();
432 public function delete( $key ) {
433 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
436 $db = $this->getDB( $serverIndex );
439 [ 'keyname' => $key ],
441 } catch ( DBError
$e ) {
442 $this->handleWriteError( $e, $db, $serverIndex );
449 public function incr( $key, $step = 1 ) {
450 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
453 $db = $this->getDB( $serverIndex );
454 $step = intval( $step );
455 $row = $db->selectRow(
457 [ 'value', 'exptime' ],
458 [ 'keyname' => $key ],
461 if ( $row === false ) {
466 $db->delete( $tableName, [ 'keyname' => $key ], __METHOD__
);
467 if ( $this->isExpired( $db, $row->exptime
) ) {
468 // Expired, do not reinsert
473 $oldValue = intval( $this->unserialize( $db->decodeBlob( $row->value
) ) );
474 $newValue = $oldValue +
$step;
475 $db->insert( $tableName,
478 'value' => $db->encodeBlob( $this->serialize( $newValue ) ),
479 'exptime' => $row->exptime
480 ], __METHOD__
, 'IGNORE' );
482 if ( $db->affectedRows() == 0 ) {
483 // Race condition. See bug 28611
486 } catch ( DBError
$e ) {
487 $this->handleWriteError( $e, $db, $serverIndex );
494 public function merge( $key, callable
$callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
495 $ok = $this->mergeViaCas( $key, $callback, $exptime, $attempts );
496 if ( ( $flags & self
::WRITE_SYNC
) == self
::WRITE_SYNC
) {
497 $ok = $this->waitForReplication() && $ok;
503 public function changeTTL( $key, $expiry = 0 ) {
504 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
507 $db = $this->getDB( $serverIndex );
510 [ 'exptime' => $db->timestamp( $this->convertExpiry( $expiry ) ) ],
511 [ 'keyname' => $key, 'exptime > ' . $db->addQuotes( $db->timestamp( time() ) ) ],
514 if ( $db->affectedRows() == 0 ) {
517 } catch ( DBError
$e ) {
518 $this->handleWriteError( $e, $db, $serverIndex );
526 * @param IDatabase $db
527 * @param string $exptime
530 protected function isExpired( $db, $exptime ) {
531 return $exptime != $this->getMaxDateTime( $db ) && wfTimestamp( TS_UNIX
, $exptime ) < time();
535 * @param IDatabase $db
538 protected function getMaxDateTime( $db ) {
539 if ( time() > 0x7fffffff ) {
540 return $db->timestamp( 1 << 62 );
542 return $db->timestamp( 0x7fffffff );
546 protected function garbageCollect() {
547 if ( !$this->purgePeriod ||
$this->replicaOnly
) {
551 // Only purge on one in every $this->purgePeriod requests.
552 if ( $this->purgePeriod
!== 1 && mt_rand( 0, $this->purgePeriod
- 1 ) ) {
556 // Avoid repeating the delete within a few seconds
557 if ( $now > ( $this->lastExpireAll +
1 ) ) {
558 $this->lastExpireAll
= $now;
563 public function expireAll() {
564 $this->deleteObjectsExpiringBefore( wfTimestampNow() );
568 * Delete objects from the database which expire before a certain date.
569 * @param string $timestamp
570 * @param bool|callable $progressCallback
573 public function deleteObjectsExpiringBefore( $timestamp, $progressCallback = false ) {
574 for ( $serverIndex = 0; $serverIndex < $this->numServers
; $serverIndex++
) {
577 $db = $this->getDB( $serverIndex );
578 $dbTimestamp = $db->timestamp( $timestamp );
579 $totalSeconds = false;
580 $baseConds = [ 'exptime < ' . $db->addQuotes( $dbTimestamp ) ];
581 for ( $i = 0; $i < $this->shards
; $i++
) {
585 if ( $maxExpTime !== false ) {
586 $conds[] = 'exptime > ' . $db->addQuotes( $maxExpTime );
589 $this->getTableNameByShard( $i ),
590 [ 'keyname', 'exptime' ],
593 [ 'LIMIT' => 100, 'ORDER BY' => 'exptime' ] );
594 if ( $rows === false ||
!$rows->numRows() ) {
598 $row = $rows->current();
599 $minExpTime = $row->exptime
;
600 if ( $totalSeconds === false ) {
601 $totalSeconds = wfTimestamp( TS_UNIX
, $timestamp )
602 - wfTimestamp( TS_UNIX
, $minExpTime );
604 foreach ( $rows as $row ) {
605 $keys[] = $row->keyname
;
606 $maxExpTime = $row->exptime
;
610 $this->getTableNameByShard( $i ),
612 'exptime >= ' . $db->addQuotes( $minExpTime ),
613 'exptime < ' . $db->addQuotes( $dbTimestamp ),
618 if ( $progressCallback ) {
619 if ( intval( $totalSeconds ) === 0 ) {
622 $remainingSeconds = wfTimestamp( TS_UNIX
, $timestamp )
623 - wfTimestamp( TS_UNIX
, $maxExpTime );
624 if ( $remainingSeconds > $totalSeconds ) {
625 $totalSeconds = $remainingSeconds;
627 $processedSeconds = $totalSeconds - $remainingSeconds;
628 $percent = ( $i +
$processedSeconds / $totalSeconds )
629 / $this->shards
* 100;
631 $percent = ( $percent / $this->numServers
)
632 +
( $serverIndex / $this->numServers
* 100 );
633 call_user_func( $progressCallback, $percent );
637 } catch ( DBError
$e ) {
638 $this->handleWriteError( $e, $db, $serverIndex );
646 * Delete content of shard tables in every server.
647 * Return true if the operation is successful, false otherwise.
650 public function deleteAll() {
651 for ( $serverIndex = 0; $serverIndex < $this->numServers
; $serverIndex++
) {
654 $db = $this->getDB( $serverIndex );
655 for ( $i = 0; $i < $this->shards
; $i++
) {
656 $db->delete( $this->getTableNameByShard( $i ), '*', __METHOD__
);
658 } catch ( DBError
$e ) {
659 $this->handleWriteError( $e, $db, $serverIndex );
667 * Serialize an object and, if possible, compress the representation.
668 * On typical message and page data, this can provide a 3X decrease
669 * in storage requirements.
674 protected function serialize( &$data ) {
675 $serial = serialize( $data );
677 if ( function_exists( 'gzdeflate' ) ) {
678 return gzdeflate( $serial );
685 * Unserialize and, if necessary, decompress an object.
686 * @param string $serial
689 protected function unserialize( $serial ) {
690 if ( function_exists( 'gzinflate' ) ) {
691 MediaWiki\
suppressWarnings();
692 $decomp = gzinflate( $serial );
693 MediaWiki\restoreWarnings
();
695 if ( false !== $decomp ) {
700 $ret = unserialize( $serial );
706 * Handle a DBError which occurred during a read operation.
708 * @param DBError $exception
709 * @param int $serverIndex
711 protected function handleReadError( DBError
$exception, $serverIndex ) {
712 if ( $exception instanceof DBConnectionError
) {
713 $this->markServerDown( $exception, $serverIndex );
715 $this->logger
->error( "DBError: {$exception->getMessage()}" );
716 if ( $exception instanceof DBConnectionError
) {
717 $this->setLastError( BagOStuff
::ERR_UNREACHABLE
);
718 $this->logger
->debug( __METHOD__
. ": ignoring connection error" );
720 $this->setLastError( BagOStuff
::ERR_UNEXPECTED
);
721 $this->logger
->debug( __METHOD__
. ": ignoring query error" );
726 * Handle a DBQueryError which occurred during a write operation.
728 * @param DBError $exception
729 * @param IDatabase|null $db DB handle or null if connection failed
730 * @param int $serverIndex
733 protected function handleWriteError( DBError
$exception, IDatabase
$db = null, $serverIndex ) {
735 $this->markServerDown( $exception, $serverIndex );
736 } elseif ( $db->wasReadOnlyError() ) {
737 if ( $db->trxLevel() && $this->usesMainDB() ) {
738 // Errors like deadlocks and connection drops already cause rollback.
739 // For consistency, we have no choice but to throw an error and trigger
740 // complete rollback if the main DB is also being used as the cache DB.
745 $this->logger
->error( "DBError: {$exception->getMessage()}" );
746 if ( $exception instanceof DBConnectionError
) {
747 $this->setLastError( BagOStuff
::ERR_UNREACHABLE
);
748 $this->logger
->debug( __METHOD__
. ": ignoring connection error" );
750 $this->setLastError( BagOStuff
::ERR_UNEXPECTED
);
751 $this->logger
->debug( __METHOD__
. ": ignoring query error" );
756 * Mark a server down due to a DBConnectionError exception
758 * @param DBError $exception
759 * @param int $serverIndex
761 protected function markServerDown( DBError
$exception, $serverIndex ) {
762 unset( $this->conns
[$serverIndex] ); // bug T103435
764 if ( isset( $this->connFailureTimes
[$serverIndex] ) ) {
765 if ( time() - $this->connFailureTimes
[$serverIndex] >= 60 ) {
766 unset( $this->connFailureTimes
[$serverIndex] );
767 unset( $this->connFailureErrors
[$serverIndex] );
769 $this->logger
->debug( __METHOD__
. ": Server #$serverIndex already down" );
774 $this->logger
->info( __METHOD__
. ": Server #$serverIndex down until " . ( $now +
60 ) );
775 $this->connFailureTimes
[$serverIndex] = $now;
776 $this->connFailureErrors
[$serverIndex] = $exception;
780 * Create shard tables. For use from eval.php.
782 public function createTables() {
783 for ( $serverIndex = 0; $serverIndex < $this->numServers
; $serverIndex++
) {
784 $db = $this->getDB( $serverIndex );
785 if ( $db->getType() !== 'mysql' ) {
786 throw new MWException( __METHOD__
. ' is not supported on this DB server' );
789 for ( $i = 0; $i < $this->shards
; $i++
) {
791 'CREATE TABLE ' . $db->tableName( $this->getTableNameByShard( $i ) ) .
792 ' LIKE ' . $db->tableName( 'objectcache' ),
799 * @return bool Whether the main DB is used, e.g. wfGetDB( DB_MASTER )
801 protected function usesMainDB() {
802 return !$this->serverInfos
;
805 protected function waitForReplication() {
806 if ( !$this->usesMainDB() ) {
807 // Custom DB server list; probably doesn't use replication
811 $lb = $this->getSeparateMainLB()
812 ?
: MediaWikiServices
::getInstance()->getDBLoadBalancer();
814 if ( $lb->getServerCount() <= 1 ) {
815 return true; // no replica DBs
818 // Main LB is used; wait for any replica DBs to catch up
819 $masterPos = $lb->getMasterPos();
821 $loop = new WaitConditionLoop(
822 function () use ( $lb, $masterPos ) {
823 return $lb->waitForAll( $masterPos, 1 );
829 return ( $loop->invoke() === $loop::CONDITION_REACHED
);