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
25 * Class to store objects in the database
29 class SqlBagOStuff
extends BagOStuff
{
30 /** @var array[] (server index => server config) */
31 protected $serverInfos;
32 /** @var string[] (server index => tag/host name) */
33 protected $serverTags;
35 protected $numServers;
37 protected $lastExpireAll = 0;
39 protected $purgePeriod = 100;
41 protected $shards = 1;
43 protected $tableName = 'objectcache';
45 protected $slaveOnly = false;
47 protected $syncTimeout = 3;
51 /** @var array UNIX timestamps */
52 protected $connFailureTimes = [];
53 /** @var array Exceptions */
54 protected $connFailureErrors = [];
57 * Constructor. Parameters are:
58 * - server: A server info structure in the format required by each
59 * element in $wgDBServers.
61 * - servers: An array of server info structures describing a set of database servers
62 * to distribute keys to. If this is specified, the "server" option will be
63 * ignored. If string keys are used, then they will be used for consistent
64 * hashing *instead* of the host name (from the server config). This is useful
65 * when a cluster is replicated to another site (with different host names)
66 * but each server has a corresponding replica in the other cluster.
68 * - purgePeriod: The average number of object cache requests in between
69 * garbage collection operations, where expired entries
70 * are removed from the database. Or in other words, the
71 * reciprocal of the probability of purging on any given
72 * request. If this is set to zero, purging will never be
75 * - tableName: The table name to use, default is "objectcache".
77 * - shards: The number of tables to use for data storage on each server.
78 * If this is more than 1, table names will be formed in the style
79 * objectcacheNNN where NNN is the shard index, between 0 and
80 * shards-1. The number of digits will be the minimum number
81 * required to hold the largest shard index. Data will be
82 * distributed across all tables by key hash. This is for
83 * MySQL bugs 61735 and 61736.
84 * - slaveOnly: Whether to only use slave DBs and avoid triggering
85 * garbage collection logic of expired items. This only
86 * makes sense if the primary DB is used and only if get()
87 * calls will be used. This is used by ReplicatedBagOStuff.
88 * - syncTimeout: Max seconds to wait for slaves to catch up for WRITE_SYNC.
90 * @param array $params
92 public function __construct( $params ) {
93 parent
::__construct( $params );
95 $this->attrMap
[self
::ATTR_EMULATION
] = self
::QOS_EMULATION_SQL
;
97 if ( isset( $params['servers'] ) ) {
98 $this->serverInfos
= [];
99 $this->serverTags
= [];
100 $this->numServers
= count( $params['servers'] );
102 foreach ( $params['servers'] as $tag => $info ) {
103 $this->serverInfos
[$index] = $info;
104 if ( is_string( $tag ) ) {
105 $this->serverTags
[$index] = $tag;
107 $this->serverTags
[$index] = isset( $info['host'] ) ?
$info['host'] : "#$index";
111 } elseif ( isset( $params['server'] ) ) {
112 $this->serverInfos
= [ $params['server'] ];
113 $this->numServers
= count( $this->serverInfos
);
115 $this->serverInfos
= false;
116 $this->numServers
= 1;
118 if ( isset( $params['purgePeriod'] ) ) {
119 $this->purgePeriod
= intval( $params['purgePeriod'] );
121 if ( isset( $params['tableName'] ) ) {
122 $this->tableName
= $params['tableName'];
124 if ( isset( $params['shards'] ) ) {
125 $this->shards
= intval( $params['shards'] );
127 if ( isset( $params['syncTimeout'] ) ) {
128 $this->syncTimeout
= $params['syncTimeout'];
130 $this->slaveOnly
= !empty( $params['slaveOnly'] );
134 * Get a connection to the specified database
136 * @param int $serverIndex
138 * @throws MWException
140 protected function getDB( $serverIndex ) {
141 if ( !isset( $this->conns
[$serverIndex] ) ) {
142 if ( $serverIndex >= $this->numServers
) {
143 throw new MWException( __METHOD__
. ": Invalid server index \"$serverIndex\"" );
146 # Don't keep timing out trying to connect for each call if the DB is down
147 if ( isset( $this->connFailureErrors
[$serverIndex] )
148 && ( time() - $this->connFailureTimes
[$serverIndex] ) < 60
150 throw $this->connFailureErrors
[$serverIndex];
153 # If server connection info was given, use that
154 if ( $this->serverInfos
) {
155 $info = $this->serverInfos
[$serverIndex];
156 $type = isset( $info['type'] ) ?
$info['type'] : 'mysql';
157 $host = isset( $info['host'] ) ?
$info['host'] : '[unknown]';
158 $this->logger
->debug( __CLASS__
. ": connecting to $host" );
159 // Use a blank trx profiler to ignore expections as this is a cache
160 $info['trxProfiler'] = new TransactionProfiler();
161 $db = DatabaseBase
::factory( $type, $info );
162 $db->clearFlag( DBO_TRX
);
164 // We must keep a separate connection to MySQL in order to avoid deadlocks
165 // However, SQLite has an opposite behavior. And PostgreSQL needs to know
166 // if we are in transaction or not (@TODO: find some work-around).
167 $index = $this->slaveOnly ? DB_SLAVE
: DB_MASTER
;
168 if ( wfGetDB( $index )->getType() == 'mysql' ) {
169 $lb = wfGetLBFactory()->newMainLB();
170 $db = $lb->getConnection( $index );
171 $db->clearFlag( DBO_TRX
); // auto-commit mode
173 $db = wfGetDB( $index );
176 $this->logger
->debug( sprintf( "Connection %s will be used for SqlBagOStuff", $db ) );
177 $this->conns
[$serverIndex] = $db;
180 return $this->conns
[$serverIndex];
184 * Get the server index and table name for a given key
186 * @return array Server index and table name
188 protected function getTableByKey( $key ) {
189 if ( $this->shards
> 1 ) {
190 $hash = hexdec( substr( md5( $key ), 0, 8 ) ) & 0x7fffffff;
191 $tableIndex = $hash %
$this->shards
;
195 if ( $this->numServers
> 1 ) {
196 $sortedServers = $this->serverTags
;
197 ArrayUtils
::consistentHashSort( $sortedServers, $key );
198 reset( $sortedServers );
199 $serverIndex = key( $sortedServers );
203 return [ $serverIndex, $this->getTableNameByShard( $tableIndex ) ];
207 * Get the table name for a given shard index
211 protected function getTableNameByShard( $index ) {
212 if ( $this->shards
> 1 ) {
213 $decimals = strlen( $this->shards
- 1 );
214 return $this->tableName
.
215 sprintf( "%0{$decimals}d", $index );
217 return $this->tableName
;
221 protected function doGet( $key, $flags = 0 ) {
224 return $this->getWithToken( $key, $casToken, $flags );
227 protected function getWithToken( $key, &$casToken, $flags = 0 ) {
228 $values = $this->getMulti( [ $key ] );
229 if ( array_key_exists( $key, $values ) ) {
230 $casToken = $values[$key];
231 return $values[$key];
236 public function getMulti( array $keys, $flags = 0 ) {
237 $values = []; // array of (key => value)
240 foreach ( $keys as $key ) {
241 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
242 $keysByTable[$serverIndex][$tableName][] = $key;
245 $this->garbageCollect(); // expire old entries if any
248 foreach ( $keysByTable as $serverIndex => $serverKeys ) {
250 $db = $this->getDB( $serverIndex );
251 foreach ( $serverKeys as $tableName => $tableKeys ) {
252 $res = $db->select( $tableName,
253 [ 'keyname', 'value', 'exptime' ],
254 [ 'keyname' => $tableKeys ],
256 // Approximate write-on-the-fly BagOStuff API via blocking.
257 // This approximation fails if a ROLLBACK happens (which is rare).
258 // We do not want to flush the TRX as that can break callers.
259 $db->trxLevel() ?
[ 'LOCK IN SHARE MODE' ] : []
261 if ( $res === false ) {
264 foreach ( $res as $row ) {
265 $row->serverIndex
= $serverIndex;
266 $row->tableName
= $tableName;
267 $dataRows[$row->keyname
] = $row;
270 } catch ( DBError
$e ) {
271 $this->handleReadError( $e, $serverIndex );
275 foreach ( $keys as $key ) {
276 if ( isset( $dataRows[$key] ) ) { // HIT?
277 $row = $dataRows[$key];
278 $this->debug( "get: retrieved data; expiry time is " . $row->exptime
);
280 $db = $this->getDB( $row->serverIndex
);
281 if ( $this->isExpired( $db, $row->exptime
) ) { // MISS
282 $this->debug( "get: key has expired" );
284 $values[$key] = $this->unserialize( $db->decodeBlob( $row->value
) );
286 } catch ( DBQueryError
$e ) {
287 $this->handleWriteError( $e, $row->serverIndex
);
290 $this->debug( 'get: no matching rows' );
297 public function setMulti( array $data, $expiry = 0 ) {
299 foreach ( $data as $key => $value ) {
300 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
301 $keysByTable[$serverIndex][$tableName][] = $key;
304 $this->garbageCollect(); // expire old entries if any
307 $exptime = (int)$expiry;
308 foreach ( $keysByTable as $serverIndex => $serverKeys ) {
310 $db = $this->getDB( $serverIndex );
311 } catch ( DBError
$e ) {
312 $this->handleWriteError( $e, $serverIndex );
317 if ( $exptime < 0 ) {
321 if ( $exptime == 0 ) {
322 $encExpiry = $this->getMaxDateTime( $db );
324 $exptime = $this->convertExpiry( $exptime );
325 $encExpiry = $db->timestamp( $exptime );
327 foreach ( $serverKeys as $tableName => $tableKeys ) {
329 foreach ( $tableKeys as $key ) {
332 'value' => $db->encodeBlob( $this->serialize( $data[$key] ) ),
333 'exptime' => $encExpiry,
344 } catch ( DBError
$e ) {
345 $this->handleWriteError( $e, $serverIndex );
356 public function set( $key, $value, $exptime = 0, $flags = 0 ) {
357 $ok = $this->setMulti( [ $key => $value ], $exptime );
358 if ( ( $flags & self
::WRITE_SYNC
) == self
::WRITE_SYNC
) {
359 $ok = $ok && $this->waitForSlaves();
365 protected function cas( $casToken, $key, $value, $exptime = 0 ) {
366 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
368 $db = $this->getDB( $serverIndex );
369 $exptime = intval( $exptime );
371 if ( $exptime < 0 ) {
375 if ( $exptime == 0 ) {
376 $encExpiry = $this->getMaxDateTime( $db );
378 $exptime = $this->convertExpiry( $exptime );
379 $encExpiry = $db->timestamp( $exptime );
381 // (bug 24425) use a replace if the db supports it instead of
382 // delete/insert to avoid clashes with conflicting keynames
387 'value' => $db->encodeBlob( $this->serialize( $value ) ),
388 'exptime' => $encExpiry
392 'value' => $db->encodeBlob( $this->serialize( $casToken ) )
396 } catch ( DBQueryError
$e ) {
397 $this->handleWriteError( $e, $serverIndex );
402 return (bool)$db->affectedRows();
405 public function delete( $key ) {
406 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
408 $db = $this->getDB( $serverIndex );
411 [ 'keyname' => $key ],
413 } catch ( DBError
$e ) {
414 $this->handleWriteError( $e, $serverIndex );
421 public function incr( $key, $step = 1 ) {
422 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
424 $db = $this->getDB( $serverIndex );
425 $step = intval( $step );
426 $row = $db->selectRow(
428 [ 'value', 'exptime' ],
429 [ 'keyname' => $key ],
432 if ( $row === false ) {
437 $db->delete( $tableName, [ 'keyname' => $key ], __METHOD__
);
438 if ( $this->isExpired( $db, $row->exptime
) ) {
439 // Expired, do not reinsert
444 $oldValue = intval( $this->unserialize( $db->decodeBlob( $row->value
) ) );
445 $newValue = $oldValue +
$step;
446 $db->insert( $tableName,
449 'value' => $db->encodeBlob( $this->serialize( $newValue ) ),
450 'exptime' => $row->exptime
451 ], __METHOD__
, 'IGNORE' );
453 if ( $db->affectedRows() == 0 ) {
454 // Race condition. See bug 28611
457 } catch ( DBError
$e ) {
458 $this->handleWriteError( $e, $serverIndex );
465 public function merge( $key, callable
$callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
466 $ok = $this->mergeViaCas( $key, $callback, $exptime, $attempts );
467 if ( ( $flags & self
::WRITE_SYNC
) == self
::WRITE_SYNC
) {
468 $ok = $ok && $this->waitForSlaves();
474 public function changeTTL( $key, $expiry = 0 ) {
475 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
477 $db = $this->getDB( $serverIndex );
480 [ 'exptime' => $db->timestamp( $this->convertExpiry( $expiry ) ) ],
481 [ 'keyname' => $key, 'exptime > ' . $db->addQuotes( $db->timestamp( time() ) ) ],
484 if ( $db->affectedRows() == 0 ) {
487 } catch ( DBError
$e ) {
488 $this->handleWriteError( $e, $serverIndex );
496 * @param IDatabase $db
497 * @param string $exptime
500 protected function isExpired( $db, $exptime ) {
501 return $exptime != $this->getMaxDateTime( $db ) && wfTimestamp( TS_UNIX
, $exptime ) < time();
505 * @param IDatabase $db
508 protected function getMaxDateTime( $db ) {
509 if ( time() > 0x7fffffff ) {
510 return $db->timestamp( 1 << 62 );
512 return $db->timestamp( 0x7fffffff );
516 protected function garbageCollect() {
517 if ( !$this->purgePeriod ||
$this->slaveOnly
) {
521 // Only purge on one in every $this->purgePeriod requests.
522 if ( $this->purgePeriod
!== 1 && mt_rand( 0, $this->purgePeriod
- 1 ) ) {
526 // Avoid repeating the delete within a few seconds
527 if ( $now > ( $this->lastExpireAll +
1 ) ) {
528 $this->lastExpireAll
= $now;
533 public function expireAll() {
534 $this->deleteObjectsExpiringBefore( wfTimestampNow() );
538 * Delete objects from the database which expire before a certain date.
539 * @param string $timestamp
540 * @param bool|callable $progressCallback
543 public function deleteObjectsExpiringBefore( $timestamp, $progressCallback = false ) {
544 for ( $serverIndex = 0; $serverIndex < $this->numServers
; $serverIndex++
) {
546 $db = $this->getDB( $serverIndex );
547 $dbTimestamp = $db->timestamp( $timestamp );
548 $totalSeconds = false;
549 $baseConds = [ 'exptime < ' . $db->addQuotes( $dbTimestamp ) ];
550 for ( $i = 0; $i < $this->shards
; $i++
) {
554 if ( $maxExpTime !== false ) {
555 $conds[] = 'exptime > ' . $db->addQuotes( $maxExpTime );
558 $this->getTableNameByShard( $i ),
559 [ 'keyname', 'exptime' ],
562 [ 'LIMIT' => 100, 'ORDER BY' => 'exptime' ] );
563 if ( $rows === false ||
!$rows->numRows() ) {
567 $row = $rows->current();
568 $minExpTime = $row->exptime
;
569 if ( $totalSeconds === false ) {
570 $totalSeconds = wfTimestamp( TS_UNIX
, $timestamp )
571 - wfTimestamp( TS_UNIX
, $minExpTime );
573 foreach ( $rows as $row ) {
574 $keys[] = $row->keyname
;
575 $maxExpTime = $row->exptime
;
579 $this->getTableNameByShard( $i ),
581 'exptime >= ' . $db->addQuotes( $minExpTime ),
582 'exptime < ' . $db->addQuotes( $dbTimestamp ),
587 if ( $progressCallback ) {
588 if ( intval( $totalSeconds ) === 0 ) {
591 $remainingSeconds = wfTimestamp( TS_UNIX
, $timestamp )
592 - wfTimestamp( TS_UNIX
, $maxExpTime );
593 if ( $remainingSeconds > $totalSeconds ) {
594 $totalSeconds = $remainingSeconds;
596 $processedSeconds = $totalSeconds - $remainingSeconds;
597 $percent = ( $i +
$processedSeconds / $totalSeconds )
598 / $this->shards
* 100;
600 $percent = ( $percent / $this->numServers
)
601 +
( $serverIndex / $this->numServers
* 100 );
602 call_user_func( $progressCallback, $percent );
606 } catch ( DBError
$e ) {
607 $this->handleWriteError( $e, $serverIndex );
615 * Delete content of shard tables in every server.
616 * Return true if the operation is successful, false otherwise.
619 public function deleteAll() {
620 for ( $serverIndex = 0; $serverIndex < $this->numServers
; $serverIndex++
) {
622 $db = $this->getDB( $serverIndex );
623 for ( $i = 0; $i < $this->shards
; $i++
) {
624 $db->delete( $this->getTableNameByShard( $i ), '*', __METHOD__
);
626 } catch ( DBError
$e ) {
627 $this->handleWriteError( $e, $serverIndex );
635 * Serialize an object and, if possible, compress the representation.
636 * On typical message and page data, this can provide a 3X decrease
637 * in storage requirements.
642 protected function serialize( &$data ) {
643 $serial = serialize( $data );
645 if ( function_exists( 'gzdeflate' ) ) {
646 return gzdeflate( $serial );
653 * Unserialize and, if necessary, decompress an object.
654 * @param string $serial
657 protected function unserialize( $serial ) {
658 if ( function_exists( 'gzinflate' ) ) {
659 MediaWiki\
suppressWarnings();
660 $decomp = gzinflate( $serial );
661 MediaWiki\restoreWarnings
();
663 if ( false !== $decomp ) {
668 $ret = unserialize( $serial );
674 * Handle a DBError which occurred during a read operation.
676 * @param DBError $exception
677 * @param int $serverIndex
679 protected function handleReadError( DBError
$exception, $serverIndex ) {
680 if ( $exception instanceof DBConnectionError
) {
681 $this->markServerDown( $exception, $serverIndex );
683 $this->logger
->error( "DBError: {$exception->getMessage()}" );
684 if ( $exception instanceof DBConnectionError
) {
685 $this->setLastError( BagOStuff
::ERR_UNREACHABLE
);
686 $this->logger
->debug( __METHOD__
. ": ignoring connection error" );
688 $this->setLastError( BagOStuff
::ERR_UNEXPECTED
);
689 $this->logger
->debug( __METHOD__
. ": ignoring query error" );
694 * Handle a DBQueryError which occurred during a write operation.
696 * @param DBError $exception
697 * @param int $serverIndex
699 protected function handleWriteError( DBError
$exception, $serverIndex ) {
700 if ( $exception instanceof DBConnectionError
) {
701 $this->markServerDown( $exception, $serverIndex );
703 if ( $exception->db
&& $exception->db
->wasReadOnlyError() ) {
704 if ( $exception->db
->trxLevel() ) {
706 $exception->db
->rollback( __METHOD__
);
707 } catch ( DBError
$e ) {
712 $this->logger
->error( "DBError: {$exception->getMessage()}" );
713 if ( $exception instanceof DBConnectionError
) {
714 $this->setLastError( BagOStuff
::ERR_UNREACHABLE
);
715 $this->logger
->debug( __METHOD__
. ": ignoring connection error" );
717 $this->setLastError( BagOStuff
::ERR_UNEXPECTED
);
718 $this->logger
->debug( __METHOD__
. ": ignoring query error" );
723 * Mark a server down due to a DBConnectionError exception
725 * @param DBError $exception
726 * @param int $serverIndex
728 protected function markServerDown( $exception, $serverIndex ) {
729 unset( $this->conns
[$serverIndex] ); // bug T103435
731 if ( isset( $this->connFailureTimes
[$serverIndex] ) ) {
732 if ( time() - $this->connFailureTimes
[$serverIndex] >= 60 ) {
733 unset( $this->connFailureTimes
[$serverIndex] );
734 unset( $this->connFailureErrors
[$serverIndex] );
736 $this->logger
->debug( __METHOD__
. ": Server #$serverIndex already down" );
741 $this->logger
->info( __METHOD__
. ": Server #$serverIndex down until " . ( $now +
60 ) );
742 $this->connFailureTimes
[$serverIndex] = $now;
743 $this->connFailureErrors
[$serverIndex] = $exception;
747 * Create shard tables. For use from eval.php.
749 public function createTables() {
750 for ( $serverIndex = 0; $serverIndex < $this->numServers
; $serverIndex++
) {
751 $db = $this->getDB( $serverIndex );
752 if ( $db->getType() !== 'mysql' ) {
753 throw new MWException( __METHOD__
. ' is not supported on this DB server' );
756 for ( $i = 0; $i < $this->shards
; $i++
) {
758 'CREATE TABLE ' . $db->tableName( $this->getTableNameByShard( $i ) ) .
759 ' LIKE ' . $db->tableName( 'objectcache' ),
765 protected function waitForSlaves() {
766 if ( !$this->serverInfos
) {
767 // Main LB is used; wait for any slaves to catch up
769 wfGetLBFactory()->waitForReplication( [ 'wiki' => wfWikiID() ] );
771 } catch ( DBReplicationWaitError
$e ) {
775 // Custom DB server list; probably doesn't use replication