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' );
279 public function setMulti( array $data, $expiry = 0 ) {
280 $keysByTable = array();
281 foreach ( $data as $key => $value ) {
282 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
283 $keysByTable[$serverIndex][$tableName][] = $key;
286 $this->garbageCollect(); // expire old entries if any
289 $exptime = (int)$expiry;
290 foreach ( $keysByTable as $serverIndex => $serverKeys ) {
292 $db = $this->getDB( $serverIndex );
293 } catch ( DBError
$e ) {
294 $this->handleWriteError( $e, $serverIndex );
299 if ( $exptime < 0 ) {
303 if ( $exptime == 0 ) {
304 $encExpiry = $this->getMaxDateTime( $db );
306 if ( $exptime < 3.16e8
) { # ~10 years
309 $encExpiry = $db->timestamp( $exptime );
311 foreach ( $serverKeys as $tableName => $tableKeys ) {
313 foreach ( $tableKeys as $key ) {
316 'value' => $db->encodeBlob( $this->serialize( $data[$key] ) ),
317 'exptime' => $encExpiry,
322 $db->commit( __METHOD__
, 'flush' );
329 $db->commit( __METHOD__
, 'flush' );
330 } catch ( DBError
$e ) {
331 $this->handleWriteError( $e, $serverIndex );
346 * @param mixed $value
347 * @param int $exptime
350 public function set( $key, $value, $exptime = 0 ) {
351 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
353 $db = $this->getDB( $serverIndex );
354 $exptime = intval( $exptime );
356 if ( $exptime < 0 ) {
360 if ( $exptime == 0 ) {
361 $encExpiry = $this->getMaxDateTime( $db );
363 if ( $exptime < 3.16e8
) { # ~10 years
367 $encExpiry = $db->timestamp( $exptime );
369 $db->commit( __METHOD__
, 'flush' );
370 // (bug 24425) use a replace if the db supports it instead of
371 // delete/insert to avoid clashes with conflicting keynames
377 'value' => $db->encodeBlob( $this->serialize( $value ) ),
378 'exptime' => $encExpiry
380 $db->commit( __METHOD__
, 'flush' );
381 } catch ( DBError
$e ) {
382 $this->handleWriteError( $e, $serverIndex );
390 * @param mixed $casToken
392 * @param mixed $value
393 * @param int $exptime
396 public function cas( $casToken, $key, $value, $exptime = 0 ) {
397 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
399 $db = $this->getDB( $serverIndex );
400 $exptime = intval( $exptime );
402 if ( $exptime < 0 ) {
406 if ( $exptime == 0 ) {
407 $encExpiry = $this->getMaxDateTime( $db );
409 if ( $exptime < 3.16e8
) { # ~10 years
412 $encExpiry = $db->timestamp( $exptime );
414 $db->commit( __METHOD__
, 'flush' );
415 // (bug 24425) use a replace if the db supports it instead of
416 // delete/insert to avoid clashes with conflicting keynames
421 'value' => $db->encodeBlob( $this->serialize( $value ) ),
422 'exptime' => $encExpiry
426 'value' => $db->encodeBlob( $this->serialize( $casToken ) )
430 $db->commit( __METHOD__
, 'flush' );
431 } catch ( DBQueryError
$e ) {
432 $this->handleWriteError( $e, $serverIndex );
437 return (bool)$db->affectedRows();
445 public function delete( $key, $time = 0 ) {
446 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
448 $db = $this->getDB( $serverIndex );
449 $db->commit( __METHOD__
, 'flush' );
452 array( 'keyname' => $key ),
454 $db->commit( __METHOD__
, 'flush' );
455 } catch ( DBError
$e ) {
456 $this->handleWriteError( $e, $serverIndex );
468 public function incr( $key, $step = 1 ) {
469 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
471 $db = $this->getDB( $serverIndex );
472 $step = intval( $step );
473 $db->commit( __METHOD__
, 'flush' );
474 $row = $db->selectRow(
476 array( 'value', 'exptime' ),
477 array( 'keyname' => $key ),
479 array( 'FOR UPDATE' ) );
480 if ( $row === false ) {
482 $db->commit( __METHOD__
, 'flush' );
486 $db->delete( $tableName, array( 'keyname' => $key ), __METHOD__
);
487 if ( $this->isExpired( $db, $row->exptime
) ) {
488 // Expired, do not reinsert
489 $db->commit( __METHOD__
, 'flush' );
494 $oldValue = intval( $this->unserialize( $db->decodeBlob( $row->value
) ) );
495 $newValue = $oldValue +
$step;
496 $db->insert( $tableName,
499 'value' => $db->encodeBlob( $this->serialize( $newValue ) ),
500 'exptime' => $row->exptime
501 ), __METHOD__
, 'IGNORE' );
503 if ( $db->affectedRows() == 0 ) {
504 // Race condition. See bug 28611
507 $db->commit( __METHOD__
, 'flush' );
508 } catch ( DBError
$e ) {
509 $this->handleWriteError( $e, $serverIndex );
517 * @param string $exptime
520 protected function isExpired( $db, $exptime ) {
521 return $exptime != $this->getMaxDateTime( $db ) && wfTimestamp( TS_UNIX
, $exptime ) < time();
525 * @param DatabaseBase $db
528 protected function getMaxDateTime( $db ) {
529 if ( time() > 0x7fffffff ) {
530 return $db->timestamp( 1 << 62 );
532 return $db->timestamp( 0x7fffffff );
536 protected function garbageCollect() {
537 if ( !$this->purgePeriod
) {
541 // Only purge on one in every $this->purgePeriod requests.
542 if ( $this->purgePeriod
!== 1 && mt_rand( 0, $this->purgePeriod
- 1 ) ) {
546 // Avoid repeating the delete within a few seconds
547 if ( $now > ( $this->lastExpireAll +
1 ) ) {
548 $this->lastExpireAll
= $now;
553 public function expireAll() {
554 $this->deleteObjectsExpiringBefore( wfTimestampNow() );
558 * Delete objects from the database which expire before a certain date.
559 * @param string $timestamp
560 * @param bool|callable $progressCallback
563 public function deleteObjectsExpiringBefore( $timestamp, $progressCallback = false ) {
564 for ( $serverIndex = 0; $serverIndex < $this->numServers
; $serverIndex++
) {
566 $db = $this->getDB( $serverIndex );
567 $dbTimestamp = $db->timestamp( $timestamp );
568 $totalSeconds = false;
569 $baseConds = array( 'exptime < ' . $db->addQuotes( $dbTimestamp ) );
570 for ( $i = 0; $i < $this->shards
; $i++
) {
574 if ( $maxExpTime !== false ) {
575 $conds[] = 'exptime > ' . $db->addQuotes( $maxExpTime );
578 $this->getTableNameByShard( $i ),
579 array( 'keyname', 'exptime' ),
582 array( 'LIMIT' => 100, 'ORDER BY' => 'exptime' ) );
583 if ( !$rows->numRows() ) {
587 $row = $rows->current();
588 $minExpTime = $row->exptime
;
589 if ( $totalSeconds === false ) {
590 $totalSeconds = wfTimestamp( TS_UNIX
, $timestamp )
591 - wfTimestamp( TS_UNIX
, $minExpTime );
593 foreach ( $rows as $row ) {
594 $keys[] = $row->keyname
;
595 $maxExpTime = $row->exptime
;
598 $db->commit( __METHOD__
, 'flush' );
600 $this->getTableNameByShard( $i ),
602 'exptime >= ' . $db->addQuotes( $minExpTime ),
603 'exptime < ' . $db->addQuotes( $dbTimestamp ),
607 $db->commit( __METHOD__
, 'flush' );
609 if ( $progressCallback ) {
610 if ( intval( $totalSeconds ) === 0 ) {
613 $remainingSeconds = wfTimestamp( TS_UNIX
, $timestamp )
614 - wfTimestamp( TS_UNIX
, $maxExpTime );
615 if ( $remainingSeconds > $totalSeconds ) {
616 $totalSeconds = $remainingSeconds;
618 $percent = ( $i +
$remainingSeconds / $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 );
635 public function deleteAll() {
636 for ( $serverIndex = 0; $serverIndex < $this->numServers
; $serverIndex++
) {
638 $db = $this->getDB( $serverIndex );
639 for ( $i = 0; $i < $this->shards
; $i++
) {
640 $db->commit( __METHOD__
, 'flush' );
641 $db->delete( $this->getTableNameByShard( $i ), '*', __METHOD__
);
642 $db->commit( __METHOD__
, 'flush' );
644 } catch ( DBError
$e ) {
645 $this->handleWriteError( $e, $serverIndex );
653 * Serialize an object and, if possible, compress the representation.
654 * On typical message and page data, this can provide a 3X decrease
655 * in storage requirements.
660 protected function serialize( &$data ) {
661 $serial = serialize( $data );
663 if ( function_exists( 'gzdeflate' ) ) {
664 return gzdeflate( $serial );
671 * Unserialize and, if necessary, decompress an object.
672 * @param string $serial
675 protected function unserialize( $serial ) {
676 if ( function_exists( 'gzinflate' ) ) {
677 wfSuppressWarnings();
678 $decomp = gzinflate( $serial );
681 if ( false !== $decomp ) {
686 $ret = unserialize( $serial );
692 * Handle a DBError which occurred during a read operation.
694 * @param DBError $exception
695 * @param int $serverIndex
697 protected function handleReadError( DBError
$exception, $serverIndex ) {
698 if ( $exception instanceof DBConnectionError
) {
699 $this->markServerDown( $exception, $serverIndex );
701 wfDebugLog( 'SQLBagOStuff', "DBError: {$exception->getMessage()}" );
702 if ( $exception instanceof DBConnectionError
) {
703 $this->setLastError( BagOStuff
::ERR_UNREACHABLE
);
704 wfDebug( __METHOD__
. ": ignoring connection error\n" );
706 $this->setLastError( BagOStuff
::ERR_UNEXPECTED
);
707 wfDebug( __METHOD__
. ": ignoring query error\n" );
712 * Handle a DBQueryError which occurred during a write operation.
714 * @param DBError $exception
715 * @param int $serverIndex
717 protected function handleWriteError( DBError
$exception, $serverIndex ) {
718 if ( $exception instanceof DBConnectionError
) {
719 $this->markServerDown( $exception, $serverIndex );
721 if ( $exception->db
&& $exception->db
->wasReadOnlyError() ) {
723 $exception->db
->rollback( __METHOD__
);
724 } catch ( DBError
$e ) {}
726 wfDebugLog( 'SQLBagOStuff', "DBError: {$exception->getMessage()}" );
727 if ( $exception instanceof DBConnectionError
) {
728 $this->setLastError( BagOStuff
::ERR_UNREACHABLE
);
729 wfDebug( __METHOD__
. ": ignoring connection error\n" );
731 $this->setLastError( BagOStuff
::ERR_UNEXPECTED
);
732 wfDebug( __METHOD__
. ": ignoring query error\n" );
737 * Mark a server down due to a DBConnectionError exception
739 * @param DBError $exception
740 * @param int $serverIndex
742 protected function markServerDown( $exception, $serverIndex ) {
743 if ( isset( $this->connFailureTimes
[$serverIndex] ) ) {
744 if ( time() - $this->connFailureTimes
[$serverIndex] >= 60 ) {
745 unset( $this->connFailureTimes
[$serverIndex] );
746 unset( $this->connFailureErrors
[$serverIndex] );
748 wfDebug( __METHOD__
. ": Server #$serverIndex already down\n" );
753 wfDebug( __METHOD__
. ": Server #$serverIndex down until " . ( $now +
60 ) . "\n" );
754 $this->connFailureTimes
[$serverIndex] = $now;
755 $this->connFailureErrors
[$serverIndex] = $exception;
759 * Create shard tables. For use from eval.php.
761 public function createTables() {
762 for ( $serverIndex = 0; $serverIndex < $this->numServers
; $serverIndex++
) {
763 $db = $this->getDB( $serverIndex );
764 if ( $db->getType() !== 'mysql' ) {
765 throw new MWException( __METHOD__
. ' is not supported on this DB server' );
768 for ( $i = 0; $i < $this->shards
; $i++
) {
769 $db->commit( __METHOD__
, 'flush' );
771 'CREATE TABLE ' . $db->tableName( $this->getTableNameByShard( $i ) ) .
772 ' LIKE ' . $db->tableName( 'objectcache' ),
774 $db->commit( __METHOD__
, 'flush' );
781 * Backwards compatibility alias
783 class MediaWikiBagOStuff
extends SqlBagOStuff
{ }