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 LoadBalancer */
33 protected $serverInfos;
35 protected $serverNames;
37 protected $numServers;
39 protected $lastExpireAll = 0;
41 protected $purgePeriod = 100;
43 protected $shards = 1;
45 protected $tableName = 'objectcache';
47 protected $slaveOnly = false;
49 protected $syncTimeout = 3;
53 /** @var array UNIX timestamps */
54 protected $connFailureTimes = array();
55 /** @var array Exceptions */
56 protected $connFailureErrors = array();
59 * Constructor. Parameters are:
60 * - server: A server info structure in the format required by each
61 * element in $wgDBServers.
63 * - servers: An array of server info structures describing a set of
64 * database servers to distribute keys to. If this is
65 * specified, the "server" option will be ignored.
67 * - purgePeriod: The average number of object cache requests in between
68 * garbage collection operations, where expired entries
69 * are removed from the database. Or in other words, the
70 * reciprocal of the probability of purging on any given
71 * request. If this is set to zero, purging will never be
74 * - tableName: The table name to use, default is "objectcache".
76 * - shards: The number of tables to use for data storage on each server.
77 * If this is more than 1, table names will be formed in the style
78 * objectcacheNNN where NNN is the shard index, between 0 and
79 * shards-1. The number of digits will be the minimum number
80 * required to hold the largest shard index. Data will be
81 * distributed across all tables by key hash. This is for
82 * MySQL bugs 61735 and 61736.
83 * - slaveOnly: Whether to only use slave DBs and avoid triggering
84 * garbage collection logic of expired items. This only
85 * makes sense if the primary DB is used and only if get()
86 * calls will be used. This is used by ReplicatedBagOStuff.
87 * - syncTimeout: Max seconds to wait for slaves to catch up for WRITE_SYNC.
89 * @param array $params
91 public function __construct( $params ) {
92 parent
::__construct( $params );
93 if ( isset( $params['servers'] ) ) {
94 $this->serverInfos
= $params['servers'];
95 $this->numServers
= count( $this->serverInfos
);
96 $this->serverNames
= array();
97 foreach ( $this->serverInfos
as $i => $info ) {
98 $this->serverNames
[$i] = isset( $info['host'] ) ?
$info['host'] : "#$i";
100 } elseif ( isset( $params['server'] ) ) {
101 $this->serverInfos
= array( $params['server'] );
102 $this->numServers
= count( $this->serverInfos
);
104 $this->serverInfos
= false;
105 $this->numServers
= 1;
107 if ( isset( $params['purgePeriod'] ) ) {
108 $this->purgePeriod
= intval( $params['purgePeriod'] );
110 if ( isset( $params['tableName'] ) ) {
111 $this->tableName
= $params['tableName'];
113 if ( isset( $params['shards'] ) ) {
114 $this->shards
= intval( $params['shards'] );
116 if ( isset( $params['syncTimeout'] ) ) {
117 $this->syncTimeout
= $params['syncTimeout'];
119 $this->slaveOnly
= !empty( $params['slaveOnly'] );
123 * Get a connection to the specified database
125 * @param int $serverIndex
127 * @throws MWException
129 protected function getDB( $serverIndex ) {
130 if ( !isset( $this->conns
[$serverIndex] ) ) {
131 if ( $serverIndex >= $this->numServers
) {
132 throw new MWException( __METHOD__
. ": Invalid server index \"$serverIndex\"" );
135 # Don't keep timing out trying to connect for each call if the DB is down
136 if ( isset( $this->connFailureErrors
[$serverIndex] )
137 && ( time() - $this->connFailureTimes
[$serverIndex] ) < 60
139 throw $this->connFailureErrors
[$serverIndex];
142 # If server connection info was given, use that
143 if ( $this->serverInfos
) {
144 $info = $this->serverInfos
[$serverIndex];
145 $type = isset( $info['type'] ) ?
$info['type'] : 'mysql';
146 $host = isset( $info['host'] ) ?
$info['host'] : '[unknown]';
147 $this->logger
->debug( __CLASS__
. ": connecting to $host" );
148 // Use a blank trx profiler to ignore expections as this is a cache
149 $info['trxProfiler'] = new TransactionProfiler();
150 $db = DatabaseBase
::factory( $type, $info );
151 $db->clearFlag( DBO_TRX
);
154 * We must keep a separate connection to MySQL in order to avoid deadlocks
155 * However, SQLite has an opposite behavior. And PostgreSQL needs to know
156 * if we are in transaction or no
158 $index = $this->slaveOnly ? DB_SLAVE
: DB_MASTER
;
159 if ( wfGetDB( $index )->getType() == 'mysql' ) {
160 $this->lb
= wfGetLBFactory()->newMainLB();
161 $db = $this->lb
->getConnection( $index );
162 $db->clearFlag( DBO_TRX
); // auto-commit mode
164 $db = wfGetDB( $index );
167 $this->logger
->debug( sprintf( "Connection %s will be used for SqlBagOStuff", $db ) );
168 $this->conns
[$serverIndex] = $db;
171 return $this->conns
[$serverIndex];
175 * Get the server index and table name for a given key
177 * @return array Server index and table name
179 protected function getTableByKey( $key ) {
180 if ( $this->shards
> 1 ) {
181 $hash = hexdec( substr( md5( $key ), 0, 8 ) ) & 0x7fffffff;
182 $tableIndex = $hash %
$this->shards
;
186 if ( $this->numServers
> 1 ) {
187 $sortedServers = $this->serverNames
;
188 ArrayUtils
::consistentHashSort( $sortedServers, $key );
189 reset( $sortedServers );
190 $serverIndex = key( $sortedServers );
194 return array( $serverIndex, $this->getTableNameByShard( $tableIndex ) );
198 * Get the table name for a given shard index
202 protected function getTableNameByShard( $index ) {
203 if ( $this->shards
> 1 ) {
204 $decimals = strlen( $this->shards
- 1 );
205 return $this->tableName
.
206 sprintf( "%0{$decimals}d", $index );
208 return $this->tableName
;
212 protected function doGet( $key, $flags = 0 ) {
215 return $this->getWithToken( $key, $casToken, $flags );
218 protected function getWithToken( $key, &$casToken, $flags = 0 ) {
219 $values = $this->getMulti( array( $key ) );
220 if ( array_key_exists( $key, $values ) ) {
221 $casToken = $values[$key];
222 return $values[$key];
227 public function getMulti( array $keys, $flags = 0 ) {
228 $values = array(); // array of (key => value)
230 $keysByTable = array();
231 foreach ( $keys as $key ) {
232 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
233 $keysByTable[$serverIndex][$tableName][] = $key;
236 $this->garbageCollect(); // expire old entries if any
239 foreach ( $keysByTable as $serverIndex => $serverKeys ) {
241 $db = $this->getDB( $serverIndex );
242 foreach ( $serverKeys as $tableName => $tableKeys ) {
243 $res = $db->select( $tableName,
244 array( 'keyname', 'value', 'exptime' ),
245 array( 'keyname' => $tableKeys ),
247 // Approximate write-on-the-fly BagOStuff API via blocking.
248 // This approximation fails if a ROLLBACK happens (which is rare).
249 // We do not want to flush the TRX as that can break callers.
250 $db->trxLevel() ?
array( 'LOCK IN SHARE MODE' ) : array()
252 if ( $res === false ) {
255 foreach ( $res as $row ) {
256 $row->serverIndex
= $serverIndex;
257 $row->tableName
= $tableName;
258 $dataRows[$row->keyname
] = $row;
261 } catch ( DBError
$e ) {
262 $this->handleReadError( $e, $serverIndex );
266 foreach ( $keys as $key ) {
267 if ( isset( $dataRows[$key] ) ) { // HIT?
268 $row = $dataRows[$key];
269 $this->debug( "get: retrieved data; expiry time is " . $row->exptime
);
271 $db = $this->getDB( $row->serverIndex
);
272 if ( $this->isExpired( $db, $row->exptime
) ) { // MISS
273 $this->debug( "get: key has expired" );
275 $values[$key] = $this->unserialize( $db->decodeBlob( $row->value
) );
277 } catch ( DBQueryError
$e ) {
278 $this->handleWriteError( $e, $row->serverIndex
);
281 $this->debug( 'get: no matching rows' );
288 public function setMulti( array $data, $expiry = 0 ) {
289 $keysByTable = array();
290 foreach ( $data as $key => $value ) {
291 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
292 $keysByTable[$serverIndex][$tableName][] = $key;
295 $this->garbageCollect(); // expire old entries if any
298 $exptime = (int)$expiry;
299 foreach ( $keysByTable as $serverIndex => $serverKeys ) {
301 $db = $this->getDB( $serverIndex );
302 } catch ( DBError
$e ) {
303 $this->handleWriteError( $e, $serverIndex );
308 if ( $exptime < 0 ) {
312 if ( $exptime == 0 ) {
313 $encExpiry = $this->getMaxDateTime( $db );
315 $exptime = $this->convertExpiry( $exptime );
316 $encExpiry = $db->timestamp( $exptime );
318 foreach ( $serverKeys as $tableName => $tableKeys ) {
320 foreach ( $tableKeys as $key ) {
323 'value' => $db->encodeBlob( $this->serialize( $data[$key] ) ),
324 'exptime' => $encExpiry,
335 } catch ( DBError
$e ) {
336 $this->handleWriteError( $e, $serverIndex );
347 public function set( $key, $value, $exptime = 0, $flags = 0 ) {
348 $ok = $this->setMulti( array( $key => $value ), $exptime );
349 if ( ( $flags & self
::WRITE_SYNC
) == self
::WRITE_SYNC
) {
350 $ok = $ok && $this->waitForSlaves();
356 protected function cas( $casToken, $key, $value, $exptime = 0 ) {
357 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
359 $db = $this->getDB( $serverIndex );
360 $exptime = intval( $exptime );
362 if ( $exptime < 0 ) {
366 if ( $exptime == 0 ) {
367 $encExpiry = $this->getMaxDateTime( $db );
369 $exptime = $this->convertExpiry( $exptime );
370 $encExpiry = $db->timestamp( $exptime );
372 // (bug 24425) use a replace if the db supports it instead of
373 // delete/insert to avoid clashes with conflicting keynames
378 'value' => $db->encodeBlob( $this->serialize( $value ) ),
379 'exptime' => $encExpiry
383 'value' => $db->encodeBlob( $this->serialize( $casToken ) )
387 } catch ( DBQueryError
$e ) {
388 $this->handleWriteError( $e, $serverIndex );
393 return (bool)$db->affectedRows();
396 public function delete( $key ) {
397 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
399 $db = $this->getDB( $serverIndex );
402 array( 'keyname' => $key ),
404 } catch ( DBError
$e ) {
405 $this->handleWriteError( $e, $serverIndex );
412 public function incr( $key, $step = 1 ) {
413 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
415 $db = $this->getDB( $serverIndex );
416 $step = intval( $step );
417 $row = $db->selectRow(
419 array( 'value', 'exptime' ),
420 array( 'keyname' => $key ),
422 array( 'FOR UPDATE' ) );
423 if ( $row === false ) {
428 $db->delete( $tableName, array( 'keyname' => $key ), __METHOD__
);
429 if ( $this->isExpired( $db, $row->exptime
) ) {
430 // Expired, do not reinsert
435 $oldValue = intval( $this->unserialize( $db->decodeBlob( $row->value
) ) );
436 $newValue = $oldValue +
$step;
437 $db->insert( $tableName,
440 'value' => $db->encodeBlob( $this->serialize( $newValue ) ),
441 'exptime' => $row->exptime
442 ), __METHOD__
, 'IGNORE' );
444 if ( $db->affectedRows() == 0 ) {
445 // Race condition. See bug 28611
448 } catch ( DBError
$e ) {
449 $this->handleWriteError( $e, $serverIndex );
456 public function merge( $key, $callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
457 if ( !is_callable( $callback ) ) {
458 throw new Exception( "Got invalid callback." );
461 $ok = $this->mergeViaCas( $key, $callback, $exptime, $attempts );
462 if ( ( $flags & self
::WRITE_SYNC
) == self
::WRITE_SYNC
) {
463 $ok = $ok && $this->waitForSlaves();
470 * @param IDatabase $db
471 * @param string $exptime
474 protected function isExpired( $db, $exptime ) {
475 return $exptime != $this->getMaxDateTime( $db ) && wfTimestamp( TS_UNIX
, $exptime ) < time();
479 * @param IDatabase $db
482 protected function getMaxDateTime( $db ) {
483 if ( time() > 0x7fffffff ) {
484 return $db->timestamp( 1 << 62 );
486 return $db->timestamp( 0x7fffffff );
490 protected function garbageCollect() {
491 if ( !$this->purgePeriod ||
$this->slaveOnly
) {
495 // Only purge on one in every $this->purgePeriod requests.
496 if ( $this->purgePeriod
!== 1 && mt_rand( 0, $this->purgePeriod
- 1 ) ) {
500 // Avoid repeating the delete within a few seconds
501 if ( $now > ( $this->lastExpireAll +
1 ) ) {
502 $this->lastExpireAll
= $now;
507 public function expireAll() {
508 $this->deleteObjectsExpiringBefore( wfTimestampNow() );
512 * Delete objects from the database which expire before a certain date.
513 * @param string $timestamp
514 * @param bool|callable $progressCallback
517 public function deleteObjectsExpiringBefore( $timestamp, $progressCallback = false ) {
518 for ( $serverIndex = 0; $serverIndex < $this->numServers
; $serverIndex++
) {
520 $db = $this->getDB( $serverIndex );
521 $dbTimestamp = $db->timestamp( $timestamp );
522 $totalSeconds = false;
523 $baseConds = array( 'exptime < ' . $db->addQuotes( $dbTimestamp ) );
524 for ( $i = 0; $i < $this->shards
; $i++
) {
528 if ( $maxExpTime !== false ) {
529 $conds[] = 'exptime > ' . $db->addQuotes( $maxExpTime );
532 $this->getTableNameByShard( $i ),
533 array( 'keyname', 'exptime' ),
536 array( 'LIMIT' => 100, 'ORDER BY' => 'exptime' ) );
537 if ( $rows === false ||
!$rows->numRows() ) {
541 $row = $rows->current();
542 $minExpTime = $row->exptime
;
543 if ( $totalSeconds === false ) {
544 $totalSeconds = wfTimestamp( TS_UNIX
, $timestamp )
545 - wfTimestamp( TS_UNIX
, $minExpTime );
547 foreach ( $rows as $row ) {
548 $keys[] = $row->keyname
;
549 $maxExpTime = $row->exptime
;
553 $this->getTableNameByShard( $i ),
555 'exptime >= ' . $db->addQuotes( $minExpTime ),
556 'exptime < ' . $db->addQuotes( $dbTimestamp ),
561 if ( $progressCallback ) {
562 if ( intval( $totalSeconds ) === 0 ) {
565 $remainingSeconds = wfTimestamp( TS_UNIX
, $timestamp )
566 - wfTimestamp( TS_UNIX
, $maxExpTime );
567 if ( $remainingSeconds > $totalSeconds ) {
568 $totalSeconds = $remainingSeconds;
570 $processedSeconds = $totalSeconds - $remainingSeconds;
571 $percent = ( $i +
$processedSeconds / $totalSeconds )
572 / $this->shards
* 100;
574 $percent = ( $percent / $this->numServers
)
575 +
( $serverIndex / $this->numServers
* 100 );
576 call_user_func( $progressCallback, $percent );
580 } catch ( DBError
$e ) {
581 $this->handleWriteError( $e, $serverIndex );
589 * Delete content of shard tables in every server.
590 * Return true if the operation is successful, false otherwise.
593 public function deleteAll() {
594 for ( $serverIndex = 0; $serverIndex < $this->numServers
; $serverIndex++
) {
596 $db = $this->getDB( $serverIndex );
597 for ( $i = 0; $i < $this->shards
; $i++
) {
598 $db->delete( $this->getTableNameByShard( $i ), '*', __METHOD__
);
600 } catch ( DBError
$e ) {
601 $this->handleWriteError( $e, $serverIndex );
609 * Serialize an object and, if possible, compress the representation.
610 * On typical message and page data, this can provide a 3X decrease
611 * in storage requirements.
616 protected function serialize( &$data ) {
617 $serial = serialize( $data );
619 if ( function_exists( 'gzdeflate' ) ) {
620 return gzdeflate( $serial );
627 * Unserialize and, if necessary, decompress an object.
628 * @param string $serial
631 protected function unserialize( $serial ) {
632 if ( function_exists( 'gzinflate' ) ) {
633 MediaWiki\
suppressWarnings();
634 $decomp = gzinflate( $serial );
635 MediaWiki\restoreWarnings
();
637 if ( false !== $decomp ) {
642 $ret = unserialize( $serial );
648 * Handle a DBError which occurred during a read operation.
650 * @param DBError $exception
651 * @param int $serverIndex
653 protected function handleReadError( DBError
$exception, $serverIndex ) {
654 if ( $exception instanceof DBConnectionError
) {
655 $this->markServerDown( $exception, $serverIndex );
657 $this->logger
->error( "DBError: {$exception->getMessage()}" );
658 if ( $exception instanceof DBConnectionError
) {
659 $this->setLastError( BagOStuff
::ERR_UNREACHABLE
);
660 $this->logger
->debug( __METHOD__
. ": ignoring connection error" );
662 $this->setLastError( BagOStuff
::ERR_UNEXPECTED
);
663 $this->logger
->debug( __METHOD__
. ": ignoring query error" );
668 * Handle a DBQueryError which occurred during a write operation.
670 * @param DBError $exception
671 * @param int $serverIndex
673 protected function handleWriteError( DBError
$exception, $serverIndex ) {
674 if ( $exception instanceof DBConnectionError
) {
675 $this->markServerDown( $exception, $serverIndex );
677 if ( $exception->db
&& $exception->db
->wasReadOnlyError() ) {
678 if ( $exception->db
->trxLevel() ) {
680 $exception->db
->rollback( __METHOD__
);
681 } catch ( DBError
$e ) {
686 $this->logger
->error( "DBError: {$exception->getMessage()}" );
687 if ( $exception instanceof DBConnectionError
) {
688 $this->setLastError( BagOStuff
::ERR_UNREACHABLE
);
689 $this->logger
->debug( __METHOD__
. ": ignoring connection error" );
691 $this->setLastError( BagOStuff
::ERR_UNEXPECTED
);
692 $this->logger
->debug( __METHOD__
. ": ignoring query error" );
697 * Mark a server down due to a DBConnectionError exception
699 * @param DBError $exception
700 * @param int $serverIndex
702 protected function markServerDown( $exception, $serverIndex ) {
703 unset( $this->conns
[$serverIndex] ); // bug T103435
705 if ( isset( $this->connFailureTimes
[$serverIndex] ) ) {
706 if ( time() - $this->connFailureTimes
[$serverIndex] >= 60 ) {
707 unset( $this->connFailureTimes
[$serverIndex] );
708 unset( $this->connFailureErrors
[$serverIndex] );
710 $this->logger
->debug( __METHOD__
. ": Server #$serverIndex already down" );
715 $this->logger
->info( __METHOD__
. ": Server #$serverIndex down until " . ( $now +
60 ) );
716 $this->connFailureTimes
[$serverIndex] = $now;
717 $this->connFailureErrors
[$serverIndex] = $exception;
721 * Create shard tables. For use from eval.php.
723 public function createTables() {
724 for ( $serverIndex = 0; $serverIndex < $this->numServers
; $serverIndex++
) {
725 $db = $this->getDB( $serverIndex );
726 if ( $db->getType() !== 'mysql' ) {
727 throw new MWException( __METHOD__
. ' is not supported on this DB server' );
730 for ( $i = 0; $i < $this->shards
; $i++
) {
732 'CREATE TABLE ' . $db->tableName( $this->getTableNameByShard( $i ) ) .
733 ' LIKE ' . $db->tableName( 'objectcache' ),
739 protected function waitForSlaves() {
740 if ( !$this->serverInfos
) {
741 // Main LB is used; wait for any slaves to catch up
742 return wfWaitForSlaves( null, false, false, $this->syncTimeout
);
744 // Custom DB server list; probably doesn't use replication