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 // Approximate write-on-the-fly BagOStuff API via blocking.
248 // This approximation fails if a ROLLBACK happens (which is rare).
249 // We do not want to flush the TRX as that can break callers.
250 $db->trxLevel() ?
array( 'LOCK IN SHARE MODE' ) : array()
252 if ( $res === false ) {
255 foreach ( $res as $row ) {
256 $row->serverIndex
= $serverIndex;
257 $row->tableName
= $tableName;
258 $dataRows[$row->keyname
] = $row;
261 } catch ( DBError
$e ) {
262 $this->handleReadError( $e, $serverIndex );
266 foreach ( $keys as $key ) {
267 if ( isset( $dataRows[$key] ) ) { // HIT?
268 $row = $dataRows[$key];
269 $this->debug( "get: retrieved data; expiry time is " . $row->exptime
);
271 $db = $this->getDB( $row->serverIndex
);
272 if ( $this->isExpired( $db, $row->exptime
) ) { // MISS
273 $this->debug( "get: key has expired, deleting" );
274 # Put the expiry time in the WHERE condition to avoid deleting a
275 # newly-inserted value
276 $db->delete( $row->tableName
,
277 array( 'keyname' => $key, 'exptime' => $row->exptime
),
280 $values[$key] = $this->unserialize( $db->decodeBlob( $row->value
) );
282 } catch ( DBQueryError
$e ) {
283 $this->handleWriteError( $e, $row->serverIndex
);
286 $this->debug( 'get: no matching rows' );
298 public function setMulti( array $data, $expiry = 0 ) {
299 $keysByTable = array();
300 foreach ( $data as $key => $value ) {
301 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
302 $keysByTable[$serverIndex][$tableName][] = $key;
305 $this->garbageCollect(); // expire old entries if any
308 $exptime = (int)$expiry;
309 foreach ( $keysByTable as $serverIndex => $serverKeys ) {
311 $db = $this->getDB( $serverIndex );
312 } catch ( DBError
$e ) {
313 $this->handleWriteError( $e, $serverIndex );
318 if ( $exptime < 0 ) {
322 if ( $exptime == 0 ) {
323 $encExpiry = $this->getMaxDateTime( $db );
325 $exptime = $this->convertExpiry( $exptime );
326 $encExpiry = $db->timestamp( $exptime );
328 foreach ( $serverKeys as $tableName => $tableKeys ) {
330 foreach ( $tableKeys as $key ) {
333 'value' => $db->encodeBlob( $this->serialize( $data[$key] ) ),
334 'exptime' => $encExpiry,
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 $exptime = $this->convertExpiry( $exptime );
379 $encExpiry = $db->timestamp( $exptime );
381 // (bug 24425) use a replace if the db supports it instead of
382 // delete/insert to avoid clashes with conflicting keynames
388 'value' => $db->encodeBlob( $this->serialize( $value ) ),
389 'exptime' => $encExpiry
391 } catch ( DBError
$e ) {
392 $this->handleWriteError( $e, $serverIndex );
400 * @param mixed $casToken
402 * @param mixed $value
403 * @param int $exptime
406 public function cas( $casToken, $key, $value, $exptime = 0 ) {
407 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
409 $db = $this->getDB( $serverIndex );
410 $exptime = intval( $exptime );
412 if ( $exptime < 0 ) {
416 if ( $exptime == 0 ) {
417 $encExpiry = $this->getMaxDateTime( $db );
419 $exptime = $this->convertExpiry( $exptime );
420 $encExpiry = $db->timestamp( $exptime );
422 // (bug 24425) use a replace if the db supports it instead of
423 // delete/insert to avoid clashes with conflicting keynames
428 'value' => $db->encodeBlob( $this->serialize( $value ) ),
429 'exptime' => $encExpiry
433 'value' => $db->encodeBlob( $this->serialize( $casToken ) )
437 } catch ( DBQueryError
$e ) {
438 $this->handleWriteError( $e, $serverIndex );
443 return (bool)$db->affectedRows();
451 public function delete( $key, $time = 0 ) {
452 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
454 $db = $this->getDB( $serverIndex );
457 array( 'keyname' => $key ),
459 } catch ( DBError
$e ) {
460 $this->handleWriteError( $e, $serverIndex );
472 public function incr( $key, $step = 1 ) {
473 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
475 $db = $this->getDB( $serverIndex );
476 $step = intval( $step );
477 $row = $db->selectRow(
479 array( 'value', 'exptime' ),
480 array( 'keyname' => $key ),
482 array( 'FOR UPDATE' ) );
483 if ( $row === false ) {
488 $db->delete( $tableName, array( 'keyname' => $key ), __METHOD__
);
489 if ( $this->isExpired( $db, $row->exptime
) ) {
490 // Expired, do not reinsert
495 $oldValue = intval( $this->unserialize( $db->decodeBlob( $row->value
) ) );
496 $newValue = $oldValue +
$step;
497 $db->insert( $tableName,
500 'value' => $db->encodeBlob( $this->serialize( $newValue ) ),
501 'exptime' => $row->exptime
502 ), __METHOD__
, 'IGNORE' );
504 if ( $db->affectedRows() == 0 ) {
505 // Race condition. See bug 28611
508 } catch ( DBError
$e ) {
509 $this->handleWriteError( $e, $serverIndex );
517 * @param DatabaseBase $db
518 * @param string $exptime
521 protected function isExpired( $db, $exptime ) {
522 return $exptime != $this->getMaxDateTime( $db ) && wfTimestamp( TS_UNIX
, $exptime ) < time();
526 * @param DatabaseBase $db
529 protected function getMaxDateTime( $db ) {
530 if ( time() > 0x7fffffff ) {
531 return $db->timestamp( 1 << 62 );
533 return $db->timestamp( 0x7fffffff );
537 protected function garbageCollect() {
538 if ( !$this->purgePeriod
) {
542 // Only purge on one in every $this->purgePeriod requests.
543 if ( $this->purgePeriod
!== 1 && mt_rand( 0, $this->purgePeriod
- 1 ) ) {
547 // Avoid repeating the delete within a few seconds
548 if ( $now > ( $this->lastExpireAll +
1 ) ) {
549 $this->lastExpireAll
= $now;
554 public function expireAll() {
555 $this->deleteObjectsExpiringBefore( wfTimestampNow() );
559 * Delete objects from the database which expire before a certain date.
560 * @param string $timestamp
561 * @param bool|callable $progressCallback
564 public function deleteObjectsExpiringBefore( $timestamp, $progressCallback = false ) {
565 for ( $serverIndex = 0; $serverIndex < $this->numServers
; $serverIndex++
) {
567 $db = $this->getDB( $serverIndex );
568 $dbTimestamp = $db->timestamp( $timestamp );
569 $totalSeconds = false;
570 $baseConds = array( 'exptime < ' . $db->addQuotes( $dbTimestamp ) );
571 for ( $i = 0; $i < $this->shards
; $i++
) {
575 if ( $maxExpTime !== false ) {
576 $conds[] = 'exptime > ' . $db->addQuotes( $maxExpTime );
579 $this->getTableNameByShard( $i ),
580 array( 'keyname', 'exptime' ),
583 array( 'LIMIT' => 100, 'ORDER BY' => 'exptime' ) );
584 if ( $rows === false ||
!$rows->numRows() ) {
588 $row = $rows->current();
589 $minExpTime = $row->exptime
;
590 if ( $totalSeconds === false ) {
591 $totalSeconds = wfTimestamp( TS_UNIX
, $timestamp )
592 - wfTimestamp( TS_UNIX
, $minExpTime );
594 foreach ( $rows as $row ) {
595 $keys[] = $row->keyname
;
596 $maxExpTime = $row->exptime
;
600 $this->getTableNameByShard( $i ),
602 'exptime >= ' . $db->addQuotes( $minExpTime ),
603 'exptime < ' . $db->addQuotes( $dbTimestamp ),
608 if ( $progressCallback ) {
609 if ( intval( $totalSeconds ) === 0 ) {
612 $remainingSeconds = wfTimestamp( TS_UNIX
, $timestamp )
613 - wfTimestamp( TS_UNIX
, $maxExpTime );
614 if ( $remainingSeconds > $totalSeconds ) {
615 $totalSeconds = $remainingSeconds;
617 $processedSeconds = $totalSeconds - $remainingSeconds;
618 $percent = ( $i +
$processedSeconds / $totalSeconds )
619 / $this->shards
* 100;
621 $percent = ( $percent / $this->numServers
)
622 +
( $serverIndex / $this->numServers
* 100 );
623 call_user_func( $progressCallback, $percent );
627 } catch ( DBError
$e ) {
628 $this->handleWriteError( $e, $serverIndex );
636 * Delete content of shard tables in every server.
637 * Return true if the operation is successful, false otherwise.
640 public function deleteAll() {
641 for ( $serverIndex = 0; $serverIndex < $this->numServers
; $serverIndex++
) {
643 $db = $this->getDB( $serverIndex );
644 for ( $i = 0; $i < $this->shards
; $i++
) {
645 $db->delete( $this->getTableNameByShard( $i ), '*', __METHOD__
);
647 } catch ( DBError
$e ) {
648 $this->handleWriteError( $e, $serverIndex );
656 * Serialize an object and, if possible, compress the representation.
657 * On typical message and page data, this can provide a 3X decrease
658 * in storage requirements.
663 protected function serialize( &$data ) {
664 $serial = serialize( $data );
666 if ( function_exists( 'gzdeflate' ) ) {
667 return gzdeflate( $serial );
674 * Unserialize and, if necessary, decompress an object.
675 * @param string $serial
678 protected function unserialize( $serial ) {
679 if ( function_exists( 'gzinflate' ) ) {
680 wfSuppressWarnings();
681 $decomp = gzinflate( $serial );
684 if ( false !== $decomp ) {
689 $ret = unserialize( $serial );
695 * Handle a DBError which occurred during a read operation.
697 * @param DBError $exception
698 * @param int $serverIndex
700 protected function handleReadError( DBError
$exception, $serverIndex ) {
701 if ( $exception instanceof DBConnectionError
) {
702 $this->markServerDown( $exception, $serverIndex );
704 wfDebugLog( 'SQLBagOStuff', "DBError: {$exception->getMessage()}" );
705 if ( $exception instanceof DBConnectionError
) {
706 $this->setLastError( BagOStuff
::ERR_UNREACHABLE
);
707 wfDebug( __METHOD__
. ": ignoring connection error\n" );
709 $this->setLastError( BagOStuff
::ERR_UNEXPECTED
);
710 wfDebug( __METHOD__
. ": ignoring query error\n" );
715 * Handle a DBQueryError which occurred during a write operation.
717 * @param DBError $exception
718 * @param int $serverIndex
720 protected function handleWriteError( DBError
$exception, $serverIndex ) {
721 if ( $exception instanceof DBConnectionError
) {
722 $this->markServerDown( $exception, $serverIndex );
724 if ( $exception->db
&& $exception->db
->wasReadOnlyError() ) {
726 $exception->db
->rollback( __METHOD__
);
727 } catch ( DBError
$e ) {
730 wfDebugLog( 'SQLBagOStuff', "DBError: {$exception->getMessage()}" );
731 if ( $exception instanceof DBConnectionError
) {
732 $this->setLastError( BagOStuff
::ERR_UNREACHABLE
);
733 wfDebug( __METHOD__
. ": ignoring connection error\n" );
735 $this->setLastError( BagOStuff
::ERR_UNEXPECTED
);
736 wfDebug( __METHOD__
. ": ignoring query error\n" );
741 * Mark a server down due to a DBConnectionError exception
743 * @param DBError $exception
744 * @param int $serverIndex
746 protected function markServerDown( $exception, $serverIndex ) {
747 if ( isset( $this->connFailureTimes
[$serverIndex] ) ) {
748 if ( time() - $this->connFailureTimes
[$serverIndex] >= 60 ) {
749 unset( $this->connFailureTimes
[$serverIndex] );
750 unset( $this->connFailureErrors
[$serverIndex] );
752 wfDebug( __METHOD__
. ": Server #$serverIndex already down\n" );
757 wfDebug( __METHOD__
. ": Server #$serverIndex down until " . ( $now +
60 ) . "\n" );
758 $this->connFailureTimes
[$serverIndex] = $now;
759 $this->connFailureErrors
[$serverIndex] = $exception;
763 * Create shard tables. For use from eval.php.
765 public function createTables() {
766 for ( $serverIndex = 0; $serverIndex < $this->numServers
; $serverIndex++
) {
767 $db = $this->getDB( $serverIndex );
768 if ( $db->getType() !== 'mysql' ) {
769 throw new MWException( __METHOD__
. ' is not supported on this DB server' );
772 for ( $i = 0; $i < $this->shards
; $i++
) {
774 'CREATE TABLE ' . $db->tableName( $this->getTableNameByShard( $i ) ) .
775 ' LIKE ' . $db->tableName( 'objectcache' ),
783 * Backwards compatibility alias
785 class MediaWikiBagOStuff
extends SqlBagOStuff
{