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
{
39 var $lastExpireAll = 0;
40 var $purgePeriod = 100;
42 var $tableName = 'objectcache';
44 protected $connFailureTimes = array(); // UNIX timestamps
45 protected $connFailureErrors = array(); // exceptions
48 * Constructor. Parameters are:
49 * - server: A server info structure in the format required by each
50 * element in $wgDBServers.
52 * - servers: An array of server info structures describing a set of
53 * database servers to distribute keys to. If this is
54 * specified, the "server" option will be ignored.
56 * - purgePeriod: The average number of object cache requests in between
57 * garbage collection operations, where expired entries
58 * are removed from the database. Or in other words, the
59 * reciprocal of the probability of purging on any given
60 * request. If this is set to zero, purging will never be
63 * - tableName: The table name to use, default is "objectcache".
65 * - shards: The number of tables to use for data storage on each server.
66 * If this is more than 1, table names will be formed in the style
67 * objectcacheNNN where NNN is the shard index, between 0 and
68 * shards-1. The number of digits will be the minimum number
69 * required to hold the largest shard index. Data will be
70 * distributed across all tables by key hash. This is for
71 * MySQL bugs 61735 and 61736.
73 * @param array $params
75 public function __construct( $params ) {
76 if ( isset( $params['servers'] ) ) {
77 $this->serverInfos
= $params['servers'];
78 $this->numServers
= count( $this->serverInfos
);
79 $this->serverNames
= array();
80 foreach ( $this->serverInfos
as $i => $info ) {
81 $this->serverNames
[$i] = isset( $info['host'] ) ?
$info['host'] : "#$i";
83 } elseif ( isset( $params['server'] ) ) {
84 $this->serverInfos
= array( $params['server'] );
85 $this->numServers
= count( $this->serverInfos
);
87 $this->serverInfos
= false;
88 $this->numServers
= 1;
90 if ( isset( $params['purgePeriod'] ) ) {
91 $this->purgePeriod
= intval( $params['purgePeriod'] );
93 if ( isset( $params['tableName'] ) ) {
94 $this->tableName
= $params['tableName'];
96 if ( isset( $params['shards'] ) ) {
97 $this->shards
= intval( $params['shards'] );
102 * Get a connection to the specified database
104 * @param int $serverIndex
105 * @return DatabaseBase
107 protected function getDB( $serverIndex ) {
108 global $wgDebugDBTransactions;
110 if ( !isset( $this->conns
[$serverIndex] ) ) {
111 if ( $serverIndex >= $this->numServers
) {
112 throw new MWException( __METHOD__
. ": Invalid server index \"$serverIndex\"" );
115 # Don't keep timing out trying to connect for each call if the DB is down
116 if ( isset( $this->connFailureErrors
[$serverIndex] )
117 && ( time() - $this->connFailureTimes
[$serverIndex] ) < 60
119 throw $this->connFailureErrors
[$serverIndex];
122 # If server connection info was given, use that
123 if ( $this->serverInfos
) {
124 if ( $wgDebugDBTransactions ) {
125 wfDebug( "Using provided serverInfo for SqlBagOStuff\n" );
127 $info = $this->serverInfos
[$serverIndex];
128 $type = isset( $info['type'] ) ?
$info['type'] : 'mysql';
129 $host = isset( $info['host'] ) ?
$info['host'] : '[unknown]';
130 wfDebug( __CLASS__
. ": connecting to $host\n" );
131 $db = DatabaseBase
::factory( $type, $info );
132 $db->clearFlag( DBO_TRX
);
135 * We must keep a separate connection to MySQL in order to avoid deadlocks
136 * However, SQLite has an opposite behavior. And PostgreSQL needs to know
137 * if we are in transaction or no
139 if ( wfGetDB( DB_MASTER
)->getType() == 'mysql' ) {
140 $this->lb
= wfGetLBFactory()->newMainLB();
141 $db = $this->lb
->getConnection( DB_MASTER
);
142 $db->clearFlag( DBO_TRX
); // auto-commit mode
144 $db = wfGetDB( DB_MASTER
);
147 if ( $wgDebugDBTransactions ) {
148 wfDebug( sprintf( "Connection %s will be used for SqlBagOStuff\n", $db ) );
150 $this->conns
[$serverIndex] = $db;
153 return $this->conns
[$serverIndex];
157 * Get the server index and table name for a given key
159 * @return array Server index and table name
161 protected function getTableByKey( $key ) {
162 if ( $this->shards
> 1 ) {
163 $hash = hexdec( substr( md5( $key ), 0, 8 ) ) & 0x7fffffff;
164 $tableIndex = $hash %
$this->shards
;
168 if ( $this->numServers
> 1 ) {
169 $sortedServers = $this->serverNames
;
170 ArrayUtils
::consistentHashSort( $sortedServers, $key );
171 reset( $sortedServers );
172 $serverIndex = key( $sortedServers );
176 return array( $serverIndex, $this->getTableNameByShard( $tableIndex ) );
180 * Get the table name for a given shard index
184 protected function getTableNameByShard( $index ) {
185 if ( $this->shards
> 1 ) {
186 $decimals = strlen( $this->shards
- 1 );
187 return $this->tableName
.
188 sprintf( "%0{$decimals}d", $index );
190 return $this->tableName
;
196 * @param mixed $casToken [optional]
199 public function get( $key, &$casToken = null ) {
200 $values = $this->getMulti( array( $key ) );
201 if ( array_key_exists( $key, $values ) ) {
202 $casToken = $values[$key];
203 return $values[$key];
212 public function getMulti( array $keys ) {
213 $values = array(); // array of (key => value)
215 $keysByTable = array();
216 foreach ( $keys as $key ) {
217 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
218 $keysByTable[$serverIndex][$tableName][] = $key;
221 $this->garbageCollect(); // expire old entries if any
224 foreach ( $keysByTable as $serverIndex => $serverKeys ) {
226 $db = $this->getDB( $serverIndex );
227 foreach ( $serverKeys as $tableName => $tableKeys ) {
228 $res = $db->select( $tableName,
229 array( 'keyname', 'value', 'exptime' ),
230 array( 'keyname' => $tableKeys ),
232 foreach ( $res as $row ) {
233 $row->serverIndex
= $serverIndex;
234 $row->tableName
= $tableName;
235 $dataRows[$row->keyname
] = $row;
238 } catch ( DBError
$e ) {
239 $this->handleReadError( $e, $serverIndex );
243 foreach ( $keys as $key ) {
244 if ( isset( $dataRows[$key] ) ) { // HIT?
245 $row = $dataRows[$key];
246 $this->debug( "get: retrieved data; expiry time is " . $row->exptime
);
248 $db = $this->getDB( $row->serverIndex
);
249 if ( $this->isExpired( $db, $row->exptime
) ) { // MISS
250 $this->debug( "get: key has expired, deleting" );
251 $db->commit( __METHOD__
, 'flush' );
252 # Put the expiry time in the WHERE condition to avoid deleting a
253 # newly-inserted value
254 $db->delete( $row->tableName
,
255 array( 'keyname' => $key, 'exptime' => $row->exptime
),
257 $db->commit( __METHOD__
, 'flush' );
258 $values[$key] = false;
260 $values[$key] = $this->unserialize( $db->decodeBlob( $row->value
) );
262 } catch ( DBQueryError
$e ) {
263 $this->handleWriteError( $e, $row->serverIndex
);
266 $values[$key] = false;
267 $this->debug( 'get: no matching rows' );
276 * @param mixed $value
277 * @param int $exptime
280 public function set( $key, $value, $exptime = 0 ) {
281 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
283 $db = $this->getDB( $serverIndex );
284 $exptime = intval( $exptime );
286 if ( $exptime < 0 ) {
290 if ( $exptime == 0 ) {
291 $encExpiry = $this->getMaxDateTime( $db );
293 if ( $exptime < 3.16e8
) { # ~10 years
297 $encExpiry = $db->timestamp( $exptime );
299 $db->commit( __METHOD__
, 'flush' );
300 // (bug 24425) use a replace if the db supports it instead of
301 // delete/insert to avoid clashes with conflicting keynames
307 'value' => $db->encodeBlob( $this->serialize( $value ) ),
308 'exptime' => $encExpiry
310 $db->commit( __METHOD__
, 'flush' );
311 } catch ( DBError
$e ) {
312 $this->handleWriteError( $e, $serverIndex );
320 * @param mixed $casToken
322 * @param mixed $value
323 * @param int $exptime
326 public function cas( $casToken, $key, $value, $exptime = 0 ) {
327 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
329 $db = $this->getDB( $serverIndex );
330 $exptime = intval( $exptime );
332 if ( $exptime < 0 ) {
336 if ( $exptime == 0 ) {
337 $encExpiry = $this->getMaxDateTime( $db );
339 if ( $exptime < 3.16e8
) { # ~10 years
342 $encExpiry = $db->timestamp( $exptime );
344 $db->commit( __METHOD__
, 'flush' );
345 // (bug 24425) use a replace if the db supports it instead of
346 // delete/insert to avoid clashes with conflicting keynames
351 'value' => $db->encodeBlob( $this->serialize( $value ) ),
352 'exptime' => $encExpiry
356 'value' => $db->encodeBlob( $this->serialize( $casToken ) )
360 $db->commit( __METHOD__
, 'flush' );
361 } catch ( DBQueryError
$e ) {
362 $this->handleWriteError( $e, $serverIndex );
367 return (bool)$db->affectedRows();
375 public function delete( $key, $time = 0 ) {
376 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
378 $db = $this->getDB( $serverIndex );
379 $db->commit( __METHOD__
, 'flush' );
382 array( 'keyname' => $key ),
384 $db->commit( __METHOD__
, 'flush' );
385 } catch ( DBError
$e ) {
386 $this->handleWriteError( $e, $serverIndex );
398 public function incr( $key, $step = 1 ) {
399 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
401 $db = $this->getDB( $serverIndex );
402 $step = intval( $step );
403 $db->commit( __METHOD__
, 'flush' );
404 $row = $db->selectRow(
406 array( 'value', 'exptime' ),
407 array( 'keyname' => $key ),
409 array( 'FOR UPDATE' ) );
410 if ( $row === false ) {
412 $db->commit( __METHOD__
, 'flush' );
416 $db->delete( $tableName, array( 'keyname' => $key ), __METHOD__
);
417 if ( $this->isExpired( $db, $row->exptime
) ) {
418 // Expired, do not reinsert
419 $db->commit( __METHOD__
, 'flush' );
424 $oldValue = intval( $this->unserialize( $db->decodeBlob( $row->value
) ) );
425 $newValue = $oldValue +
$step;
426 $db->insert( $tableName,
429 'value' => $db->encodeBlob( $this->serialize( $newValue ) ),
430 'exptime' => $row->exptime
431 ), __METHOD__
, 'IGNORE' );
433 if ( $db->affectedRows() == 0 ) {
434 // Race condition. See bug 28611
437 $db->commit( __METHOD__
, 'flush' );
438 } catch ( DBError
$e ) {
439 $this->handleWriteError( $e, $serverIndex );
447 * @param string $exptime
450 protected function isExpired( $db, $exptime ) {
451 return $exptime != $this->getMaxDateTime( $db ) && wfTimestamp( TS_UNIX
, $exptime ) < time();
455 * @param DatabaseBase $db
458 protected function getMaxDateTime( $db ) {
459 if ( time() > 0x7fffffff ) {
460 return $db->timestamp( 1 << 62 );
462 return $db->timestamp( 0x7fffffff );
466 protected function garbageCollect() {
467 if ( !$this->purgePeriod
) {
471 // Only purge on one in every $this->purgePeriod requests.
472 if ( $this->purgePeriod
!== 1 && mt_rand( 0, $this->purgePeriod
- 1 ) ) {
476 // Avoid repeating the delete within a few seconds
477 if ( $now > ( $this->lastExpireAll +
1 ) ) {
478 $this->lastExpireAll
= $now;
483 public function expireAll() {
484 $this->deleteObjectsExpiringBefore( wfTimestampNow() );
488 * Delete objects from the database which expire before a certain date.
489 * @param string $timestamp
490 * @param bool|callable $progressCallback
493 public function deleteObjectsExpiringBefore( $timestamp, $progressCallback = false ) {
494 for ( $serverIndex = 0; $serverIndex < $this->numServers
; $serverIndex++
) {
496 $db = $this->getDB( $serverIndex );
497 $dbTimestamp = $db->timestamp( $timestamp );
498 $totalSeconds = false;
499 $baseConds = array( 'exptime < ' . $db->addQuotes( $dbTimestamp ) );
500 for ( $i = 0; $i < $this->shards
; $i++
) {
504 if ( $maxExpTime !== false ) {
505 $conds[] = 'exptime > ' . $db->addQuotes( $maxExpTime );
508 $this->getTableNameByShard( $i ),
509 array( 'keyname', 'exptime' ),
512 array( 'LIMIT' => 100, 'ORDER BY' => 'exptime' ) );
513 if ( !$rows->numRows() ) {
517 $row = $rows->current();
518 $minExpTime = $row->exptime
;
519 if ( $totalSeconds === false ) {
520 $totalSeconds = wfTimestamp( TS_UNIX
, $timestamp )
521 - wfTimestamp( TS_UNIX
, $minExpTime );
523 foreach ( $rows as $row ) {
524 $keys[] = $row->keyname
;
525 $maxExpTime = $row->exptime
;
528 $db->commit( __METHOD__
, 'flush' );
530 $this->getTableNameByShard( $i ),
532 'exptime >= ' . $db->addQuotes( $minExpTime ),
533 'exptime < ' . $db->addQuotes( $dbTimestamp ),
537 $db->commit( __METHOD__
, 'flush' );
539 if ( $progressCallback ) {
540 if ( intval( $totalSeconds ) === 0 ) {
543 $remainingSeconds = wfTimestamp( TS_UNIX
, $timestamp )
544 - wfTimestamp( TS_UNIX
, $maxExpTime );
545 if ( $remainingSeconds > $totalSeconds ) {
546 $totalSeconds = $remainingSeconds;
548 $percent = ( $i +
$remainingSeconds / $totalSeconds )
549 / $this->shards
* 100;
551 $percent = ( $percent / $this->numServers
)
552 +
( $serverIndex / $this->numServers
* 100 );
553 call_user_func( $progressCallback, $percent );
557 } catch ( DBError
$e ) {
558 $this->handleWriteError( $e, $serverIndex );
565 public function deleteAll() {
566 for ( $serverIndex = 0; $serverIndex < $this->numServers
; $serverIndex++
) {
568 $db = $this->getDB( $serverIndex );
569 for ( $i = 0; $i < $this->shards
; $i++
) {
570 $db->commit( __METHOD__
, 'flush' );
571 $db->delete( $this->getTableNameByShard( $i ), '*', __METHOD__
);
572 $db->commit( __METHOD__
, 'flush' );
574 } catch ( DBError
$e ) {
575 $this->handleWriteError( $e, $serverIndex );
583 * Serialize an object and, if possible, compress the representation.
584 * On typical message and page data, this can provide a 3X decrease
585 * in storage requirements.
590 protected function serialize( &$data ) {
591 $serial = serialize( $data );
593 if ( function_exists( 'gzdeflate' ) ) {
594 return gzdeflate( $serial );
601 * Unserialize and, if necessary, decompress an object.
602 * @param string $serial
605 protected function unserialize( $serial ) {
606 if ( function_exists( 'gzinflate' ) ) {
607 wfSuppressWarnings();
608 $decomp = gzinflate( $serial );
611 if ( false !== $decomp ) {
616 $ret = unserialize( $serial );
622 * Handle a DBError which occurred during a read operation.
624 * @param DBError $exception
625 * @param int $serverIndex
627 protected function handleReadError( DBError
$exception, $serverIndex ) {
628 if ( $exception instanceof DBConnectionError
) {
629 $this->markServerDown( $exception, $serverIndex );
631 wfDebugLog( 'SQLBagOStuff', "DBError: {$exception->getMessage()}" );
632 if ( $exception instanceof DBConnectionError
) {
633 $this->setLastError( BagOStuff
::ERR_UNREACHABLE
);
634 wfDebug( __METHOD__
. ": ignoring connection error\n" );
636 $this->setLastError( BagOStuff
::ERR_UNEXPECTED
);
637 wfDebug( __METHOD__
. ": ignoring query error\n" );
642 * Handle a DBQueryError which occurred during a write operation.
644 * @param DBError $exception
645 * @param int $serverIndex
647 protected function handleWriteError( DBError
$exception, $serverIndex ) {
648 if ( $exception instanceof DBConnectionError
) {
649 $this->markServerDown( $exception, $serverIndex );
651 if ( $exception->db
&& $exception->db
->wasReadOnlyError() ) {
653 $exception->db
->rollback( __METHOD__
);
654 } catch ( DBError
$e ) {}
656 wfDebugLog( 'SQLBagOStuff', "DBError: {$exception->getMessage()}" );
657 if ( $exception instanceof DBConnectionError
) {
658 $this->setLastError( BagOStuff
::ERR_UNREACHABLE
);
659 wfDebug( __METHOD__
. ": ignoring connection error\n" );
661 $this->setLastError( BagOStuff
::ERR_UNEXPECTED
);
662 wfDebug( __METHOD__
. ": ignoring query error\n" );
667 * Mark a server down due to a DBConnectionError exception
669 * @param DBError $exception
670 * @param int $serverIndex
672 protected function markServerDown( $exception, $serverIndex ) {
673 if ( isset( $this->connFailureTimes
[$serverIndex] ) ) {
674 if ( time() - $this->connFailureTimes
[$serverIndex] >= 60 ) {
675 unset( $this->connFailureTimes
[$serverIndex] );
676 unset( $this->connFailureErrors
[$serverIndex] );
678 wfDebug( __METHOD__
. ": Server #$serverIndex already down\n" );
683 wfDebug( __METHOD__
. ": Server #$serverIndex down until " . ( $now +
60 ) . "\n" );
684 $this->connFailureTimes
[$serverIndex] = $now;
685 $this->connFailureErrors
[$serverIndex] = $exception;
689 * Create shard tables. For use from eval.php.
691 public function createTables() {
692 for ( $serverIndex = 0; $serverIndex < $this->numServers
; $serverIndex++
) {
693 $db = $this->getDB( $serverIndex );
694 if ( $db->getType() !== 'mysql' ) {
695 throw new MWException( __METHOD__
. ' is not supported on this DB server' );
698 for ( $i = 0; $i < $this->shards
; $i++
) {
699 $db->commit( __METHOD__
, 'flush' );
701 'CREATE TABLE ' . $db->tableName( $this->getTableNameByShard( $i ) ) .
702 ' LIKE ' . $db->tableName( 'objectcache' ),
704 $db->commit( __METHOD__
, 'flush' );
711 * Backwards compatibility alias
713 class MediaWikiBagOStuff
extends SqlBagOStuff
{ }