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();
475 * @param IDatabase $db
476 * @param string $exptime
479 protected function isExpired( $db, $exptime ) {
480 return $exptime != $this->getMaxDateTime( $db ) && wfTimestamp( TS_UNIX
, $exptime ) < time();
484 * @param IDatabase $db
487 protected function getMaxDateTime( $db ) {
488 if ( time() > 0x7fffffff ) {
489 return $db->timestamp( 1 << 62 );
491 return $db->timestamp( 0x7fffffff );
495 protected function garbageCollect() {
496 if ( !$this->purgePeriod ||
$this->slaveOnly
) {
500 // Only purge on one in every $this->purgePeriod requests.
501 if ( $this->purgePeriod
!== 1 && mt_rand( 0, $this->purgePeriod
- 1 ) ) {
505 // Avoid repeating the delete within a few seconds
506 if ( $now > ( $this->lastExpireAll +
1 ) ) {
507 $this->lastExpireAll
= $now;
512 public function expireAll() {
513 $this->deleteObjectsExpiringBefore( wfTimestampNow() );
517 * Delete objects from the database which expire before a certain date.
518 * @param string $timestamp
519 * @param bool|callable $progressCallback
522 public function deleteObjectsExpiringBefore( $timestamp, $progressCallback = false ) {
523 for ( $serverIndex = 0; $serverIndex < $this->numServers
; $serverIndex++
) {
525 $db = $this->getDB( $serverIndex );
526 $dbTimestamp = $db->timestamp( $timestamp );
527 $totalSeconds = false;
528 $baseConds = [ 'exptime < ' . $db->addQuotes( $dbTimestamp ) ];
529 for ( $i = 0; $i < $this->shards
; $i++
) {
533 if ( $maxExpTime !== false ) {
534 $conds[] = 'exptime > ' . $db->addQuotes( $maxExpTime );
537 $this->getTableNameByShard( $i ),
538 [ 'keyname', 'exptime' ],
541 [ 'LIMIT' => 100, 'ORDER BY' => 'exptime' ] );
542 if ( $rows === false ||
!$rows->numRows() ) {
546 $row = $rows->current();
547 $minExpTime = $row->exptime
;
548 if ( $totalSeconds === false ) {
549 $totalSeconds = wfTimestamp( TS_UNIX
, $timestamp )
550 - wfTimestamp( TS_UNIX
, $minExpTime );
552 foreach ( $rows as $row ) {
553 $keys[] = $row->keyname
;
554 $maxExpTime = $row->exptime
;
558 $this->getTableNameByShard( $i ),
560 'exptime >= ' . $db->addQuotes( $minExpTime ),
561 'exptime < ' . $db->addQuotes( $dbTimestamp ),
566 if ( $progressCallback ) {
567 if ( intval( $totalSeconds ) === 0 ) {
570 $remainingSeconds = wfTimestamp( TS_UNIX
, $timestamp )
571 - wfTimestamp( TS_UNIX
, $maxExpTime );
572 if ( $remainingSeconds > $totalSeconds ) {
573 $totalSeconds = $remainingSeconds;
575 $processedSeconds = $totalSeconds - $remainingSeconds;
576 $percent = ( $i +
$processedSeconds / $totalSeconds )
577 / $this->shards
* 100;
579 $percent = ( $percent / $this->numServers
)
580 +
( $serverIndex / $this->numServers
* 100 );
581 call_user_func( $progressCallback, $percent );
585 } catch ( DBError
$e ) {
586 $this->handleWriteError( $e, $serverIndex );
594 * Delete content of shard tables in every server.
595 * Return true if the operation is successful, false otherwise.
598 public function deleteAll() {
599 for ( $serverIndex = 0; $serverIndex < $this->numServers
; $serverIndex++
) {
601 $db = $this->getDB( $serverIndex );
602 for ( $i = 0; $i < $this->shards
; $i++
) {
603 $db->delete( $this->getTableNameByShard( $i ), '*', __METHOD__
);
605 } catch ( DBError
$e ) {
606 $this->handleWriteError( $e, $serverIndex );
614 * Serialize an object and, if possible, compress the representation.
615 * On typical message and page data, this can provide a 3X decrease
616 * in storage requirements.
621 protected function serialize( &$data ) {
622 $serial = serialize( $data );
624 if ( function_exists( 'gzdeflate' ) ) {
625 return gzdeflate( $serial );
632 * Unserialize and, if necessary, decompress an object.
633 * @param string $serial
636 protected function unserialize( $serial ) {
637 if ( function_exists( 'gzinflate' ) ) {
638 MediaWiki\
suppressWarnings();
639 $decomp = gzinflate( $serial );
640 MediaWiki\restoreWarnings
();
642 if ( false !== $decomp ) {
647 $ret = unserialize( $serial );
653 * Handle a DBError which occurred during a read operation.
655 * @param DBError $exception
656 * @param int $serverIndex
658 protected function handleReadError( DBError
$exception, $serverIndex ) {
659 if ( $exception instanceof DBConnectionError
) {
660 $this->markServerDown( $exception, $serverIndex );
662 $this->logger
->error( "DBError: {$exception->getMessage()}" );
663 if ( $exception instanceof DBConnectionError
) {
664 $this->setLastError( BagOStuff
::ERR_UNREACHABLE
);
665 $this->logger
->debug( __METHOD__
. ": ignoring connection error" );
667 $this->setLastError( BagOStuff
::ERR_UNEXPECTED
);
668 $this->logger
->debug( __METHOD__
. ": ignoring query error" );
673 * Handle a DBQueryError which occurred during a write operation.
675 * @param DBError $exception
676 * @param int $serverIndex
678 protected function handleWriteError( DBError
$exception, $serverIndex ) {
679 if ( $exception instanceof DBConnectionError
) {
680 $this->markServerDown( $exception, $serverIndex );
682 if ( $exception->db
&& $exception->db
->wasReadOnlyError() ) {
683 if ( $exception->db
->trxLevel() ) {
685 $exception->db
->rollback( __METHOD__
);
686 } catch ( DBError
$e ) {
691 $this->logger
->error( "DBError: {$exception->getMessage()}" );
692 if ( $exception instanceof DBConnectionError
) {
693 $this->setLastError( BagOStuff
::ERR_UNREACHABLE
);
694 $this->logger
->debug( __METHOD__
. ": ignoring connection error" );
696 $this->setLastError( BagOStuff
::ERR_UNEXPECTED
);
697 $this->logger
->debug( __METHOD__
. ": ignoring query error" );
702 * Mark a server down due to a DBConnectionError exception
704 * @param DBError $exception
705 * @param int $serverIndex
707 protected function markServerDown( $exception, $serverIndex ) {
708 unset( $this->conns
[$serverIndex] ); // bug T103435
710 if ( isset( $this->connFailureTimes
[$serverIndex] ) ) {
711 if ( time() - $this->connFailureTimes
[$serverIndex] >= 60 ) {
712 unset( $this->connFailureTimes
[$serverIndex] );
713 unset( $this->connFailureErrors
[$serverIndex] );
715 $this->logger
->debug( __METHOD__
. ": Server #$serverIndex already down" );
720 $this->logger
->info( __METHOD__
. ": Server #$serverIndex down until " . ( $now +
60 ) );
721 $this->connFailureTimes
[$serverIndex] = $now;
722 $this->connFailureErrors
[$serverIndex] = $exception;
726 * Create shard tables. For use from eval.php.
728 public function createTables() {
729 for ( $serverIndex = 0; $serverIndex < $this->numServers
; $serverIndex++
) {
730 $db = $this->getDB( $serverIndex );
731 if ( $db->getType() !== 'mysql' ) {
732 throw new MWException( __METHOD__
. ' is not supported on this DB server' );
735 for ( $i = 0; $i < $this->shards
; $i++
) {
737 'CREATE TABLE ' . $db->tableName( $this->getTableNameByShard( $i ) ) .
738 ' LIKE ' . $db->tableName( 'objectcache' ),
744 protected function waitForSlaves() {
745 if ( !$this->serverInfos
) {
746 // Main LB is used; wait for any slaves to catch up
748 wfGetLBFactory()->waitForReplication( [ 'wiki' => wfWikiID() ] );
750 } catch ( DBReplicationWaitError
$e ) {
754 // Custom DB server list; probably doesn't use replication