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 if ( isset( $params['servers'] ) ) {
92 $this->serverInfos
= $params['servers'];
93 $this->numServers
= count( $this->serverInfos
);
94 $this->serverNames
= array();
95 foreach ( $this->serverInfos
as $i => $info ) {
96 $this->serverNames
[$i] = isset( $info['host'] ) ?
$info['host'] : "#$i";
98 } elseif ( isset( $params['server'] ) ) {
99 $this->serverInfos
= array( $params['server'] );
100 $this->numServers
= count( $this->serverInfos
);
102 $this->serverInfos
= false;
103 $this->numServers
= 1;
105 if ( isset( $params['purgePeriod'] ) ) {
106 $this->purgePeriod
= intval( $params['purgePeriod'] );
108 if ( isset( $params['tableName'] ) ) {
109 $this->tableName
= $params['tableName'];
111 if ( isset( $params['shards'] ) ) {
112 $this->shards
= intval( $params['shards'] );
117 * Get a connection to the specified database
119 * @param int $serverIndex
120 * @return DatabaseBase
122 protected function getDB( $serverIndex ) {
123 global $wgDebugDBTransactions;
125 if ( !isset( $this->conns
[$serverIndex] ) ) {
126 if ( $serverIndex >= $this->numServers
) {
127 throw new MWException( __METHOD__
. ": Invalid server index \"$serverIndex\"" );
130 # Don't keep timing out trying to connect for each call if the DB is down
131 if ( isset( $this->connFailureErrors
[$serverIndex] )
132 && ( time() - $this->connFailureTimes
[$serverIndex] ) < 60
134 throw $this->connFailureErrors
[$serverIndex];
137 # If server connection info was given, use that
138 if ( $this->serverInfos
) {
139 if ( $wgDebugDBTransactions ) {
140 wfDebug( "Using provided serverInfo for SqlBagOStuff\n" );
142 $info = $this->serverInfos
[$serverIndex];
143 $type = isset( $info['type'] ) ?
$info['type'] : 'mysql';
144 $host = isset( $info['host'] ) ?
$info['host'] : '[unknown]';
145 wfDebug( __CLASS__
. ": connecting to $host\n" );
146 $db = DatabaseBase
::factory( $type, $info );
147 $db->clearFlag( DBO_TRX
);
150 * We must keep a separate connection to MySQL in order to avoid deadlocks
151 * However, SQLite has an opposite behavior. And PostgreSQL needs to know
152 * if we are in transaction or no
154 if ( wfGetDB( DB_MASTER
)->getType() == 'mysql' ) {
155 $this->lb
= wfGetLBFactory()->newMainLB();
156 $db = $this->lb
->getConnection( DB_MASTER
);
157 $db->clearFlag( DBO_TRX
); // auto-commit mode
159 $db = wfGetDB( DB_MASTER
);
162 if ( $wgDebugDBTransactions ) {
163 wfDebug( sprintf( "Connection %s will be used for SqlBagOStuff\n", $db ) );
165 $this->conns
[$serverIndex] = $db;
168 return $this->conns
[$serverIndex];
172 * Get the server index and table name for a given key
174 * @return array Server index and table name
176 protected function getTableByKey( $key ) {
177 if ( $this->shards
> 1 ) {
178 $hash = hexdec( substr( md5( $key ), 0, 8 ) ) & 0x7fffffff;
179 $tableIndex = $hash %
$this->shards
;
183 if ( $this->numServers
> 1 ) {
184 $sortedServers = $this->serverNames
;
185 ArrayUtils
::consistentHashSort( $sortedServers, $key );
186 reset( $sortedServers );
187 $serverIndex = key( $sortedServers );
191 return array( $serverIndex, $this->getTableNameByShard( $tableIndex ) );
195 * Get the table name for a given shard index
199 protected function getTableNameByShard( $index ) {
200 if ( $this->shards
> 1 ) {
201 $decimals = strlen( $this->shards
- 1 );
202 return $this->tableName
.
203 sprintf( "%0{$decimals}d", $index );
205 return $this->tableName
;
211 * @param mixed $casToken [optional]
214 public function get( $key, &$casToken = null ) {
215 $values = $this->getMulti( array( $key ) );
216 if ( array_key_exists( $key, $values ) ) {
217 $casToken = $values[$key];
218 return $values[$key];
227 public function getMulti( array $keys ) {
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 foreach ( $res as $row ) {
248 $row->serverIndex
= $serverIndex;
249 $row->tableName
= $tableName;
250 $dataRows[$row->keyname
] = $row;
253 } catch ( DBError
$e ) {
254 $this->handleReadError( $e, $serverIndex );
258 foreach ( $keys as $key ) {
259 if ( isset( $dataRows[$key] ) ) { // HIT?
260 $row = $dataRows[$key];
261 $this->debug( "get: retrieved data; expiry time is " . $row->exptime
);
263 $db = $this->getDB( $row->serverIndex
);
264 if ( $this->isExpired( $db, $row->exptime
) ) { // MISS
265 $this->debug( "get: key has expired, deleting" );
266 $db->commit( __METHOD__
, 'flush' );
267 # Put the expiry time in the WHERE condition to avoid deleting a
268 # newly-inserted value
269 $db->delete( $row->tableName
,
270 array( 'keyname' => $key, 'exptime' => $row->exptime
),
272 $db->commit( __METHOD__
, 'flush' );
273 $values[$key] = false;
275 $values[$key] = $this->unserialize( $db->decodeBlob( $row->value
) );
277 } catch ( DBQueryError
$e ) {
278 $this->handleWriteError( $e, $row->serverIndex
);
281 $values[$key] = false;
282 $this->debug( 'get: no matching rows' );
294 public function setMulti( array $data, $expiry = 0 ) {
295 $keysByTable = array();
296 foreach ( $data as $key => $value ) {
297 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
298 $keysByTable[$serverIndex][$tableName][] = $key;
301 $this->garbageCollect(); // expire old entries if any
304 $exptime = (int)$expiry;
305 foreach ( $keysByTable as $serverIndex => $serverKeys ) {
307 $db = $this->getDB( $serverIndex );
308 } catch ( DBError
$e ) {
309 $this->handleWriteError( $e, $serverIndex );
314 if ( $exptime < 0 ) {
318 if ( $exptime == 0 ) {
319 $encExpiry = $this->getMaxDateTime( $db );
321 if ( $exptime < 3.16e8
) { # ~10 years
324 $encExpiry = $db->timestamp( $exptime );
326 foreach ( $serverKeys as $tableName => $tableKeys ) {
328 foreach ( $tableKeys as $key ) {
331 'value' => $db->encodeBlob( $this->serialize( $data[$key] ) ),
332 'exptime' => $encExpiry,
337 $db->commit( __METHOD__
, 'flush' );
344 $db->commit( __METHOD__
, 'flush' );
345 } catch ( DBError
$e ) {
346 $this->handleWriteError( $e, $serverIndex );
361 * @param mixed $value
362 * @param int $exptime
365 public function set( $key, $value, $exptime = 0 ) {
366 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
368 $db = $this->getDB( $serverIndex );
369 $exptime = intval( $exptime );
371 if ( $exptime < 0 ) {
375 if ( $exptime == 0 ) {
376 $encExpiry = $this->getMaxDateTime( $db );
378 if ( $exptime < 3.16e8
) { # ~10 years
382 $encExpiry = $db->timestamp( $exptime );
384 $db->commit( __METHOD__
, 'flush' );
385 // (bug 24425) use a replace if the db supports it instead of
386 // delete/insert to avoid clashes with conflicting keynames
392 'value' => $db->encodeBlob( $this->serialize( $value ) ),
393 'exptime' => $encExpiry
395 $db->commit( __METHOD__
, 'flush' );
396 } catch ( DBError
$e ) {
397 $this->handleWriteError( $e, $serverIndex );
405 * @param mixed $casToken
407 * @param mixed $value
408 * @param int $exptime
411 public function cas( $casToken, $key, $value, $exptime = 0 ) {
412 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
414 $db = $this->getDB( $serverIndex );
415 $exptime = intval( $exptime );
417 if ( $exptime < 0 ) {
421 if ( $exptime == 0 ) {
422 $encExpiry = $this->getMaxDateTime( $db );
424 if ( $exptime < 3.16e8
) { # ~10 years
427 $encExpiry = $db->timestamp( $exptime );
429 $db->commit( __METHOD__
, 'flush' );
430 // (bug 24425) use a replace if the db supports it instead of
431 // delete/insert to avoid clashes with conflicting keynames
436 'value' => $db->encodeBlob( $this->serialize( $value ) ),
437 'exptime' => $encExpiry
441 'value' => $db->encodeBlob( $this->serialize( $casToken ) )
445 $db->commit( __METHOD__
, 'flush' );
446 } catch ( DBQueryError
$e ) {
447 $this->handleWriteError( $e, $serverIndex );
452 return (bool)$db->affectedRows();
460 public function delete( $key, $time = 0 ) {
461 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
463 $db = $this->getDB( $serverIndex );
464 $db->commit( __METHOD__
, 'flush' );
467 array( 'keyname' => $key ),
469 $db->commit( __METHOD__
, 'flush' );
470 } catch ( DBError
$e ) {
471 $this->handleWriteError( $e, $serverIndex );
483 public function incr( $key, $step = 1 ) {
484 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
486 $db = $this->getDB( $serverIndex );
487 $step = intval( $step );
488 $db->commit( __METHOD__
, 'flush' );
489 $row = $db->selectRow(
491 array( 'value', 'exptime' ),
492 array( 'keyname' => $key ),
494 array( 'FOR UPDATE' ) );
495 if ( $row === false ) {
497 $db->commit( __METHOD__
, 'flush' );
501 $db->delete( $tableName, array( 'keyname' => $key ), __METHOD__
);
502 if ( $this->isExpired( $db, $row->exptime
) ) {
503 // Expired, do not reinsert
504 $db->commit( __METHOD__
, 'flush' );
509 $oldValue = intval( $this->unserialize( $db->decodeBlob( $row->value
) ) );
510 $newValue = $oldValue +
$step;
511 $db->insert( $tableName,
514 'value' => $db->encodeBlob( $this->serialize( $newValue ) ),
515 'exptime' => $row->exptime
516 ), __METHOD__
, 'IGNORE' );
518 if ( $db->affectedRows() == 0 ) {
519 // Race condition. See bug 28611
522 $db->commit( __METHOD__
, 'flush' );
523 } catch ( DBError
$e ) {
524 $this->handleWriteError( $e, $serverIndex );
532 * @param string $exptime
535 protected function isExpired( $db, $exptime ) {
536 return $exptime != $this->getMaxDateTime( $db ) && wfTimestamp( TS_UNIX
, $exptime ) < time();
540 * @param DatabaseBase $db
543 protected function getMaxDateTime( $db ) {
544 if ( time() > 0x7fffffff ) {
545 return $db->timestamp( 1 << 62 );
547 return $db->timestamp( 0x7fffffff );
551 protected function garbageCollect() {
552 if ( !$this->purgePeriod
) {
556 // Only purge on one in every $this->purgePeriod requests.
557 if ( $this->purgePeriod
!== 1 && mt_rand( 0, $this->purgePeriod
- 1 ) ) {
561 // Avoid repeating the delete within a few seconds
562 if ( $now > ( $this->lastExpireAll +
1 ) ) {
563 $this->lastExpireAll
= $now;
568 public function expireAll() {
569 $this->deleteObjectsExpiringBefore( wfTimestampNow() );
573 * Delete objects from the database which expire before a certain date.
574 * @param string $timestamp
575 * @param bool|callable $progressCallback
578 public function deleteObjectsExpiringBefore( $timestamp, $progressCallback = false ) {
579 for ( $serverIndex = 0; $serverIndex < $this->numServers
; $serverIndex++
) {
581 $db = $this->getDB( $serverIndex );
582 $dbTimestamp = $db->timestamp( $timestamp );
583 $totalSeconds = false;
584 $baseConds = array( 'exptime < ' . $db->addQuotes( $dbTimestamp ) );
585 for ( $i = 0; $i < $this->shards
; $i++
) {
589 if ( $maxExpTime !== false ) {
590 $conds[] = 'exptime > ' . $db->addQuotes( $maxExpTime );
593 $this->getTableNameByShard( $i ),
594 array( 'keyname', 'exptime' ),
597 array( 'LIMIT' => 100, 'ORDER BY' => 'exptime' ) );
598 if ( !$rows->numRows() ) {
602 $row = $rows->current();
603 $minExpTime = $row->exptime
;
604 if ( $totalSeconds === false ) {
605 $totalSeconds = wfTimestamp( TS_UNIX
, $timestamp )
606 - wfTimestamp( TS_UNIX
, $minExpTime );
608 foreach ( $rows as $row ) {
609 $keys[] = $row->keyname
;
610 $maxExpTime = $row->exptime
;
613 $db->commit( __METHOD__
, 'flush' );
615 $this->getTableNameByShard( $i ),
617 'exptime >= ' . $db->addQuotes( $minExpTime ),
618 'exptime < ' . $db->addQuotes( $dbTimestamp ),
622 $db->commit( __METHOD__
, 'flush' );
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 $percent = ( $i +
$remainingSeconds / $totalSeconds )
634 / $this->shards
* 100;
636 $percent = ( $percent / $this->numServers
)
637 +
( $serverIndex / $this->numServers
* 100 );
638 call_user_func( $progressCallback, $percent );
642 } catch ( DBError
$e ) {
643 $this->handleWriteError( $e, $serverIndex );
650 public function deleteAll() {
651 for ( $serverIndex = 0; $serverIndex < $this->numServers
; $serverIndex++
) {
653 $db = $this->getDB( $serverIndex );
654 for ( $i = 0; $i < $this->shards
; $i++
) {
655 $db->commit( __METHOD__
, 'flush' );
656 $db->delete( $this->getTableNameByShard( $i ), '*', __METHOD__
);
657 $db->commit( __METHOD__
, 'flush' );
659 } catch ( DBError
$e ) {
660 $this->handleWriteError( $e, $serverIndex );
668 * Serialize an object and, if possible, compress the representation.
669 * On typical message and page data, this can provide a 3X decrease
670 * in storage requirements.
675 protected function serialize( &$data ) {
676 $serial = serialize( $data );
678 if ( function_exists( 'gzdeflate' ) ) {
679 return gzdeflate( $serial );
686 * Unserialize and, if necessary, decompress an object.
687 * @param string $serial
690 protected function unserialize( $serial ) {
691 if ( function_exists( 'gzinflate' ) ) {
692 wfSuppressWarnings();
693 $decomp = gzinflate( $serial );
696 if ( false !== $decomp ) {
701 $ret = unserialize( $serial );
707 * Handle a DBError which occurred during a read operation.
709 * @param DBError $exception
710 * @param int $serverIndex
712 protected function handleReadError( DBError
$exception, $serverIndex ) {
713 if ( $exception instanceof DBConnectionError
) {
714 $this->markServerDown( $exception, $serverIndex );
716 wfDebugLog( 'SQLBagOStuff', "DBError: {$exception->getMessage()}" );
717 if ( $exception instanceof DBConnectionError
) {
718 $this->setLastError( BagOStuff
::ERR_UNREACHABLE
);
719 wfDebug( __METHOD__
. ": ignoring connection error\n" );
721 $this->setLastError( BagOStuff
::ERR_UNEXPECTED
);
722 wfDebug( __METHOD__
. ": ignoring query error\n" );
727 * Handle a DBQueryError which occurred during a write operation.
729 * @param DBError $exception
730 * @param int $serverIndex
732 protected function handleWriteError( DBError
$exception, $serverIndex ) {
733 if ( $exception instanceof DBConnectionError
) {
734 $this->markServerDown( $exception, $serverIndex );
736 if ( $exception->db
&& $exception->db
->wasReadOnlyError() ) {
738 $exception->db
->rollback( __METHOD__
);
739 } catch ( DBError
$e ) {
742 wfDebugLog( 'SQLBagOStuff', "DBError: {$exception->getMessage()}" );
743 if ( $exception instanceof DBConnectionError
) {
744 $this->setLastError( BagOStuff
::ERR_UNREACHABLE
);
745 wfDebug( __METHOD__
. ": ignoring connection error\n" );
747 $this->setLastError( BagOStuff
::ERR_UNEXPECTED
);
748 wfDebug( __METHOD__
. ": ignoring query error\n" );
753 * Mark a server down due to a DBConnectionError exception
755 * @param DBError $exception
756 * @param int $serverIndex
758 protected function markServerDown( $exception, $serverIndex ) {
759 if ( isset( $this->connFailureTimes
[$serverIndex] ) ) {
760 if ( time() - $this->connFailureTimes
[$serverIndex] >= 60 ) {
761 unset( $this->connFailureTimes
[$serverIndex] );
762 unset( $this->connFailureErrors
[$serverIndex] );
764 wfDebug( __METHOD__
. ": Server #$serverIndex already down\n" );
769 wfDebug( __METHOD__
. ": Server #$serverIndex down until " . ( $now +
60 ) . "\n" );
770 $this->connFailureTimes
[$serverIndex] = $now;
771 $this->connFailureErrors
[$serverIndex] = $exception;
775 * Create shard tables. For use from eval.php.
777 public function createTables() {
778 for ( $serverIndex = 0; $serverIndex < $this->numServers
; $serverIndex++
) {
779 $db = $this->getDB( $serverIndex );
780 if ( $db->getType() !== 'mysql' ) {
781 throw new MWException( __METHOD__
. ' is not supported on this DB server' );
784 for ( $i = 0; $i < $this->shards
; $i++
) {
785 $db->commit( __METHOD__
, 'flush' );
787 'CREATE TABLE ' . $db->tableName( $this->getTableNameByShard( $i ) ) .
788 ' LIKE ' . $db->tableName( 'objectcache' ),
790 $db->commit( __METHOD__
, 'flush' );
797 * Backwards compatibility alias
799 class MediaWikiBagOStuff
extends SqlBagOStuff
{