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 */
34 protected $serverInfos;
37 protected $serverNames;
40 protected $numServers;
46 protected $lastExpireAll = 0;
49 protected $purgePeriod = 100;
52 protected $shards = 1;
55 protected $tableName = 'objectcache';
58 protected $slaveOnly = false;
60 /** @var array UNIX timestamps */
61 protected $connFailureTimes = array();
63 /** @var array Exceptions */
64 protected $connFailureErrors = array();
67 * Constructor. Parameters are:
68 * - server: A server info structure in the format required by each
69 * element in $wgDBServers.
71 * - servers: An array of server info structures describing a set of
72 * database servers to distribute keys to. If this is
73 * specified, the "server" option will be ignored.
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 slave 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.
96 * @param array $params
98 public function __construct( $params ) {
99 parent
::__construct( $params );
100 if ( isset( $params['servers'] ) ) {
101 $this->serverInfos
= $params['servers'];
102 $this->numServers
= count( $this->serverInfos
);
103 $this->serverNames
= array();
104 foreach ( $this->serverInfos
as $i => $info ) {
105 $this->serverNames
[$i] = isset( $info['host'] ) ?
$info['host'] : "#$i";
107 } elseif ( isset( $params['server'] ) ) {
108 $this->serverInfos
= array( $params['server'] );
109 $this->numServers
= count( $this->serverInfos
);
111 $this->serverInfos
= false;
112 $this->numServers
= 1;
114 if ( isset( $params['purgePeriod'] ) ) {
115 $this->purgePeriod
= intval( $params['purgePeriod'] );
117 if ( isset( $params['tableName'] ) ) {
118 $this->tableName
= $params['tableName'];
120 if ( isset( $params['shards'] ) ) {
121 $this->shards
= intval( $params['shards'] );
123 $this->slaveOnly
= !empty( $params['slaveOnly'] );
127 * Get a connection to the specified database
129 * @param int $serverIndex
130 * @return DatabaseBase
131 * @throws MWException
133 protected function getDB( $serverIndex ) {
134 global $wgDebugDBTransactions;
136 if ( !isset( $this->conns
[$serverIndex] ) ) {
137 if ( $serverIndex >= $this->numServers
) {
138 throw new MWException( __METHOD__
. ": Invalid server index \"$serverIndex\"" );
141 # Don't keep timing out trying to connect for each call if the DB is down
142 if ( isset( $this->connFailureErrors
[$serverIndex] )
143 && ( time() - $this->connFailureTimes
[$serverIndex] ) < 60
145 throw $this->connFailureErrors
[$serverIndex];
148 # If server connection info was given, use that
149 if ( $this->serverInfos
) {
150 if ( $wgDebugDBTransactions ) {
151 $this->logger
->debug( "Using provided serverInfo for SqlBagOStuff" );
153 $info = $this->serverInfos
[$serverIndex];
154 $type = isset( $info['type'] ) ?
$info['type'] : 'mysql';
155 $host = isset( $info['host'] ) ?
$info['host'] : '[unknown]';
156 $this->logger
->debug( __CLASS__
. ": connecting to $host" );
157 // Use a blank trx profiler to ignore expections as this is a cache
158 $info['trxProfiler'] = new TransactionProfiler();
159 $db = DatabaseBase
::factory( $type, $info );
160 $db->clearFlag( DBO_TRX
);
163 * We must keep a separate connection to MySQL in order to avoid deadlocks
164 * However, SQLite has an opposite behavior. And PostgreSQL needs to know
165 * if we are in transaction or no
167 $index = $this->slaveOnly ? DB_SLAVE
: DB_MASTER
;
168 if ( wfGetDB( $index )->getType() == 'mysql' ) {
169 $this->lb
= wfGetLBFactory()->newMainLB();
170 $db = $this->lb
->getConnection( $index );
171 $db->clearFlag( DBO_TRX
); // auto-commit mode
173 $db = wfGetDB( $index );
176 if ( $wgDebugDBTransactions ) {
177 $this->logger
->debug( sprintf( "Connection %s will be used for SqlBagOStuff", $db ) );
179 $this->conns
[$serverIndex] = $db;
182 return $this->conns
[$serverIndex];
186 * Get the server index and table name for a given key
188 * @return array Server index and table name
190 protected function getTableByKey( $key ) {
191 if ( $this->shards
> 1 ) {
192 $hash = hexdec( substr( md5( $key ), 0, 8 ) ) & 0x7fffffff;
193 $tableIndex = $hash %
$this->shards
;
197 if ( $this->numServers
> 1 ) {
198 $sortedServers = $this->serverNames
;
199 ArrayUtils
::consistentHashSort( $sortedServers, $key );
200 reset( $sortedServers );
201 $serverIndex = key( $sortedServers );
205 return array( $serverIndex, $this->getTableNameByShard( $tableIndex ) );
209 * Get the table name for a given shard index
213 protected function getTableNameByShard( $index ) {
214 if ( $this->shards
> 1 ) {
215 $decimals = strlen( $this->shards
- 1 );
216 return $this->tableName
.
217 sprintf( "%0{$decimals}d", $index );
219 return $this->tableName
;
225 * @param mixed $casToken [optional]
228 public function get( $key, &$casToken = null ) {
229 $values = $this->getMulti( array( $key ) );
230 if ( array_key_exists( $key, $values ) ) {
231 $casToken = $values[$key];
232 return $values[$key];
241 public function getMulti( array $keys ) {
242 $values = array(); // array of (key => value)
244 $keysByTable = array();
245 foreach ( $keys as $key ) {
246 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
247 $keysByTable[$serverIndex][$tableName][] = $key;
250 $this->garbageCollect(); // expire old entries if any
253 foreach ( $keysByTable as $serverIndex => $serverKeys ) {
255 $db = $this->getDB( $serverIndex );
256 foreach ( $serverKeys as $tableName => $tableKeys ) {
257 $res = $db->select( $tableName,
258 array( 'keyname', 'value', 'exptime' ),
259 array( 'keyname' => $tableKeys ),
261 // Approximate write-on-the-fly BagOStuff API via blocking.
262 // This approximation fails if a ROLLBACK happens (which is rare).
263 // We do not want to flush the TRX as that can break callers.
264 $db->trxLevel() ?
array( 'LOCK IN SHARE MODE' ) : array()
266 if ( $res === false ) {
269 foreach ( $res as $row ) {
270 $row->serverIndex
= $serverIndex;
271 $row->tableName
= $tableName;
272 $dataRows[$row->keyname
] = $row;
275 } catch ( DBError
$e ) {
276 $this->handleReadError( $e, $serverIndex );
280 foreach ( $keys as $key ) {
281 if ( isset( $dataRows[$key] ) ) { // HIT?
282 $row = $dataRows[$key];
283 $this->debug( "get: retrieved data; expiry time is " . $row->exptime
);
285 $db = $this->getDB( $row->serverIndex
);
286 if ( $this->isExpired( $db, $row->exptime
) ) { // MISS
287 $this->debug( "get: key has expired" );
289 $values[$key] = $this->unserialize( $db->decodeBlob( $row->value
) );
291 } catch ( DBQueryError
$e ) {
292 $this->handleWriteError( $e, $row->serverIndex
);
295 $this->debug( 'get: no matching rows' );
307 public function setMulti( array $data, $expiry = 0 ) {
308 $keysByTable = array();
309 foreach ( $data as $key => $value ) {
310 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
311 $keysByTable[$serverIndex][$tableName][] = $key;
314 $this->garbageCollect(); // expire old entries if any
317 $exptime = (int)$expiry;
318 foreach ( $keysByTable as $serverIndex => $serverKeys ) {
320 $db = $this->getDB( $serverIndex );
321 } catch ( DBError
$e ) {
322 $this->handleWriteError( $e, $serverIndex );
327 if ( $exptime < 0 ) {
331 if ( $exptime == 0 ) {
332 $encExpiry = $this->getMaxDateTime( $db );
334 $exptime = $this->convertExpiry( $exptime );
335 $encExpiry = $db->timestamp( $exptime );
337 foreach ( $serverKeys as $tableName => $tableKeys ) {
339 foreach ( $tableKeys as $key ) {
342 'value' => $db->encodeBlob( $this->serialize( $data[$key] ) ),
343 'exptime' => $encExpiry,
354 } catch ( DBError
$e ) {
355 $this->handleWriteError( $e, $serverIndex );
370 * @param mixed $value
371 * @param int $exptime
374 public function set( $key, $value, $exptime = 0 ) {
375 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
377 $db = $this->getDB( $serverIndex );
378 $exptime = intval( $exptime );
380 if ( $exptime < 0 ) {
384 if ( $exptime == 0 ) {
385 $encExpiry = $this->getMaxDateTime( $db );
387 $exptime = $this->convertExpiry( $exptime );
388 $encExpiry = $db->timestamp( $exptime );
390 // (bug 24425) use a replace if the db supports it instead of
391 // delete/insert to avoid clashes with conflicting keynames
397 'value' => $db->encodeBlob( $this->serialize( $value ) ),
398 'exptime' => $encExpiry
400 } catch ( DBError
$e ) {
401 $this->handleWriteError( $e, $serverIndex );
409 * @param mixed $casToken
411 * @param mixed $value
412 * @param int $exptime
415 protected function cas( $casToken, $key, $value, $exptime = 0 ) {
416 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
418 $db = $this->getDB( $serverIndex );
419 $exptime = intval( $exptime );
421 if ( $exptime < 0 ) {
425 if ( $exptime == 0 ) {
426 $encExpiry = $this->getMaxDateTime( $db );
428 $exptime = $this->convertExpiry( $exptime );
429 $encExpiry = $db->timestamp( $exptime );
431 // (bug 24425) use a replace if the db supports it instead of
432 // delete/insert to avoid clashes with conflicting keynames
437 'value' => $db->encodeBlob( $this->serialize( $value ) ),
438 'exptime' => $encExpiry
442 'value' => $db->encodeBlob( $this->serialize( $casToken ) )
446 } catch ( DBQueryError
$e ) {
447 $this->handleWriteError( $e, $serverIndex );
452 return (bool)$db->affectedRows();
459 public function delete( $key ) {
460 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
462 $db = $this->getDB( $serverIndex );
465 array( 'keyname' => $key ),
467 } catch ( DBError
$e ) {
468 $this->handleWriteError( $e, $serverIndex );
480 public function incr( $key, $step = 1 ) {
481 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
483 $db = $this->getDB( $serverIndex );
484 $step = intval( $step );
485 $row = $db->selectRow(
487 array( 'value', 'exptime' ),
488 array( 'keyname' => $key ),
490 array( 'FOR UPDATE' ) );
491 if ( $row === false ) {
496 $db->delete( $tableName, array( 'keyname' => $key ), __METHOD__
);
497 if ( $this->isExpired( $db, $row->exptime
) ) {
498 // Expired, do not reinsert
503 $oldValue = intval( $this->unserialize( $db->decodeBlob( $row->value
) ) );
504 $newValue = $oldValue +
$step;
505 $db->insert( $tableName,
508 'value' => $db->encodeBlob( $this->serialize( $newValue ) ),
509 'exptime' => $row->exptime
510 ), __METHOD__
, 'IGNORE' );
512 if ( $db->affectedRows() == 0 ) {
513 // Race condition. See bug 28611
516 } catch ( DBError
$e ) {
517 $this->handleWriteError( $e, $serverIndex );
524 public function merge( $key, $callback, $exptime = 0, $attempts = 10 ) {
525 if ( !is_callable( $callback ) ) {
526 throw new Exception( "Got invalid callback." );
529 return $this->mergeViaCas( $key, $callback, $exptime, $attempts );
533 * @param DatabaseBase $db
534 * @param string $exptime
537 protected function isExpired( $db, $exptime ) {
538 return $exptime != $this->getMaxDateTime( $db ) && wfTimestamp( TS_UNIX
, $exptime ) < time();
542 * @param DatabaseBase $db
545 protected function getMaxDateTime( $db ) {
546 if ( time() > 0x7fffffff ) {
547 return $db->timestamp( 1 << 62 );
549 return $db->timestamp( 0x7fffffff );
553 protected function garbageCollect() {
554 if ( !$this->purgePeriod ||
$this->slaveOnly
) {
558 // Only purge on one in every $this->purgePeriod requests.
559 if ( $this->purgePeriod
!== 1 && mt_rand( 0, $this->purgePeriod
- 1 ) ) {
563 // Avoid repeating the delete within a few seconds
564 if ( $now > ( $this->lastExpireAll +
1 ) ) {
565 $this->lastExpireAll
= $now;
570 public function expireAll() {
571 $this->deleteObjectsExpiringBefore( wfTimestampNow() );
575 * Delete objects from the database which expire before a certain date.
576 * @param string $timestamp
577 * @param bool|callable $progressCallback
580 public function deleteObjectsExpiringBefore( $timestamp, $progressCallback = false ) {
581 for ( $serverIndex = 0; $serverIndex < $this->numServers
; $serverIndex++
) {
583 $db = $this->getDB( $serverIndex );
584 $dbTimestamp = $db->timestamp( $timestamp );
585 $totalSeconds = false;
586 $baseConds = array( 'exptime < ' . $db->addQuotes( $dbTimestamp ) );
587 for ( $i = 0; $i < $this->shards
; $i++
) {
591 if ( $maxExpTime !== false ) {
592 $conds[] = 'exptime > ' . $db->addQuotes( $maxExpTime );
595 $this->getTableNameByShard( $i ),
596 array( 'keyname', 'exptime' ),
599 array( 'LIMIT' => 100, 'ORDER BY' => 'exptime' ) );
600 if ( $rows === false ||
!$rows->numRows() ) {
604 $row = $rows->current();
605 $minExpTime = $row->exptime
;
606 if ( $totalSeconds === false ) {
607 $totalSeconds = wfTimestamp( TS_UNIX
, $timestamp )
608 - wfTimestamp( TS_UNIX
, $minExpTime );
610 foreach ( $rows as $row ) {
611 $keys[] = $row->keyname
;
612 $maxExpTime = $row->exptime
;
616 $this->getTableNameByShard( $i ),
618 'exptime >= ' . $db->addQuotes( $minExpTime ),
619 'exptime < ' . $db->addQuotes( $dbTimestamp ),
624 if ( $progressCallback ) {
625 if ( intval( $totalSeconds ) === 0 ) {
628 $remainingSeconds = wfTimestamp( TS_UNIX
, $timestamp )
629 - wfTimestamp( TS_UNIX
, $maxExpTime );
630 if ( $remainingSeconds > $totalSeconds ) {
631 $totalSeconds = $remainingSeconds;
633 $processedSeconds = $totalSeconds - $remainingSeconds;
634 $percent = ( $i +
$processedSeconds / $totalSeconds )
635 / $this->shards
* 100;
637 $percent = ( $percent / $this->numServers
)
638 +
( $serverIndex / $this->numServers
* 100 );
639 call_user_func( $progressCallback, $percent );
643 } catch ( DBError
$e ) {
644 $this->handleWriteError( $e, $serverIndex );
652 * Delete content of shard tables in every server.
653 * Return true if the operation is successful, false otherwise.
656 public function deleteAll() {
657 for ( $serverIndex = 0; $serverIndex < $this->numServers
; $serverIndex++
) {
659 $db = $this->getDB( $serverIndex );
660 for ( $i = 0; $i < $this->shards
; $i++
) {
661 $db->delete( $this->getTableNameByShard( $i ), '*', __METHOD__
);
663 } catch ( DBError
$e ) {
664 $this->handleWriteError( $e, $serverIndex );
672 * Serialize an object and, if possible, compress the representation.
673 * On typical message and page data, this can provide a 3X decrease
674 * in storage requirements.
679 protected function serialize( &$data ) {
680 $serial = serialize( $data );
682 if ( function_exists( 'gzdeflate' ) ) {
683 return gzdeflate( $serial );
690 * Unserialize and, if necessary, decompress an object.
691 * @param string $serial
694 protected function unserialize( $serial ) {
695 if ( function_exists( 'gzinflate' ) ) {
696 wfSuppressWarnings();
697 $decomp = gzinflate( $serial );
700 if ( false !== $decomp ) {
705 $ret = unserialize( $serial );
711 * Handle a DBError which occurred during a read operation.
713 * @param DBError $exception
714 * @param int $serverIndex
716 protected function handleReadError( DBError
$exception, $serverIndex ) {
717 if ( $exception instanceof DBConnectionError
) {
718 $this->markServerDown( $exception, $serverIndex );
720 $this->logger
->error( "DBError: {$exception->getMessage()}" );
721 if ( $exception instanceof DBConnectionError
) {
722 $this->setLastError( BagOStuff
::ERR_UNREACHABLE
);
723 $this->logger
->debug( __METHOD__
. ": ignoring connection error" );
725 $this->setLastError( BagOStuff
::ERR_UNEXPECTED
);
726 $this->logger
->debug( __METHOD__
. ": ignoring query error" );
731 * Handle a DBQueryError which occurred during a write operation.
733 * @param DBError $exception
734 * @param int $serverIndex
736 protected function handleWriteError( DBError
$exception, $serverIndex ) {
737 if ( $exception instanceof DBConnectionError
) {
738 $this->markServerDown( $exception, $serverIndex );
740 if ( $exception->db
&& $exception->db
->wasReadOnlyError() ) {
741 if ( $exception->db
->trxLevel() ) {
743 $exception->db
->rollback( __METHOD__
);
744 } catch ( DBError
$e ) {
749 $this->logger
->error( "DBError: {$exception->getMessage()}" );
750 if ( $exception instanceof DBConnectionError
) {
751 $this->setLastError( BagOStuff
::ERR_UNREACHABLE
);
752 $this->logger
->debug( __METHOD__
. ": ignoring connection error" );
754 $this->setLastError( BagOStuff
::ERR_UNEXPECTED
);
755 $this->logger
->debug( __METHOD__
. ": ignoring query error" );
760 * Mark a server down due to a DBConnectionError exception
762 * @param DBError $exception
763 * @param int $serverIndex
765 protected function markServerDown( $exception, $serverIndex ) {
766 if ( isset( $this->connFailureTimes
[$serverIndex] ) ) {
767 if ( time() - $this->connFailureTimes
[$serverIndex] >= 60 ) {
768 unset( $this->connFailureTimes
[$serverIndex] );
769 unset( $this->connFailureErrors
[$serverIndex] );
771 $this->logger
->debug( __METHOD__
. ": Server #$serverIndex already down" );
776 $this->logger
->info( __METHOD__
. ": Server #$serverIndex down until " . ( $now +
60 ) );
777 $this->connFailureTimes
[$serverIndex] = $now;
778 $this->connFailureErrors
[$serverIndex] = $exception;
782 * Create shard tables. For use from eval.php.
784 public function createTables() {
785 for ( $serverIndex = 0; $serverIndex < $this->numServers
; $serverIndex++
) {
786 $db = $this->getDB( $serverIndex );
787 if ( $db->getType() !== 'mysql' ) {
788 throw new MWException( __METHOD__
. ' is not supported on this DB server' );
791 for ( $i = 0; $i < $this->shards
; $i++
) {
793 'CREATE TABLE ' . $db->tableName( $this->getTableNameByShard( $i ) ) .
794 ' LIKE ' . $db->tableName( 'objectcache' ),