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
{
38 var $lastExpireAll = 0;
39 var $purgePeriod = 100;
41 var $tableName = 'objectcache';
43 protected $connFailureTimes = array(); // UNIX timestamps
44 protected $connFailureErrors = array(); // exceptions
47 * Constructor. Parameters are:
48 * - server: A server info structure in the format required by each
49 * element in $wgDBServers.
51 * - servers: An array of server info structures describing a set of
52 * database servers to distribute keys to. If this is
53 * specified, the "server" option will be ignored.
55 * - purgePeriod: The average number of object cache requests in between
56 * garbage collection operations, where expired entries
57 * are removed from the database. Or in other words, the
58 * reciprocal of the probability of purging on any given
59 * request. If this is set to zero, purging will never be
62 * - tableName: The table name to use, default is "objectcache".
64 * - shards: The number of tables to use for data storage on each server.
65 * If this is more than 1, table names will be formed in the style
66 * objectcacheNNN where NNN is the shard index, between 0 and
67 * shards-1. The number of digits will be the minimum number
68 * required to hold the largest shard index. Data will be
69 * distributed across all tables by key hash. This is for
70 * MySQL bugs 61735 and 61736.
72 * @param $params array
74 public function __construct( $params ) {
75 if ( isset( $params['servers'] ) ) {
76 $this->serverInfos
= $params['servers'];
77 $this->numServers
= count( $this->serverInfos
);
78 } elseif ( isset( $params['server'] ) ) {
79 $this->serverInfos
= array( $params['server'] );
80 $this->numServers
= count( $this->serverInfos
);
82 $this->serverInfos
= false;
83 $this->numServers
= 1;
85 if ( isset( $params['purgePeriod'] ) ) {
86 $this->purgePeriod
= intval( $params['purgePeriod'] );
88 if ( isset( $params['tableName'] ) ) {
89 $this->tableName
= $params['tableName'];
91 if ( isset( $params['shards'] ) ) {
92 $this->shards
= intval( $params['shards'] );
97 * Get a connection to the specified database
99 * @param $serverIndex integer
100 * @return DatabaseBase
102 protected function getDB( $serverIndex ) {
103 global $wgDebugDBTransactions;
105 if ( !isset( $this->conns
[$serverIndex] ) ) {
106 if ( $serverIndex >= $this->numServers
) {
107 throw new MWException( __METHOD__
. ": Invalid server index \"$serverIndex\"" );
110 # Don't keep timing out trying to connect for each call if the DB is down
111 if ( isset( $this->connFailureErrors
[$serverIndex] )
112 && ( time() - $this->connFailureTimes
[$serverIndex] ) < 60 )
114 throw $this->connFailureErrors
[$serverIndex];
117 # If server connection info was given, use that
118 if ( $this->serverInfos
) {
119 if ( $wgDebugDBTransactions ) {
120 wfDebug( "Using provided serverInfo for SqlBagOStuff\n" );
122 $info = $this->serverInfos
[$serverIndex];
123 $type = isset( $info['type'] ) ?
$info['type'] : 'mysql';
124 $host = isset( $info['host'] ) ?
$info['host'] : '[unknown]';
125 wfDebug( __CLASS__
.": connecting to $host\n" );
126 $db = DatabaseBase
::factory( $type, $info );
127 $db->clearFlag( DBO_TRX
);
130 * We must keep a separate connection to MySQL in order to avoid deadlocks
131 * However, SQLite has an opposite behaviour. And PostgreSQL needs to know
132 * if we are in transaction or no
134 if ( wfGetDB( DB_MASTER
)->getType() == 'mysql' ) {
135 $this->lb
= wfGetLBFactory()->newMainLB();
136 $db = $this->lb
->getConnection( DB_MASTER
);
137 $db->clearFlag( DBO_TRX
); // auto-commit mode
139 $db = wfGetDB( DB_MASTER
);
142 if ( $wgDebugDBTransactions ) {
143 wfDebug( sprintf( "Connection %s will be used for SqlBagOStuff\n", $db ) );
145 $this->conns
[$serverIndex] = $db;
148 return $this->conns
[$serverIndex];
152 * Get the server index and table name for a given key
154 * @return Array: server index and table name
156 protected function getTableByKey( $key ) {
157 $numTables = $this->shards
* $this->numServers
;
158 if ( $numTables > 1 ) {
159 $hash = ( hexdec( substr( md5( $key ), 0, 8 ) ) & 0x7fffffff ) %
$numTables;
160 $tableIndex = $hash %
$this->shards
;
161 $serverIndex = intval( round( ( $hash - $tableIndex ) / $this->shards
) );
162 $tableName = $this->getTableNameByShard( $tableIndex );
163 return array( $serverIndex, $tableName );
165 return array( 0, $this->tableName
);
170 * Get the table name for a given shard index
174 protected function getTableNameByShard( $index ) {
175 if ( $this->shards
> 1 ) {
176 $decimals = strlen( $this->shards
- 1 );
177 return $this->tableName
.
178 sprintf( "%0{$decimals}d", $index );
180 return $this->tableName
;
188 public function get( $key ) {
189 $values = $this->getMulti( array( $key ) );
190 return array_key_exists( $key, $values ) ?
$values[$key] : false;
197 public function getMulti( array $keys ) {
198 $values = array(); // array of (key => value)
200 $keysByTable = array();
201 foreach ( $keys as $key ) {
202 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
203 $keysByTable[$serverIndex][$tableName][] = $key;
206 $this->garbageCollect(); // expire old entries if any
209 foreach ( $keysByTable as $serverIndex => $serverKeys ) {
210 $db = $this->getDB( $serverIndex );
212 foreach ( $serverKeys as $tableName => $tableKeys ) {
213 $res = $db->select( $tableName,
214 array( 'keyname', 'value', 'exptime' ),
215 array( 'keyname' => $tableKeys ),
217 foreach ( $res as $row ) {
218 $row->serverIndex
= $serverIndex;
219 $row->tableName
= $tableName;
220 $dataRows[$row->keyname
] = $row;
223 } catch ( DBError
$e ) {
224 $this->handleReadError( $e, $serverIndex );
228 foreach ( $keys as $key ) {
229 if ( isset( $dataRows[$key] ) ) { // HIT?
230 $row = $dataRows[$key];
231 $this->debug( "get: retrieved data; expiry time is " . $row->exptime
);
232 $db = $this->getDB( $row->serverIndex
);
233 if ( $this->isExpired( $db, $row->exptime
) ) { // MISS
234 $this->debug( "get: key has expired, deleting" );
236 $db->begin( __METHOD__
);
237 # Put the expiry time in the WHERE condition to avoid deleting a
238 # newly-inserted value
239 $db->delete( $row->tableName
,
240 array( 'keyname' => $key, 'exptime' => $row->exptime
),
242 $db->commit( __METHOD__
);
243 } catch ( DBQueryError
$e ) {
244 $this->handleWriteError( $e, $row->serverIndex
);
246 $values[$key] = false;
248 $values[$key] = $this->unserialize( $db->decodeBlob( $row->value
) );
251 $values[$key] = false;
252 $this->debug( 'get: no matching rows' );
261 * @param $value mixed
262 * @param $exptime int
265 public function set( $key, $value, $exptime = 0 ) {
266 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
268 $db = $this->getDB( $serverIndex );
269 $exptime = intval( $exptime );
271 if ( $exptime < 0 ) {
275 if ( $exptime == 0 ) {
276 $encExpiry = $this->getMaxDateTime( $db );
278 if ( $exptime < 3.16e8
) { # ~10 years
282 $encExpiry = $db->timestamp( $exptime );
284 $db->begin( __METHOD__
);
285 // (bug 24425) use a replace if the db supports it instead of
286 // delete/insert to avoid clashes with conflicting keynames
292 'value' => $db->encodeBlob( $this->serialize( $value ) ),
293 'exptime' => $encExpiry
295 $db->commit( __METHOD__
);
296 } catch ( DBError
$e ) {
297 $this->handleWriteError( $e, $serverIndex );
309 public function delete( $key, $time = 0 ) {
310 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
312 $db = $this->getDB( $serverIndex );
313 $db->begin( __METHOD__
);
316 array( 'keyname' => $key ),
318 $db->commit( __METHOD__
);
319 } catch ( DBError
$e ) {
320 $this->handleWriteError( $e, $serverIndex );
332 public function incr( $key, $step = 1 ) {
333 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
335 $db = $this->getDB( $serverIndex );
336 $step = intval( $step );
337 $db->begin( __METHOD__
);
338 $row = $db->selectRow(
340 array( 'value', 'exptime' ),
341 array( 'keyname' => $key ),
343 array( 'FOR UPDATE' ) );
344 if ( $row === false ) {
346 $db->commit( __METHOD__
);
350 $db->delete( $tableName, array( 'keyname' => $key ), __METHOD__
);
351 if ( $this->isExpired( $db, $row->exptime
) ) {
352 // Expired, do not reinsert
353 $db->commit( __METHOD__
);
358 $oldValue = intval( $this->unserialize( $db->decodeBlob( $row->value
) ) );
359 $newValue = $oldValue +
$step;
360 $db->insert( $tableName,
363 'value' => $db->encodeBlob( $this->serialize( $newValue ) ),
364 'exptime' => $row->exptime
365 ), __METHOD__
, 'IGNORE' );
367 if ( $db->affectedRows() == 0 ) {
368 // Race condition. See bug 28611
371 $db->commit( __METHOD__
);
372 } catch ( DBError
$e ) {
373 $this->handleWriteError( $e, $serverIndex );
383 public function keys() {
386 for ( $serverIndex = 0; $serverIndex < $this->numServers
; $serverIndex++
) {
388 $db = $this->getDB( $serverIndex );
389 for ( $i = 0; $i < $this->shards
; $i++
) {
390 $res = $db->select( $this->getTableNameByShard( $i ),
391 array( 'keyname' ), false, __METHOD__
);
392 foreach ( $res as $row ) {
393 $result[] = $row->keyname
;
396 } catch ( DBError
$e ) {
397 $this->handleReadError( $e, $serverIndex );
404 * @param $exptime string
407 protected function isExpired( $db, $exptime ) {
408 return $exptime != $this->getMaxDateTime( $db ) && wfTimestamp( TS_UNIX
, $exptime ) < time();
414 protected function getMaxDateTime( $db ) {
415 if ( time() > 0x7fffffff ) {
416 return $db->timestamp( 1 << 62 );
418 return $db->timestamp( 0x7fffffff );
422 protected function garbageCollect() {
423 if ( !$this->purgePeriod
) {
427 // Only purge on one in every $this->purgePeriod requests.
428 if ( $this->purgePeriod
!== 1 && mt_rand( 0, $this->purgePeriod
- 1 ) ) {
432 // Avoid repeating the delete within a few seconds
433 if ( $now > ( $this->lastExpireAll +
1 ) ) {
434 $this->lastExpireAll
= $now;
439 public function expireAll() {
440 $this->deleteObjectsExpiringBefore( wfTimestampNow() );
444 * Delete objects from the database which expire before a certain date.
445 * @param $timestamp string
446 * @param $progressCallback bool|callback
449 public function deleteObjectsExpiringBefore( $timestamp, $progressCallback = false ) {
450 for ( $serverIndex = 0; $serverIndex < $this->numServers
; $serverIndex++
) {
452 $db = $this->getDB( $serverIndex );
453 $dbTimestamp = $db->timestamp( $timestamp );
454 $totalSeconds = false;
455 $baseConds = array( 'exptime < ' . $db->addQuotes( $dbTimestamp ) );
456 for ( $i = 0; $i < $this->shards
; $i++
) {
460 if ( $maxExpTime !== false ) {
461 $conds[] = 'exptime > ' . $db->addQuotes( $maxExpTime );
464 $this->getTableNameByShard( $i ),
465 array( 'keyname', 'exptime' ),
468 array( 'LIMIT' => 100, 'ORDER BY' => 'exptime' ) );
469 if ( !$rows->numRows() ) {
473 $row = $rows->current();
474 $minExpTime = $row->exptime
;
475 if ( $totalSeconds === false ) {
476 $totalSeconds = wfTimestamp( TS_UNIX
, $timestamp )
477 - wfTimestamp( TS_UNIX
, $minExpTime );
479 foreach ( $rows as $row ) {
480 $keys[] = $row->keyname
;
481 $maxExpTime = $row->exptime
;
484 $db->begin( __METHOD__
);
486 $this->getTableNameByShard( $i ),
488 'exptime >= ' . $db->addQuotes( $minExpTime ),
489 'exptime < ' . $db->addQuotes( $dbTimestamp ),
493 $db->commit( __METHOD__
);
495 if ( $progressCallback ) {
496 if ( intval( $totalSeconds ) === 0 ) {
499 $remainingSeconds = wfTimestamp( TS_UNIX
, $timestamp )
500 - wfTimestamp( TS_UNIX
, $maxExpTime );
501 if ( $remainingSeconds > $totalSeconds ) {
502 $totalSeconds = $remainingSeconds;
504 $percent = ( $i +
$remainingSeconds / $totalSeconds )
505 / $this->shards
* 100;
507 $percent = ( $percent / $this->numServers
)
508 +
( $serverIndex / $this->numServers
* 100 );
509 call_user_func( $progressCallback, $percent );
513 } catch ( DBError
$e ) {
514 $this->handleWriteError( $e, $serverIndex );
521 public function deleteAll() {
522 for ( $serverIndex = 0; $serverIndex < $this->numServers
; $serverIndex++
) {
524 $db = $this->getDB( $serverIndex );
525 for ( $i = 0; $i < $this->shards
; $i++
) {
526 $db->begin( __METHOD__
);
527 $db->delete( $this->getTableNameByShard( $i ), '*', __METHOD__
);
528 $db->commit( __METHOD__
);
530 } catch ( DBError
$e ) {
531 $this->handleWriteError( $e, $serverIndex );
539 * Serialize an object and, if possible, compress the representation.
540 * On typical message and page data, this can provide a 3X decrease
541 * in storage requirements.
546 protected function serialize( &$data ) {
547 $serial = serialize( $data );
549 if ( function_exists( 'gzdeflate' ) ) {
550 return gzdeflate( $serial );
557 * Unserialize and, if necessary, decompress an object.
558 * @param $serial string
561 protected function unserialize( $serial ) {
562 if ( function_exists( 'gzinflate' ) ) {
563 wfSuppressWarnings();
564 $decomp = gzinflate( $serial );
567 if ( false !== $decomp ) {
572 $ret = unserialize( $serial );
578 * Handle a DBError which occurred during a read operation.
580 protected function handleReadError( DBError
$exception, $serverIndex ) {
581 if ( $exception instanceof DBConnectionError
) {
582 $this->markServerDown( $exception, $serverIndex );
584 wfDebugLog( 'SQLBagOStuff', "DBError: {$exception->getMessage()}" );
585 if ( $exception instanceof DBConnectionError
) {
586 wfDebug( __METHOD__
. ": ignoring connection error\n" );
588 wfDebug( __METHOD__
. ": ignoring query error\n" );
593 * Handle a DBQueryError which occurred during a write operation.
595 protected function handleWriteError( DBError
$exception, $serverIndex ) {
596 if ( $exception instanceof DBConnectionError
) {
597 $this->markServerDown( $exception, $serverIndex );
599 if ( $exception->db
&& $exception->db
->wasReadOnlyError() ) {
601 $exception->db
->rollback( __METHOD__
);
602 } catch ( DBError
$e ) {}
604 wfDebugLog( 'SQLBagOStuff', "DBError: {$exception->getMessage()}" );
605 if ( $exception instanceof DBConnectionError
) {
606 wfDebug( __METHOD__
. ": ignoring connection error\n" );
608 wfDebug( __METHOD__
. ": ignoring query error\n" );
613 * Mark a server down due to a DBConnectionError exception
615 protected function markServerDown( $exception, $serverIndex ) {
616 if ( isset( $this->connFailureTimes
[$serverIndex] ) ) {
617 if ( time() - $this->connFailureTimes
[$serverIndex] >= 60 ) {
618 unset( $this->connFailureTimes
[$serverIndex] );
619 unset( $this->connFailureErrors
[$serverIndex] );
621 wfDebug( __METHOD__
.": Server #$serverIndex already down\n" );
626 wfDebug( __METHOD__
.": Server #$serverIndex down until " . ( $now +
60 ) . "\n" );
627 $this->connFailureTimes
[$serverIndex] = $now;
628 $this->connFailureErrors
[$serverIndex] = $exception;
632 * Create shard tables. For use from eval.php.
634 public function createTables() {
635 for ( $serverIndex = 0; $serverIndex < $this->numServers
; $serverIndex++
) {
636 $db = $this->getDB( $serverIndex );
637 if ( $db->getType() !== 'mysql'
638 ||
version_compare( $db->getServerVersion(), '4.1.0', '<' ) )
640 throw new MWException( __METHOD__
. ' is not supported on this DB server' );
643 for ( $i = 0; $i < $this->shards
; $i++
) {
644 $db->begin( __METHOD__
);
646 'CREATE TABLE ' . $db->tableName( $this->getTableNameByShard( $i ) ) .
647 ' LIKE ' . $db->tableName( 'objectcache' ),
649 $db->commit( __METHOD__
);
656 * Backwards compatibility alias
658 class MediaWikiBagOStuff
extends SqlBagOStuff
{ }