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 */
34 protected $serverInfos;
37 protected $serverNames;
40 protected $numServers;
46 protected $lastExpireAll = 0;
49 protected $purgePeriod = 100;
52 protected $shards = 1;
55 protected $tableName = 'objectcache';
58 protected $slaveOnly = false;
60 /** @var array UNIX timestamps */
61 protected $connFailureTimes = array();
63 /** @var array Exceptions */
64 protected $connFailureErrors = array();
67 * Constructor. Parameters are:
68 * - server: A server info structure in the format required by each
69 * element in $wgDBServers.
71 * - servers: An array of server info structures describing a set of
72 * database servers to distribute keys to. If this is
73 * specified, the "server" option will be ignored.
75 * - purgePeriod: The average number of object cache requests in between
76 * garbage collection operations, where expired entries
77 * are removed from the database. Or in other words, the
78 * reciprocal of the probability of purging on any given
79 * request. If this is set to zero, purging will never be
82 * - tableName: The table name to use, default is "objectcache".
84 * - shards: The number of tables to use for data storage on each server.
85 * If this is more than 1, table names will be formed in the style
86 * objectcacheNNN where NNN is the shard index, between 0 and
87 * shards-1. The number of digits will be the minimum number
88 * required to hold the largest shard index. Data will be
89 * distributed across all tables by key hash. This is for
90 * MySQL bugs 61735 and 61736.
91 * - slaveOnly: Whether to only use slave DBs and avoid triggering
92 * garbage collection logic of expired items. This only
93 * makes sense if the primary DB is used and only if get()
94 * calls will be used. This is used by ReplicatedBagOStuff.
96 * @param array $params
98 public function __construct( $params ) {
99 parent
::__construct( $params );
100 if ( isset( $params['servers'] ) ) {
101 $this->serverInfos
= $params['servers'];
102 $this->numServers
= count( $this->serverInfos
);
103 $this->serverNames
= array();
104 foreach ( $this->serverInfos
as $i => $info ) {
105 $this->serverNames
[$i] = isset( $info['host'] ) ?
$info['host'] : "#$i";
107 } elseif ( isset( $params['server'] ) ) {
108 $this->serverInfos
= array( $params['server'] );
109 $this->numServers
= count( $this->serverInfos
);
111 $this->serverInfos
= false;
112 $this->numServers
= 1;
114 if ( isset( $params['purgePeriod'] ) ) {
115 $this->purgePeriod
= intval( $params['purgePeriod'] );
117 if ( isset( $params['tableName'] ) ) {
118 $this->tableName
= $params['tableName'];
120 if ( isset( $params['shards'] ) ) {
121 $this->shards
= intval( $params['shards'] );
123 $this->slaveOnly
= !empty( $params['slaveOnly'] );
127 * Get a connection to the specified database
129 * @param int $serverIndex
131 * @throws MWException
133 protected function getDB( $serverIndex ) {
134 if ( !isset( $this->conns
[$serverIndex] ) ) {
135 if ( $serverIndex >= $this->numServers
) {
136 throw new MWException( __METHOD__
. ": Invalid server index \"$serverIndex\"" );
139 # Don't keep timing out trying to connect for each call if the DB is down
140 if ( isset( $this->connFailureErrors
[$serverIndex] )
141 && ( time() - $this->connFailureTimes
[$serverIndex] ) < 60
143 throw $this->connFailureErrors
[$serverIndex];
146 # If server connection info was given, use that
147 if ( $this->serverInfos
) {
148 $info = $this->serverInfos
[$serverIndex];
149 $type = isset( $info['type'] ) ?
$info['type'] : 'mysql';
150 $host = isset( $info['host'] ) ?
$info['host'] : '[unknown]';
151 $this->logger
->debug( __CLASS__
. ": connecting to $host" );
152 // Use a blank trx profiler to ignore expections as this is a cache
153 $info['trxProfiler'] = new TransactionProfiler();
154 $db = DatabaseBase
::factory( $type, $info );
155 $db->clearFlag( DBO_TRX
);
158 * We must keep a separate connection to MySQL in order to avoid deadlocks
159 * However, SQLite has an opposite behavior. And PostgreSQL needs to know
160 * if we are in transaction or no
162 $index = $this->slaveOnly ? DB_SLAVE
: DB_MASTER
;
163 if ( wfGetDB( $index )->getType() == 'mysql' ) {
164 $this->lb
= wfGetLBFactory()->newMainLB();
165 $db = $this->lb
->getConnection( $index );
166 $db->clearFlag( DBO_TRX
); // auto-commit mode
168 $db = wfGetDB( $index );
171 $this->logger
->debug( sprintf( "Connection %s will be used for SqlBagOStuff", $db ) );
172 $this->conns
[$serverIndex] = $db;
175 return $this->conns
[$serverIndex];
179 * Get the server index and table name for a given key
181 * @return array Server index and table name
183 protected function getTableByKey( $key ) {
184 if ( $this->shards
> 1 ) {
185 $hash = hexdec( substr( md5( $key ), 0, 8 ) ) & 0x7fffffff;
186 $tableIndex = $hash %
$this->shards
;
190 if ( $this->numServers
> 1 ) {
191 $sortedServers = $this->serverNames
;
192 ArrayUtils
::consistentHashSort( $sortedServers, $key );
193 reset( $sortedServers );
194 $serverIndex = key( $sortedServers );
198 return array( $serverIndex, $this->getTableNameByShard( $tableIndex ) );
202 * Get the table name for a given shard index
206 protected function getTableNameByShard( $index ) {
207 if ( $this->shards
> 1 ) {
208 $decimals = strlen( $this->shards
- 1 );
209 return $this->tableName
.
210 sprintf( "%0{$decimals}d", $index );
212 return $this->tableName
;
216 protected function doGet( $key, $flags = 0 ) {
219 return $this->getWithToken( $key, $casToken, $flags );
222 protected function getWithToken( $key, &$casToken, $flags = 0 ) {
223 $values = $this->getMulti( array( $key ) );
224 if ( array_key_exists( $key, $values ) ) {
225 $casToken = $values[$key];
226 return $values[$key];
231 public function getMulti( array $keys, $flags = 0 ) {
232 $values = array(); // array of (key => value)
234 $keysByTable = array();
235 foreach ( $keys as $key ) {
236 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
237 $keysByTable[$serverIndex][$tableName][] = $key;
240 $this->garbageCollect(); // expire old entries if any
243 foreach ( $keysByTable as $serverIndex => $serverKeys ) {
245 $db = $this->getDB( $serverIndex );
246 foreach ( $serverKeys as $tableName => $tableKeys ) {
247 $res = $db->select( $tableName,
248 array( 'keyname', 'value', 'exptime' ),
249 array( 'keyname' => $tableKeys ),
251 // Approximate write-on-the-fly BagOStuff API via blocking.
252 // This approximation fails if a ROLLBACK happens (which is rare).
253 // We do not want to flush the TRX as that can break callers.
254 $db->trxLevel() ?
array( 'LOCK IN SHARE MODE' ) : array()
256 if ( $res === false ) {
259 foreach ( $res as $row ) {
260 $row->serverIndex
= $serverIndex;
261 $row->tableName
= $tableName;
262 $dataRows[$row->keyname
] = $row;
265 } catch ( DBError
$e ) {
266 $this->handleReadError( $e, $serverIndex );
270 foreach ( $keys as $key ) {
271 if ( isset( $dataRows[$key] ) ) { // HIT?
272 $row = $dataRows[$key];
273 $this->debug( "get: retrieved data; expiry time is " . $row->exptime
);
275 $db = $this->getDB( $row->serverIndex
);
276 if ( $this->isExpired( $db, $row->exptime
) ) { // MISS
277 $this->debug( "get: key has expired" );
279 $values[$key] = $this->unserialize( $db->decodeBlob( $row->value
) );
281 } catch ( DBQueryError
$e ) {
282 $this->handleWriteError( $e, $row->serverIndex
);
285 $this->debug( 'get: no matching rows' );
297 public function setMulti( array $data, $expiry = 0 ) {
298 $keysByTable = array();
299 foreach ( $data as $key => $value ) {
300 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
301 $keysByTable[$serverIndex][$tableName][] = $key;
304 $this->garbageCollect(); // expire old entries if any
307 $exptime = (int)$expiry;
308 foreach ( $keysByTable as $serverIndex => $serverKeys ) {
310 $db = $this->getDB( $serverIndex );
311 } catch ( DBError
$e ) {
312 $this->handleWriteError( $e, $serverIndex );
317 if ( $exptime < 0 ) {
321 if ( $exptime == 0 ) {
322 $encExpiry = $this->getMaxDateTime( $db );
324 $exptime = $this->convertExpiry( $exptime );
325 $encExpiry = $db->timestamp( $exptime );
327 foreach ( $serverKeys as $tableName => $tableKeys ) {
329 foreach ( $tableKeys as $key ) {
332 'value' => $db->encodeBlob( $this->serialize( $data[$key] ) ),
333 'exptime' => $encExpiry,
344 } catch ( DBError
$e ) {
345 $this->handleWriteError( $e, $serverIndex );
358 * @param mixed $value
359 * @param int $exptime
362 public function set( $key, $value, $exptime = 0 ) {
363 return $this->setMulti( array( $key => $value ), $exptime );
367 * @param mixed $casToken
369 * @param mixed $value
370 * @param int $exptime
373 protected function cas( $casToken, $key, $value, $exptime = 0 ) {
374 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
376 $db = $this->getDB( $serverIndex );
377 $exptime = intval( $exptime );
379 if ( $exptime < 0 ) {
383 if ( $exptime == 0 ) {
384 $encExpiry = $this->getMaxDateTime( $db );
386 $exptime = $this->convertExpiry( $exptime );
387 $encExpiry = $db->timestamp( $exptime );
389 // (bug 24425) use a replace if the db supports it instead of
390 // delete/insert to avoid clashes with conflicting keynames
395 'value' => $db->encodeBlob( $this->serialize( $value ) ),
396 'exptime' => $encExpiry
400 'value' => $db->encodeBlob( $this->serialize( $casToken ) )
404 } catch ( DBQueryError
$e ) {
405 $this->handleWriteError( $e, $serverIndex );
410 return (bool)$db->affectedRows();
417 public function delete( $key ) {
418 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
420 $db = $this->getDB( $serverIndex );
423 array( 'keyname' => $key ),
425 } catch ( DBError
$e ) {
426 $this->handleWriteError( $e, $serverIndex );
438 public function incr( $key, $step = 1 ) {
439 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
441 $db = $this->getDB( $serverIndex );
442 $step = intval( $step );
443 $row = $db->selectRow(
445 array( 'value', 'exptime' ),
446 array( 'keyname' => $key ),
448 array( 'FOR UPDATE' ) );
449 if ( $row === false ) {
454 $db->delete( $tableName, array( 'keyname' => $key ), __METHOD__
);
455 if ( $this->isExpired( $db, $row->exptime
) ) {
456 // Expired, do not reinsert
461 $oldValue = intval( $this->unserialize( $db->decodeBlob( $row->value
) ) );
462 $newValue = $oldValue +
$step;
463 $db->insert( $tableName,
466 'value' => $db->encodeBlob( $this->serialize( $newValue ) ),
467 'exptime' => $row->exptime
468 ), __METHOD__
, 'IGNORE' );
470 if ( $db->affectedRows() == 0 ) {
471 // Race condition. See bug 28611
474 } catch ( DBError
$e ) {
475 $this->handleWriteError( $e, $serverIndex );
482 public function merge( $key, $callback, $exptime = 0, $attempts = 10 ) {
483 if ( !is_callable( $callback ) ) {
484 throw new Exception( "Got invalid callback." );
487 return $this->mergeViaCas( $key, $callback, $exptime, $attempts );
491 * @param IDatabase $db
492 * @param string $exptime
495 protected function isExpired( $db, $exptime ) {
496 return $exptime != $this->getMaxDateTime( $db ) && wfTimestamp( TS_UNIX
, $exptime ) < time();
500 * @param IDatabase $db
503 protected function getMaxDateTime( $db ) {
504 if ( time() > 0x7fffffff ) {
505 return $db->timestamp( 1 << 62 );
507 return $db->timestamp( 0x7fffffff );
511 protected function garbageCollect() {
512 if ( !$this->purgePeriod ||
$this->slaveOnly
) {
516 // Only purge on one in every $this->purgePeriod requests.
517 if ( $this->purgePeriod
!== 1 && mt_rand( 0, $this->purgePeriod
- 1 ) ) {
521 // Avoid repeating the delete within a few seconds
522 if ( $now > ( $this->lastExpireAll +
1 ) ) {
523 $this->lastExpireAll
= $now;
528 public function expireAll() {
529 $this->deleteObjectsExpiringBefore( wfTimestampNow() );
533 * Delete objects from the database which expire before a certain date.
534 * @param string $timestamp
535 * @param bool|callable $progressCallback
538 public function deleteObjectsExpiringBefore( $timestamp, $progressCallback = false ) {
539 for ( $serverIndex = 0; $serverIndex < $this->numServers
; $serverIndex++
) {
541 $db = $this->getDB( $serverIndex );
542 $dbTimestamp = $db->timestamp( $timestamp );
543 $totalSeconds = false;
544 $baseConds = array( 'exptime < ' . $db->addQuotes( $dbTimestamp ) );
545 for ( $i = 0; $i < $this->shards
; $i++
) {
549 if ( $maxExpTime !== false ) {
550 $conds[] = 'exptime > ' . $db->addQuotes( $maxExpTime );
553 $this->getTableNameByShard( $i ),
554 array( 'keyname', 'exptime' ),
557 array( 'LIMIT' => 100, 'ORDER BY' => 'exptime' ) );
558 if ( $rows === false ||
!$rows->numRows() ) {
562 $row = $rows->current();
563 $minExpTime = $row->exptime
;
564 if ( $totalSeconds === false ) {
565 $totalSeconds = wfTimestamp( TS_UNIX
, $timestamp )
566 - wfTimestamp( TS_UNIX
, $minExpTime );
568 foreach ( $rows as $row ) {
569 $keys[] = $row->keyname
;
570 $maxExpTime = $row->exptime
;
574 $this->getTableNameByShard( $i ),
576 'exptime >= ' . $db->addQuotes( $minExpTime ),
577 'exptime < ' . $db->addQuotes( $dbTimestamp ),
582 if ( $progressCallback ) {
583 if ( intval( $totalSeconds ) === 0 ) {
586 $remainingSeconds = wfTimestamp( TS_UNIX
, $timestamp )
587 - wfTimestamp( TS_UNIX
, $maxExpTime );
588 if ( $remainingSeconds > $totalSeconds ) {
589 $totalSeconds = $remainingSeconds;
591 $processedSeconds = $totalSeconds - $remainingSeconds;
592 $percent = ( $i +
$processedSeconds / $totalSeconds )
593 / $this->shards
* 100;
595 $percent = ( $percent / $this->numServers
)
596 +
( $serverIndex / $this->numServers
* 100 );
597 call_user_func( $progressCallback, $percent );
601 } catch ( DBError
$e ) {
602 $this->handleWriteError( $e, $serverIndex );
610 * Delete content of shard tables in every server.
611 * Return true if the operation is successful, false otherwise.
614 public function deleteAll() {
615 for ( $serverIndex = 0; $serverIndex < $this->numServers
; $serverIndex++
) {
617 $db = $this->getDB( $serverIndex );
618 for ( $i = 0; $i < $this->shards
; $i++
) {
619 $db->delete( $this->getTableNameByShard( $i ), '*', __METHOD__
);
621 } catch ( DBError
$e ) {
622 $this->handleWriteError( $e, $serverIndex );
630 * Serialize an object and, if possible, compress the representation.
631 * On typical message and page data, this can provide a 3X decrease
632 * in storage requirements.
637 protected function serialize( &$data ) {
638 $serial = serialize( $data );
640 if ( function_exists( 'gzdeflate' ) ) {
641 return gzdeflate( $serial );
648 * Unserialize and, if necessary, decompress an object.
649 * @param string $serial
652 protected function unserialize( $serial ) {
653 if ( function_exists( 'gzinflate' ) ) {
654 MediaWiki\
suppressWarnings();
655 $decomp = gzinflate( $serial );
656 MediaWiki\restoreWarnings
();
658 if ( false !== $decomp ) {
663 $ret = unserialize( $serial );
669 * Handle a DBError which occurred during a read operation.
671 * @param DBError $exception
672 * @param int $serverIndex
674 protected function handleReadError( DBError
$exception, $serverIndex ) {
675 if ( $exception instanceof DBConnectionError
) {
676 $this->markServerDown( $exception, $serverIndex );
678 $this->logger
->error( "DBError: {$exception->getMessage()}" );
679 if ( $exception instanceof DBConnectionError
) {
680 $this->setLastError( BagOStuff
::ERR_UNREACHABLE
);
681 $this->logger
->debug( __METHOD__
. ": ignoring connection error" );
683 $this->setLastError( BagOStuff
::ERR_UNEXPECTED
);
684 $this->logger
->debug( __METHOD__
. ": ignoring query error" );
689 * Handle a DBQueryError which occurred during a write operation.
691 * @param DBError $exception
692 * @param int $serverIndex
694 protected function handleWriteError( DBError
$exception, $serverIndex ) {
695 if ( $exception instanceof DBConnectionError
) {
696 $this->markServerDown( $exception, $serverIndex );
698 if ( $exception->db
&& $exception->db
->wasReadOnlyError() ) {
699 if ( $exception->db
->trxLevel() ) {
701 $exception->db
->rollback( __METHOD__
);
702 } catch ( DBError
$e ) {
707 $this->logger
->error( "DBError: {$exception->getMessage()}" );
708 if ( $exception instanceof DBConnectionError
) {
709 $this->setLastError( BagOStuff
::ERR_UNREACHABLE
);
710 $this->logger
->debug( __METHOD__
. ": ignoring connection error" );
712 $this->setLastError( BagOStuff
::ERR_UNEXPECTED
);
713 $this->logger
->debug( __METHOD__
. ": ignoring query error" );
718 * Mark a server down due to a DBConnectionError exception
720 * @param DBError $exception
721 * @param int $serverIndex
723 protected function markServerDown( $exception, $serverIndex ) {
724 unset( $this->conns
[$serverIndex] ); // bug T103435
726 if ( isset( $this->connFailureTimes
[$serverIndex] ) ) {
727 if ( time() - $this->connFailureTimes
[$serverIndex] >= 60 ) {
728 unset( $this->connFailureTimes
[$serverIndex] );
729 unset( $this->connFailureErrors
[$serverIndex] );
731 $this->logger
->debug( __METHOD__
. ": Server #$serverIndex already down" );
736 $this->logger
->info( __METHOD__
. ": Server #$serverIndex down until " . ( $now +
60 ) );
737 $this->connFailureTimes
[$serverIndex] = $now;
738 $this->connFailureErrors
[$serverIndex] = $exception;
742 * Create shard tables. For use from eval.php.
744 public function createTables() {
745 for ( $serverIndex = 0; $serverIndex < $this->numServers
; $serverIndex++
) {
746 $db = $this->getDB( $serverIndex );
747 if ( $db->getType() !== 'mysql' ) {
748 throw new MWException( __METHOD__
. ' is not supported on this DB server' );
751 for ( $i = 0; $i < $this->shards
; $i++
) {
753 'CREATE TABLE ' . $db->tableName( $this->getTableNameByShard( $i ) ) .
754 ' LIKE ' . $db->tableName( 'objectcache' ),