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 $db = DatabaseBase
::factory( $type, $info );
149 $db->clearFlag( DBO_TRX
);
152 * We must keep a separate connection to MySQL in order to avoid deadlocks
153 * However, SQLite has an opposite behavior. And PostgreSQL needs to know
154 * if we are in transaction or no
156 if ( wfGetDB( DB_MASTER
)->getType() == 'mysql' ) {
157 $this->lb
= wfGetLBFactory()->newMainLB();
158 $db = $this->lb
->getConnection( DB_MASTER
);
159 $db->clearFlag( DBO_TRX
); // auto-commit mode
161 $db = wfGetDB( DB_MASTER
);
164 if ( $wgDebugDBTransactions ) {
165 $this->logger
->debug( sprintf( "Connection %s will be used for SqlBagOStuff", $db ) );
167 $this->conns
[$serverIndex] = $db;
170 return $this->conns
[$serverIndex];
174 * Get the server index and table name for a given key
176 * @return array Server index and table name
178 protected function getTableByKey( $key ) {
179 if ( $this->shards
> 1 ) {
180 $hash = hexdec( substr( md5( $key ), 0, 8 ) ) & 0x7fffffff;
181 $tableIndex = $hash %
$this->shards
;
185 if ( $this->numServers
> 1 ) {
186 $sortedServers = $this->serverNames
;
187 ArrayUtils
::consistentHashSort( $sortedServers, $key );
188 reset( $sortedServers );
189 $serverIndex = key( $sortedServers );
193 return array( $serverIndex, $this->getTableNameByShard( $tableIndex ) );
197 * Get the table name for a given shard index
201 protected function getTableNameByShard( $index ) {
202 if ( $this->shards
> 1 ) {
203 $decimals = strlen( $this->shards
- 1 );
204 return $this->tableName
.
205 sprintf( "%0{$decimals}d", $index );
207 return $this->tableName
;
213 * @param mixed $casToken [optional]
216 public function get( $key, &$casToken = null ) {
217 $values = $this->getMulti( array( $key ) );
218 if ( array_key_exists( $key, $values ) ) {
219 $casToken = $values[$key];
220 return $values[$key];
229 public function getMulti( array $keys ) {
230 $values = array(); // array of (key => value)
232 $keysByTable = array();
233 foreach ( $keys as $key ) {
234 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
235 $keysByTable[$serverIndex][$tableName][] = $key;
238 $this->garbageCollect(); // expire old entries if any
241 foreach ( $keysByTable as $serverIndex => $serverKeys ) {
243 $db = $this->getDB( $serverIndex );
244 foreach ( $serverKeys as $tableName => $tableKeys ) {
245 $res = $db->select( $tableName,
246 array( 'keyname', 'value', 'exptime' ),
247 array( 'keyname' => $tableKeys ),
249 // Approximate write-on-the-fly BagOStuff API via blocking.
250 // This approximation fails if a ROLLBACK happens (which is rare).
251 // We do not want to flush the TRX as that can break callers.
252 $db->trxLevel() ?
array( 'LOCK IN SHARE MODE' ) : array()
254 if ( $res === false ) {
257 foreach ( $res as $row ) {
258 $row->serverIndex
= $serverIndex;
259 $row->tableName
= $tableName;
260 $dataRows[$row->keyname
] = $row;
263 } catch ( DBError
$e ) {
264 $this->handleReadError( $e, $serverIndex );
268 foreach ( $keys as $key ) {
269 if ( isset( $dataRows[$key] ) ) { // HIT?
270 $row = $dataRows[$key];
271 $this->debug( "get: retrieved data; expiry time is " . $row->exptime
);
273 $db = $this->getDB( $row->serverIndex
);
274 if ( $this->isExpired( $db, $row->exptime
) ) { // MISS
275 $this->debug( "get: key has expired, deleting" );
276 # Put the expiry time in the WHERE condition to avoid deleting a
277 # newly-inserted value
278 $db->delete( $row->tableName
,
279 array( 'keyname' => $key, 'exptime' => $row->exptime
),
282 $values[$key] = $this->unserialize( $db->decodeBlob( $row->value
) );
284 } catch ( DBQueryError
$e ) {
285 $this->handleWriteError( $e, $row->serverIndex
);
288 $this->debug( 'get: no matching rows' );
300 public function setMulti( array $data, $expiry = 0 ) {
301 $keysByTable = array();
302 foreach ( $data as $key => $value ) {
303 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
304 $keysByTable[$serverIndex][$tableName][] = $key;
307 $this->garbageCollect(); // expire old entries if any
310 $exptime = (int)$expiry;
311 foreach ( $keysByTable as $serverIndex => $serverKeys ) {
313 $db = $this->getDB( $serverIndex );
314 } catch ( DBError
$e ) {
315 $this->handleWriteError( $e, $serverIndex );
320 if ( $exptime < 0 ) {
324 if ( $exptime == 0 ) {
325 $encExpiry = $this->getMaxDateTime( $db );
327 $exptime = $this->convertExpiry( $exptime );
328 $encExpiry = $db->timestamp( $exptime );
330 foreach ( $serverKeys as $tableName => $tableKeys ) {
332 foreach ( $tableKeys as $key ) {
335 'value' => $db->encodeBlob( $this->serialize( $data[$key] ) ),
336 'exptime' => $encExpiry,
347 } catch ( DBError
$e ) {
348 $this->handleWriteError( $e, $serverIndex );
363 * @param mixed $value
364 * @param int $exptime
367 public function set( $key, $value, $exptime = 0 ) {
368 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
370 $db = $this->getDB( $serverIndex );
371 $exptime = intval( $exptime );
373 if ( $exptime < 0 ) {
377 if ( $exptime == 0 ) {
378 $encExpiry = $this->getMaxDateTime( $db );
380 $exptime = $this->convertExpiry( $exptime );
381 $encExpiry = $db->timestamp( $exptime );
383 // (bug 24425) use a replace if the db supports it instead of
384 // delete/insert to avoid clashes with conflicting keynames
390 'value' => $db->encodeBlob( $this->serialize( $value ) ),
391 'exptime' => $encExpiry
393 } catch ( DBError
$e ) {
394 $this->handleWriteError( $e, $serverIndex );
402 * @param mixed $casToken
404 * @param mixed $value
405 * @param int $exptime
408 public function cas( $casToken, $key, $value, $exptime = 0 ) {
409 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
411 $db = $this->getDB( $serverIndex );
412 $exptime = intval( $exptime );
414 if ( $exptime < 0 ) {
418 if ( $exptime == 0 ) {
419 $encExpiry = $this->getMaxDateTime( $db );
421 $exptime = $this->convertExpiry( $exptime );
422 $encExpiry = $db->timestamp( $exptime );
424 // (bug 24425) use a replace if the db supports it instead of
425 // delete/insert to avoid clashes with conflicting keynames
430 'value' => $db->encodeBlob( $this->serialize( $value ) ),
431 'exptime' => $encExpiry
435 'value' => $db->encodeBlob( $this->serialize( $casToken ) )
439 } catch ( DBQueryError
$e ) {
440 $this->handleWriteError( $e, $serverIndex );
445 return (bool)$db->affectedRows();
453 public function delete( $key, $time = 0 ) {
454 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
456 $db = $this->getDB( $serverIndex );
459 array( 'keyname' => $key ),
461 } catch ( DBError
$e ) {
462 $this->handleWriteError( $e, $serverIndex );
474 public function incr( $key, $step = 1 ) {
475 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
477 $db = $this->getDB( $serverIndex );
478 $step = intval( $step );
479 $row = $db->selectRow(
481 array( 'value', 'exptime' ),
482 array( 'keyname' => $key ),
484 array( 'FOR UPDATE' ) );
485 if ( $row === false ) {
490 $db->delete( $tableName, array( 'keyname' => $key ), __METHOD__
);
491 if ( $this->isExpired( $db, $row->exptime
) ) {
492 // Expired, do not reinsert
497 $oldValue = intval( $this->unserialize( $db->decodeBlob( $row->value
) ) );
498 $newValue = $oldValue +
$step;
499 $db->insert( $tableName,
502 'value' => $db->encodeBlob( $this->serialize( $newValue ) ),
503 'exptime' => $row->exptime
504 ), __METHOD__
, 'IGNORE' );
506 if ( $db->affectedRows() == 0 ) {
507 // Race condition. See bug 28611
510 } catch ( DBError
$e ) {
511 $this->handleWriteError( $e, $serverIndex );
519 * @param DatabaseBase $db
520 * @param string $exptime
523 protected function isExpired( $db, $exptime ) {
524 return $exptime != $this->getMaxDateTime( $db ) && wfTimestamp( TS_UNIX
, $exptime ) < time();
528 * @param DatabaseBase $db
531 protected function getMaxDateTime( $db ) {
532 if ( time() > 0x7fffffff ) {
533 return $db->timestamp( 1 << 62 );
535 return $db->timestamp( 0x7fffffff );
539 protected function garbageCollect() {
540 if ( !$this->purgePeriod
) {
544 // Only purge on one in every $this->purgePeriod requests.
545 if ( $this->purgePeriod
!== 1 && mt_rand( 0, $this->purgePeriod
- 1 ) ) {
549 // Avoid repeating the delete within a few seconds
550 if ( $now > ( $this->lastExpireAll +
1 ) ) {
551 $this->lastExpireAll
= $now;
556 public function expireAll() {
557 $this->deleteObjectsExpiringBefore( wfTimestampNow() );
561 * Delete objects from the database which expire before a certain date.
562 * @param string $timestamp
563 * @param bool|callable $progressCallback
566 public function deleteObjectsExpiringBefore( $timestamp, $progressCallback = false ) {
567 for ( $serverIndex = 0; $serverIndex < $this->numServers
; $serverIndex++
) {
569 $db = $this->getDB( $serverIndex );
570 $dbTimestamp = $db->timestamp( $timestamp );
571 $totalSeconds = false;
572 $baseConds = array( 'exptime < ' . $db->addQuotes( $dbTimestamp ) );
573 for ( $i = 0; $i < $this->shards
; $i++
) {
577 if ( $maxExpTime !== false ) {
578 $conds[] = 'exptime > ' . $db->addQuotes( $maxExpTime );
581 $this->getTableNameByShard( $i ),
582 array( 'keyname', 'exptime' ),
585 array( 'LIMIT' => 100, 'ORDER BY' => 'exptime' ) );
586 if ( $rows === false ||
!$rows->numRows() ) {
590 $row = $rows->current();
591 $minExpTime = $row->exptime
;
592 if ( $totalSeconds === false ) {
593 $totalSeconds = wfTimestamp( TS_UNIX
, $timestamp )
594 - wfTimestamp( TS_UNIX
, $minExpTime );
596 foreach ( $rows as $row ) {
597 $keys[] = $row->keyname
;
598 $maxExpTime = $row->exptime
;
602 $this->getTableNameByShard( $i ),
604 'exptime >= ' . $db->addQuotes( $minExpTime ),
605 'exptime < ' . $db->addQuotes( $dbTimestamp ),
610 if ( $progressCallback ) {
611 if ( intval( $totalSeconds ) === 0 ) {
614 $remainingSeconds = wfTimestamp( TS_UNIX
, $timestamp )
615 - wfTimestamp( TS_UNIX
, $maxExpTime );
616 if ( $remainingSeconds > $totalSeconds ) {
617 $totalSeconds = $remainingSeconds;
619 $processedSeconds = $totalSeconds - $remainingSeconds;
620 $percent = ( $i +
$processedSeconds / $totalSeconds )
621 / $this->shards
* 100;
623 $percent = ( $percent / $this->numServers
)
624 +
( $serverIndex / $this->numServers
* 100 );
625 call_user_func( $progressCallback, $percent );
629 } catch ( DBError
$e ) {
630 $this->handleWriteError( $e, $serverIndex );
638 * Delete content of shard tables in every server.
639 * Return true if the operation is successful, false otherwise.
642 public function deleteAll() {
643 for ( $serverIndex = 0; $serverIndex < $this->numServers
; $serverIndex++
) {
645 $db = $this->getDB( $serverIndex );
646 for ( $i = 0; $i < $this->shards
; $i++
) {
647 $db->delete( $this->getTableNameByShard( $i ), '*', __METHOD__
);
649 } catch ( DBError
$e ) {
650 $this->handleWriteError( $e, $serverIndex );
658 * Serialize an object and, if possible, compress the representation.
659 * On typical message and page data, this can provide a 3X decrease
660 * in storage requirements.
665 protected function serialize( &$data ) {
666 $serial = serialize( $data );
668 if ( function_exists( 'gzdeflate' ) ) {
669 return gzdeflate( $serial );
676 * Unserialize and, if necessary, decompress an object.
677 * @param string $serial
680 protected function unserialize( $serial ) {
681 if ( function_exists( 'gzinflate' ) ) {
682 wfSuppressWarnings();
683 $decomp = gzinflate( $serial );
686 if ( false !== $decomp ) {
691 $ret = unserialize( $serial );
697 * Handle a DBError which occurred during a read operation.
699 * @param DBError $exception
700 * @param int $serverIndex
702 protected function handleReadError( DBError
$exception, $serverIndex ) {
703 if ( $exception instanceof DBConnectionError
) {
704 $this->markServerDown( $exception, $serverIndex );
706 $this->logger
->error( "DBError: {$exception->getMessage()}" );
707 if ( $exception instanceof DBConnectionError
) {
708 $this->setLastError( BagOStuff
::ERR_UNREACHABLE
);
709 $this->logger
->debug( __METHOD__
. ": ignoring connection error" );
711 $this->setLastError( BagOStuff
::ERR_UNEXPECTED
);
712 $this->logger
->debug( __METHOD__
. ": ignoring query error" );
717 * Handle a DBQueryError which occurred during a write operation.
719 * @param DBError $exception
720 * @param int $serverIndex
722 protected function handleWriteError( DBError
$exception, $serverIndex ) {
723 if ( $exception instanceof DBConnectionError
) {
724 $this->markServerDown( $exception, $serverIndex );
726 if ( $exception->db
&& $exception->db
->wasReadOnlyError() ) {
728 $exception->db
->rollback( __METHOD__
);
729 } catch ( DBError
$e ) {
733 $this->logger
->error( "DBError: {$exception->getMessage()}" );
734 if ( $exception instanceof DBConnectionError
) {
735 $this->setLastError( BagOStuff
::ERR_UNREACHABLE
);
736 $this->logger
->debug( __METHOD__
. ": ignoring connection error" );
738 $this->setLastError( BagOStuff
::ERR_UNEXPECTED
);
739 $this->logger
->debug( __METHOD__
. ": ignoring query error" );
744 * Mark a server down due to a DBConnectionError exception
746 * @param DBError $exception
747 * @param int $serverIndex
749 protected function markServerDown( $exception, $serverIndex ) {
750 if ( isset( $this->connFailureTimes
[$serverIndex] ) ) {
751 if ( time() - $this->connFailureTimes
[$serverIndex] >= 60 ) {
752 unset( $this->connFailureTimes
[$serverIndex] );
753 unset( $this->connFailureErrors
[$serverIndex] );
755 $this->logger
->debug( __METHOD__
. ": Server #$serverIndex already down" );
760 $this->logger
->info( __METHOD__
. ": Server #$serverIndex down until " . ( $now +
60 ) );
761 $this->connFailureTimes
[$serverIndex] = $now;
762 $this->connFailureErrors
[$serverIndex] = $exception;
766 * Create shard tables. For use from eval.php.
768 public function createTables() {
769 for ( $serverIndex = 0; $serverIndex < $this->numServers
; $serverIndex++
) {
770 $db = $this->getDB( $serverIndex );
771 if ( $db->getType() !== 'mysql' ) {
772 throw new MWException( __METHOD__
. ' is not supported on this DB server' );
775 for ( $i = 0; $i < $this->shards
; $i++
) {
777 'CREATE TABLE ' . $db->tableName( $this->getTableNameByShard( $i ) ) .
778 ' LIKE ' . $db->tableName( 'objectcache' ),
786 * Backwards compatibility alias
788 class MediaWikiBagOStuff
extends SqlBagOStuff
{