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;
36 protected $serverNames;
39 protected $numServers;
45 protected $lastExpireAll = 0;
48 protected $purgePeriod = 100;
51 protected $shards = 1;
54 protected $tableName = 'objectcache';
56 /** @var array UNIX timestamps */
57 protected $connFailureTimes = array();
59 /** @var array Exceptions */
60 protected $connFailureErrors = array();
63 * Constructor. Parameters are:
64 * - server: A server info structure in the format required by each
65 * element in $wgDBServers.
67 * - servers: An array of server info structures describing a set of
68 * database servers to distribute keys to. If this is
69 * specified, the "server" option will be ignored.
71 * - purgePeriod: The average number of object cache requests in between
72 * garbage collection operations, where expired entries
73 * are removed from the database. Or in other words, the
74 * reciprocal of the probability of purging on any given
75 * request. If this is set to zero, purging will never be
78 * - tableName: The table name to use, default is "objectcache".
80 * - shards: The number of tables to use for data storage on each server.
81 * If this is more than 1, table names will be formed in the style
82 * objectcacheNNN where NNN is the shard index, between 0 and
83 * shards-1. The number of digits will be the minimum number
84 * required to hold the largest shard index. Data will be
85 * distributed across all tables by key hash. This is for
86 * MySQL bugs 61735 and 61736.
88 * @param array $params
90 public function __construct( $params ) {
91 parent
::__construct( $params );
92 if ( isset( $params['servers'] ) ) {
93 $this->serverInfos
= $params['servers'];
94 $this->numServers
= count( $this->serverInfos
);
95 $this->serverNames
= array();
96 foreach ( $this->serverInfos
as $i => $info ) {
97 $this->serverNames
[$i] = isset( $info['host'] ) ?
$info['host'] : "#$i";
99 } elseif ( isset( $params['server'] ) ) {
100 $this->serverInfos
= array( $params['server'] );
101 $this->numServers
= count( $this->serverInfos
);
103 $this->serverInfos
= false;
104 $this->numServers
= 1;
106 if ( isset( $params['purgePeriod'] ) ) {
107 $this->purgePeriod
= intval( $params['purgePeriod'] );
109 if ( isset( $params['tableName'] ) ) {
110 $this->tableName
= $params['tableName'];
112 if ( isset( $params['shards'] ) ) {
113 $this->shards
= intval( $params['shards'] );
118 * Get a connection to the specified database
120 * @param int $serverIndex
121 * @return DatabaseBase
122 * @throws MWException
124 protected function getDB( $serverIndex ) {
125 global $wgDebugDBTransactions;
127 if ( !isset( $this->conns
[$serverIndex] ) ) {
128 if ( $serverIndex >= $this->numServers
) {
129 throw new MWException( __METHOD__
. ": Invalid server index \"$serverIndex\"" );
132 # Don't keep timing out trying to connect for each call if the DB is down
133 if ( isset( $this->connFailureErrors
[$serverIndex] )
134 && ( time() - $this->connFailureTimes
[$serverIndex] ) < 60
136 throw $this->connFailureErrors
[$serverIndex];
139 # If server connection info was given, use that
140 if ( $this->serverInfos
) {
141 if ( $wgDebugDBTransactions ) {
142 $this->logger
->debug( "Using provided serverInfo for SqlBagOStuff" );
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 if ( wfGetDB( DB_MASTER
)->getType() == 'mysql' ) {
159 $this->lb
= wfGetLBFactory()->newMainLB();
160 $db = $this->lb
->getConnection( DB_MASTER
);
161 $db->clearFlag( DBO_TRX
); // auto-commit mode
163 $db = wfGetDB( DB_MASTER
);
166 if ( $wgDebugDBTransactions ) {
167 $this->logger
->debug( sprintf( "Connection %s will be used for SqlBagOStuff", $db ) );
169 $this->conns
[$serverIndex] = $db;
172 return $this->conns
[$serverIndex];
176 * Get the server index and table name for a given key
178 * @return array Server index and table name
180 protected function getTableByKey( $key ) {
181 if ( $this->shards
> 1 ) {
182 $hash = hexdec( substr( md5( $key ), 0, 8 ) ) & 0x7fffffff;
183 $tableIndex = $hash %
$this->shards
;
187 if ( $this->numServers
> 1 ) {
188 $sortedServers = $this->serverNames
;
189 ArrayUtils
::consistentHashSort( $sortedServers, $key );
190 reset( $sortedServers );
191 $serverIndex = key( $sortedServers );
195 return array( $serverIndex, $this->getTableNameByShard( $tableIndex ) );
199 * Get the table name for a given shard index
203 protected function getTableNameByShard( $index ) {
204 if ( $this->shards
> 1 ) {
205 $decimals = strlen( $this->shards
- 1 );
206 return $this->tableName
.
207 sprintf( "%0{$decimals}d", $index );
209 return $this->tableName
;
215 * @param mixed $casToken [optional]
218 public function get( $key, &$casToken = null ) {
219 $values = $this->getMulti( array( $key ) );
220 if ( array_key_exists( $key, $values ) ) {
221 $casToken = $values[$key];
222 return $values[$key];
231 public function getMulti( array $keys ) {
232 $values = array(); // array of (key => value)
234 $keysByTable = array();
235 foreach ( $keys as $key ) {
236 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
237 $keysByTable[$serverIndex][$tableName][] = $key;
240 $this->garbageCollect(); // expire old entries if any
243 foreach ( $keysByTable as $serverIndex => $serverKeys ) {
245 $db = $this->getDB( $serverIndex );
246 foreach ( $serverKeys as $tableName => $tableKeys ) {
247 $res = $db->select( $tableName,
248 array( 'keyname', 'value', 'exptime' ),
249 array( 'keyname' => $tableKeys ),
251 // Approximate write-on-the-fly BagOStuff API via blocking.
252 // This approximation fails if a ROLLBACK happens (which is rare).
253 // We do not want to flush the TRX as that can break callers.
254 $db->trxLevel() ?
array( 'LOCK IN SHARE MODE' ) : array()
256 if ( $res === false ) {
259 foreach ( $res as $row ) {
260 $row->serverIndex
= $serverIndex;
261 $row->tableName
= $tableName;
262 $dataRows[$row->keyname
] = $row;
265 } catch ( DBError
$e ) {
266 $this->handleReadError( $e, $serverIndex );
270 foreach ( $keys as $key ) {
271 if ( isset( $dataRows[$key] ) ) { // HIT?
272 $row = $dataRows[$key];
273 $this->debug( "get: retrieved data; expiry time is " . $row->exptime
);
275 $db = $this->getDB( $row->serverIndex
);
276 if ( $this->isExpired( $db, $row->exptime
) ) { // MISS
277 $this->debug( "get: key has expired, deleting" );
278 # Put the expiry time in the WHERE condition to avoid deleting a
279 # newly-inserted value
280 $db->delete( $row->tableName
,
281 array( 'keyname' => $key, 'exptime' => $row->exptime
),
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' );
302 public function setMulti( array $data, $expiry = 0 ) {
303 $keysByTable = array();
304 foreach ( $data as $key => $value ) {
305 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
306 $keysByTable[$serverIndex][$tableName][] = $key;
309 $this->garbageCollect(); // expire old entries if any
312 $exptime = (int)$expiry;
313 foreach ( $keysByTable as $serverIndex => $serverKeys ) {
315 $db = $this->getDB( $serverIndex );
316 } catch ( DBError
$e ) {
317 $this->handleWriteError( $e, $serverIndex );
322 if ( $exptime < 0 ) {
326 if ( $exptime == 0 ) {
327 $encExpiry = $this->getMaxDateTime( $db );
329 $exptime = $this->convertExpiry( $exptime );
330 $encExpiry = $db->timestamp( $exptime );
332 foreach ( $serverKeys as $tableName => $tableKeys ) {
334 foreach ( $tableKeys as $key ) {
337 'value' => $db->encodeBlob( $this->serialize( $data[$key] ) ),
338 'exptime' => $encExpiry,
349 } catch ( DBError
$e ) {
350 $this->handleWriteError( $e, $serverIndex );
363 * @param mixed $value
364 * @param int $exptime
367 public function set( $key, $value, $exptime = 0 ) {
368 return $this->setMulti( array( $key => $value ), $exptime );
372 * @param mixed $casToken
374 * @param mixed $value
375 * @param int $exptime
378 protected function cas( $casToken, $key, $value, $exptime = 0 ) {
379 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
381 $db = $this->getDB( $serverIndex );
382 $exptime = intval( $exptime );
384 if ( $exptime < 0 ) {
388 if ( $exptime == 0 ) {
389 $encExpiry = $this->getMaxDateTime( $db );
391 $exptime = $this->convertExpiry( $exptime );
392 $encExpiry = $db->timestamp( $exptime );
394 // (bug 24425) use a replace if the db supports it instead of
395 // delete/insert to avoid clashes with conflicting keynames
400 'value' => $db->encodeBlob( $this->serialize( $value ) ),
401 'exptime' => $encExpiry
405 'value' => $db->encodeBlob( $this->serialize( $casToken ) )
409 } catch ( DBQueryError
$e ) {
410 $this->handleWriteError( $e, $serverIndex );
415 return (bool)$db->affectedRows();
422 public function delete( $key ) {
423 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
425 $db = $this->getDB( $serverIndex );
428 array( 'keyname' => $key ),
430 } catch ( DBError
$e ) {
431 $this->handleWriteError( $e, $serverIndex );
443 public function incr( $key, $step = 1 ) {
444 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
446 $db = $this->getDB( $serverIndex );
447 $step = intval( $step );
448 $row = $db->selectRow(
450 array( 'value', 'exptime' ),
451 array( 'keyname' => $key ),
453 array( 'FOR UPDATE' ) );
454 if ( $row === false ) {
459 $db->delete( $tableName, array( 'keyname' => $key ), __METHOD__
);
460 if ( $this->isExpired( $db, $row->exptime
) ) {
461 // Expired, do not reinsert
466 $oldValue = intval( $this->unserialize( $db->decodeBlob( $row->value
) ) );
467 $newValue = $oldValue +
$step;
468 $db->insert( $tableName,
471 'value' => $db->encodeBlob( $this->serialize( $newValue ) ),
472 'exptime' => $row->exptime
473 ), __METHOD__
, 'IGNORE' );
475 if ( $db->affectedRows() == 0 ) {
476 // Race condition. See bug 28611
479 } catch ( DBError
$e ) {
480 $this->handleWriteError( $e, $serverIndex );
487 public function merge( $key, $callback, $exptime = 0, $attempts = 10 ) {
488 if ( !is_callable( $callback ) ) {
489 throw new Exception( "Got invalid callback." );
492 return $this->mergeViaCas( $key, $callback, $exptime, $attempts );
496 * @param DatabaseBase $db
497 * @param string $exptime
500 protected function isExpired( $db, $exptime ) {
501 return $exptime != $this->getMaxDateTime( $db ) && wfTimestamp( TS_UNIX
, $exptime ) < time();
505 * @param DatabaseBase $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
) {
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 = array( '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 array( 'keyname', 'exptime' ),
562 array( '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 if ( isset( $this->connFailureTimes
[$serverIndex] ) ) {
730 if ( time() - $this->connFailureTimes
[$serverIndex] >= 60 ) {
731 unset( $this->connFailureTimes
[$serverIndex] );
732 unset( $this->connFailureErrors
[$serverIndex] );
734 $this->logger
->debug( __METHOD__
. ": Server #$serverIndex already down" );
739 $this->logger
->info( __METHOD__
. ": Server #$serverIndex down until " . ( $now +
60 ) );
740 $this->connFailureTimes
[$serverIndex] = $now;
741 $this->connFailureErrors
[$serverIndex] = $exception;
745 * Create shard tables. For use from eval.php.
747 public function createTables() {
748 for ( $serverIndex = 0; $serverIndex < $this->numServers
; $serverIndex++
) {
749 $db = $this->getDB( $serverIndex );
750 if ( $db->getType() !== 'mysql' ) {
751 throw new MWException( __METHOD__
. ' is not supported on this DB server' );
754 for ( $i = 0; $i < $this->shards
; $i++
) {
756 'CREATE TABLE ' . $db->tableName( $this->getTableNameByShard( $i ) ) .
757 ' LIKE ' . $db->tableName( 'objectcache' ),