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' );
274 $values[$key] = $this->unserialize( $db->decodeBlob( $row->value
) );
276 } catch ( DBQueryError
$e ) {
277 $this->handleWriteError( $e, $row->serverIndex
);
280 $this->debug( 'get: no matching rows' );
292 public function setMulti( array $data, $expiry = 0 ) {
293 $keysByTable = array();
294 foreach ( $data as $key => $value ) {
295 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
296 $keysByTable[$serverIndex][$tableName][] = $key;
299 $this->garbageCollect(); // expire old entries if any
302 $exptime = (int)$expiry;
303 foreach ( $keysByTable as $serverIndex => $serverKeys ) {
305 $db = $this->getDB( $serverIndex );
306 } catch ( DBError
$e ) {
307 $this->handleWriteError( $e, $serverIndex );
312 if ( $exptime < 0 ) {
316 if ( $exptime == 0 ) {
317 $encExpiry = $this->getMaxDateTime( $db );
319 if ( $exptime < 3.16e8
) { # ~10 years
322 $encExpiry = $db->timestamp( $exptime );
324 foreach ( $serverKeys as $tableName => $tableKeys ) {
326 foreach ( $tableKeys as $key ) {
329 'value' => $db->encodeBlob( $this->serialize( $data[$key] ) ),
330 'exptime' => $encExpiry,
335 $db->commit( __METHOD__
, 'flush' );
342 $db->commit( __METHOD__
, 'flush' );
343 } catch ( DBError
$e ) {
344 $this->handleWriteError( $e, $serverIndex );
359 * @param mixed $value
360 * @param int $exptime
363 public function set( $key, $value, $exptime = 0 ) {
364 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
366 $db = $this->getDB( $serverIndex );
367 $exptime = intval( $exptime );
369 if ( $exptime < 0 ) {
373 if ( $exptime == 0 ) {
374 $encExpiry = $this->getMaxDateTime( $db );
376 if ( $exptime < 3.16e8
) { # ~10 years
380 $encExpiry = $db->timestamp( $exptime );
382 $db->commit( __METHOD__
, 'flush' );
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 $db->commit( __METHOD__
, 'flush' );
394 } catch ( DBError
$e ) {
395 $this->handleWriteError( $e, $serverIndex );
403 * @param mixed $casToken
405 * @param mixed $value
406 * @param int $exptime
409 public function cas( $casToken, $key, $value, $exptime = 0 ) {
410 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
412 $db = $this->getDB( $serverIndex );
413 $exptime = intval( $exptime );
415 if ( $exptime < 0 ) {
419 if ( $exptime == 0 ) {
420 $encExpiry = $this->getMaxDateTime( $db );
422 if ( $exptime < 3.16e8
) { # ~10 years
425 $encExpiry = $db->timestamp( $exptime );
427 $db->commit( __METHOD__
, 'flush' );
428 // (bug 24425) use a replace if the db supports it instead of
429 // delete/insert to avoid clashes with conflicting keynames
434 'value' => $db->encodeBlob( $this->serialize( $value ) ),
435 'exptime' => $encExpiry
439 'value' => $db->encodeBlob( $this->serialize( $casToken ) )
443 $db->commit( __METHOD__
, 'flush' );
444 } catch ( DBQueryError
$e ) {
445 $this->handleWriteError( $e, $serverIndex );
450 return (bool)$db->affectedRows();
458 public function delete( $key, $time = 0 ) {
459 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
461 $db = $this->getDB( $serverIndex );
462 $db->commit( __METHOD__
, 'flush' );
465 array( 'keyname' => $key ),
467 $db->commit( __METHOD__
, 'flush' );
468 } catch ( DBError
$e ) {
469 $this->handleWriteError( $e, $serverIndex );
481 public function incr( $key, $step = 1 ) {
482 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
484 $db = $this->getDB( $serverIndex );
485 $step = intval( $step );
486 $db->commit( __METHOD__
, 'flush' );
487 $row = $db->selectRow(
489 array( 'value', 'exptime' ),
490 array( 'keyname' => $key ),
492 array( 'FOR UPDATE' ) );
493 if ( $row === false ) {
495 $db->commit( __METHOD__
, 'flush' );
499 $db->delete( $tableName, array( 'keyname' => $key ), __METHOD__
);
500 if ( $this->isExpired( $db, $row->exptime
) ) {
501 // Expired, do not reinsert
502 $db->commit( __METHOD__
, 'flush' );
507 $oldValue = intval( $this->unserialize( $db->decodeBlob( $row->value
) ) );
508 $newValue = $oldValue +
$step;
509 $db->insert( $tableName,
512 'value' => $db->encodeBlob( $this->serialize( $newValue ) ),
513 'exptime' => $row->exptime
514 ), __METHOD__
, 'IGNORE' );
516 if ( $db->affectedRows() == 0 ) {
517 // Race condition. See bug 28611
520 $db->commit( __METHOD__
, 'flush' );
521 } catch ( DBError
$e ) {
522 $this->handleWriteError( $e, $serverIndex );
530 * @param string $exptime
533 protected function isExpired( $db, $exptime ) {
534 return $exptime != $this->getMaxDateTime( $db ) && wfTimestamp( TS_UNIX
, $exptime ) < time();
538 * @param DatabaseBase $db
541 protected function getMaxDateTime( $db ) {
542 if ( time() > 0x7fffffff ) {
543 return $db->timestamp( 1 << 62 );
545 return $db->timestamp( 0x7fffffff );
549 protected function garbageCollect() {
550 if ( !$this->purgePeriod
) {
554 // Only purge on one in every $this->purgePeriod requests.
555 if ( $this->purgePeriod
!== 1 && mt_rand( 0, $this->purgePeriod
- 1 ) ) {
559 // Avoid repeating the delete within a few seconds
560 if ( $now > ( $this->lastExpireAll +
1 ) ) {
561 $this->lastExpireAll
= $now;
566 public function expireAll() {
567 $this->deleteObjectsExpiringBefore( wfTimestampNow() );
571 * Delete objects from the database which expire before a certain date.
572 * @param string $timestamp
573 * @param bool|callable $progressCallback
576 public function deleteObjectsExpiringBefore( $timestamp, $progressCallback = false ) {
577 for ( $serverIndex = 0; $serverIndex < $this->numServers
; $serverIndex++
) {
579 $db = $this->getDB( $serverIndex );
580 $dbTimestamp = $db->timestamp( $timestamp );
581 $totalSeconds = false;
582 $baseConds = array( 'exptime < ' . $db->addQuotes( $dbTimestamp ) );
583 for ( $i = 0; $i < $this->shards
; $i++
) {
587 if ( $maxExpTime !== false ) {
588 $conds[] = 'exptime > ' . $db->addQuotes( $maxExpTime );
591 $this->getTableNameByShard( $i ),
592 array( 'keyname', 'exptime' ),
595 array( 'LIMIT' => 100, 'ORDER BY' => 'exptime' ) );
596 if ( !$rows->numRows() ) {
600 $row = $rows->current();
601 $minExpTime = $row->exptime
;
602 if ( $totalSeconds === false ) {
603 $totalSeconds = wfTimestamp( TS_UNIX
, $timestamp )
604 - wfTimestamp( TS_UNIX
, $minExpTime );
606 foreach ( $rows as $row ) {
607 $keys[] = $row->keyname
;
608 $maxExpTime = $row->exptime
;
611 $db->commit( __METHOD__
, 'flush' );
613 $this->getTableNameByShard( $i ),
615 'exptime >= ' . $db->addQuotes( $minExpTime ),
616 'exptime < ' . $db->addQuotes( $dbTimestamp ),
620 $db->commit( __METHOD__
, 'flush' );
622 if ( $progressCallback ) {
623 if ( intval( $totalSeconds ) === 0 ) {
626 $remainingSeconds = wfTimestamp( TS_UNIX
, $timestamp )
627 - wfTimestamp( TS_UNIX
, $maxExpTime );
628 if ( $remainingSeconds > $totalSeconds ) {
629 $totalSeconds = $remainingSeconds;
631 $percent = ( $i +
$remainingSeconds / $totalSeconds )
632 / $this->shards
* 100;
634 $percent = ( $percent / $this->numServers
)
635 +
( $serverIndex / $this->numServers
* 100 );
636 call_user_func( $progressCallback, $percent );
640 } catch ( DBError
$e ) {
641 $this->handleWriteError( $e, $serverIndex );
648 public function deleteAll() {
649 for ( $serverIndex = 0; $serverIndex < $this->numServers
; $serverIndex++
) {
651 $db = $this->getDB( $serverIndex );
652 for ( $i = 0; $i < $this->shards
; $i++
) {
653 $db->commit( __METHOD__
, 'flush' );
654 $db->delete( $this->getTableNameByShard( $i ), '*', __METHOD__
);
655 $db->commit( __METHOD__
, 'flush' );
657 } catch ( DBError
$e ) {
658 $this->handleWriteError( $e, $serverIndex );
666 * Serialize an object and, if possible, compress the representation.
667 * On typical message and page data, this can provide a 3X decrease
668 * in storage requirements.
673 protected function serialize( &$data ) {
674 $serial = serialize( $data );
676 if ( function_exists( 'gzdeflate' ) ) {
677 return gzdeflate( $serial );
684 * Unserialize and, if necessary, decompress an object.
685 * @param string $serial
688 protected function unserialize( $serial ) {
689 if ( function_exists( 'gzinflate' ) ) {
690 wfSuppressWarnings();
691 $decomp = gzinflate( $serial );
694 if ( false !== $decomp ) {
699 $ret = unserialize( $serial );
705 * Handle a DBError which occurred during a read operation.
707 * @param DBError $exception
708 * @param int $serverIndex
710 protected function handleReadError( DBError
$exception, $serverIndex ) {
711 if ( $exception instanceof DBConnectionError
) {
712 $this->markServerDown( $exception, $serverIndex );
714 wfDebugLog( 'SQLBagOStuff', "DBError: {$exception->getMessage()}" );
715 if ( $exception instanceof DBConnectionError
) {
716 $this->setLastError( BagOStuff
::ERR_UNREACHABLE
);
717 wfDebug( __METHOD__
. ": ignoring connection error\n" );
719 $this->setLastError( BagOStuff
::ERR_UNEXPECTED
);
720 wfDebug( __METHOD__
. ": ignoring query error\n" );
725 * Handle a DBQueryError which occurred during a write operation.
727 * @param DBError $exception
728 * @param int $serverIndex
730 protected function handleWriteError( DBError
$exception, $serverIndex ) {
731 if ( $exception instanceof DBConnectionError
) {
732 $this->markServerDown( $exception, $serverIndex );
734 if ( $exception->db
&& $exception->db
->wasReadOnlyError() ) {
736 $exception->db
->rollback( __METHOD__
);
737 } catch ( DBError
$e ) {
740 wfDebugLog( 'SQLBagOStuff', "DBError: {$exception->getMessage()}" );
741 if ( $exception instanceof DBConnectionError
) {
742 $this->setLastError( BagOStuff
::ERR_UNREACHABLE
);
743 wfDebug( __METHOD__
. ": ignoring connection error\n" );
745 $this->setLastError( BagOStuff
::ERR_UNEXPECTED
);
746 wfDebug( __METHOD__
. ": ignoring query error\n" );
751 * Mark a server down due to a DBConnectionError exception
753 * @param DBError $exception
754 * @param int $serverIndex
756 protected function markServerDown( $exception, $serverIndex ) {
757 if ( isset( $this->connFailureTimes
[$serverIndex] ) ) {
758 if ( time() - $this->connFailureTimes
[$serverIndex] >= 60 ) {
759 unset( $this->connFailureTimes
[$serverIndex] );
760 unset( $this->connFailureErrors
[$serverIndex] );
762 wfDebug( __METHOD__
. ": Server #$serverIndex already down\n" );
767 wfDebug( __METHOD__
. ": Server #$serverIndex down until " . ( $now +
60 ) . "\n" );
768 $this->connFailureTimes
[$serverIndex] = $now;
769 $this->connFailureErrors
[$serverIndex] = $exception;
773 * Create shard tables. For use from eval.php.
775 public function createTables() {
776 for ( $serverIndex = 0; $serverIndex < $this->numServers
; $serverIndex++
) {
777 $db = $this->getDB( $serverIndex );
778 if ( $db->getType() !== 'mysql' ) {
779 throw new MWException( __METHOD__
. ' is not supported on this DB server' );
782 for ( $i = 0; $i < $this->shards
; $i++
) {
783 $db->commit( __METHOD__
, 'flush' );
785 'CREATE TABLE ' . $db->tableName( $this->getTableNameByShard( $i ) ) .
786 ' LIKE ' . $db->tableName( 'objectcache' ),
788 $db->commit( __METHOD__
, 'flush' );
795 * Backwards compatibility alias
797 class MediaWikiBagOStuff
extends SqlBagOStuff
{