Localisation updates from http://translatewiki.net.
[mediawiki.git] / includes / objectcache / SqlBagOStuff.php
blobe5048870904e33b07263e5b8105e6c1452c27b52
1 <?php
2 /**
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
20 * @file
21 * @ingroup Cache
24 /**
25 * Class to store objects in the database
27 * @ingroup Cache
29 class SqlBagOStuff extends BagOStuff {
31 /**
32 * @var LoadBalancer
34 var $lb;
36 /**
37 * @var DatabaseBase
39 var $db;
40 var $serverInfo;
41 var $lastExpireAll = 0;
42 var $purgePeriod = 100;
43 var $shards = 1;
44 var $tableName = 'objectcache';
46 /**
47 * Constructor. Parameters are:
48 * - server: A server info structure in the format required by each
49 * element in $wgDBServers.
51 * - purgePeriod: The average number of object cache requests in between
52 * garbage collection operations, where expired entries
53 * are removed from the database. Or in other words, the
54 * reciprocal of the probability of purging on any given
55 * request. If this is set to zero, purging will never be
56 * done.
58 * - tableName: The table name to use, default is "objectcache".
60 * - shards: The number of tables to use for data storage. If this is
61 * more than 1, table names will be formed in the style
62 * objectcacheNNN where NNN is the shard index, between 0 and
63 * shards-1. The number of digits will be the minimum number
64 * required to hold the largest shard index. Data will be
65 * distributed across all tables by key hash. This is for
66 * MySQL bugs 61735 and 61736.
68 * @param $params array
70 public function __construct( $params ) {
71 if ( isset( $params['server'] ) ) {
72 $this->serverInfo = $params['server'];
73 $this->serverInfo['load'] = 1;
75 if ( isset( $params['purgePeriod'] ) ) {
76 $this->purgePeriod = intval( $params['purgePeriod'] );
78 if ( isset( $params['tableName'] ) ) {
79 $this->tableName = $params['tableName'];
81 if ( isset( $params['shards'] ) ) {
82 $this->shards = intval( $params['shards'] );
86 /**
87 * @return DatabaseBase
89 protected function getDB() {
90 if ( !isset( $this->db ) ) {
91 # If server connection info was given, use that
92 if ( $this->serverInfo ) {
93 $this->lb = new LoadBalancer( array(
94 'servers' => array( $this->serverInfo ) ) );
95 $this->db = $this->lb->getConnection( DB_MASTER );
96 $this->db->clearFlag( DBO_TRX );
97 } else {
98 # We must keep a separate connection to MySQL in order to avoid deadlocks
99 # However, SQLite has an opposite behaviour.
100 # @todo Investigate behaviour for other databases
101 if ( wfGetDB( DB_MASTER )->getType() == 'sqlite' ) {
102 $this->db = wfGetDB( DB_MASTER );
103 } else {
104 $this->lb = wfGetLBFactory()->newMainLB();
105 $this->db = $this->lb->getConnection( DB_MASTER );
106 $this->db->clearFlag( DBO_TRX );
111 return $this->db;
115 * Get the table name for a given key
116 * @return string
118 protected function getTableByKey( $key ) {
119 if ( $this->shards > 1 ) {
120 $hash = hexdec( substr( md5( $key ), 0, 8 ) ) & 0x7fffffff;
121 return $this->getTableByShard( $hash % $this->shards );
122 } else {
123 return $this->tableName;
128 * Get the table name for a given shard index
129 * @return string
131 protected function getTableByShard( $index ) {
132 if ( $this->shards > 1 ) {
133 $decimals = strlen( $this->shards - 1 );
134 return $this->tableName .
135 sprintf( "%0{$decimals}d", $index );
136 } else {
137 return $this->tableName;
141 public function get( $key ) {
142 $values = $this->getMulti( array( $key ) );
143 return $values[$key];
146 public function getMulti( array $keys ) {
147 $values = array(); // array of (key => value)
149 $keysByTableName = array();
150 foreach ( $keys as $key ) {
151 $tableName = $this->getTableByKey( $key );
152 if ( !isset( $keysByTableName[$tableName] ) ) {
153 $keysByTableName[$tableName] = array();
155 $keysByTableName[$tableName][] = $key;
158 $db = $this->getDB();
159 $this->garbageCollect(); // expire old entries if any
161 $dataRows = array();
162 foreach ( $keysByTableName as $tableName => $tableKeys ) {
163 $res = $db->select( $tableName,
164 array( 'keyname', 'value', 'exptime' ),
165 array( 'keyname' => $tableKeys ),
166 __METHOD__ );
167 foreach ( $res as $row ) {
168 $dataRows[$row->keyname] = $row;
172 foreach ( $keys as $key ) {
173 if ( isset( $dataRows[$key] ) ) { // HIT?
174 $row = $dataRows[$key];
175 $this->debug( "get: retrieved data; expiry time is " . $row->exptime );
176 if ( $this->isExpired( $row->exptime ) ) { // MISS
177 $this->debug( "get: key has expired, deleting" );
178 try {
179 $db->begin( __METHOD__ );
180 # Put the expiry time in the WHERE condition to avoid deleting a
181 # newly-inserted value
182 $db->delete( $this->getTableByKey( $key ),
183 array( 'keyname' => $key, 'exptime' => $row->exptime ),
184 __METHOD__ );
185 $db->commit( __METHOD__ );
186 } catch ( DBQueryError $e ) {
187 $this->handleWriteError( $e );
189 $values[$key] = false;
190 } else { // HIT
191 $values[$key] = $this->unserialize( $db->decodeBlob( $row->value ) );
193 } else { // MISS
194 $values[$key] = false;
195 $this->debug( 'get: no matching rows' );
199 return $values;
202 public function set( $key, $value, $exptime = 0 ) {
203 $db = $this->getDB();
204 $exptime = intval( $exptime );
206 if ( $exptime < 0 ) {
207 $exptime = 0;
210 if ( $exptime == 0 ) {
211 $encExpiry = $this->getMaxDateTime();
212 } else {
213 if ( $exptime < 3.16e8 ) { # ~10 years
214 $exptime += time();
217 $encExpiry = $db->timestamp( $exptime );
219 try {
220 $db->begin( __METHOD__ );
221 // (bug 24425) use a replace if the db supports it instead of
222 // delete/insert to avoid clashes with conflicting keynames
223 $db->replace(
224 $this->getTableByKey( $key ),
225 array( 'keyname' ),
226 array(
227 'keyname' => $key,
228 'value' => $db->encodeBlob( $this->serialize( $value ) ),
229 'exptime' => $encExpiry
230 ), __METHOD__ );
231 $db->commit( __METHOD__ );
232 } catch ( DBQueryError $e ) {
233 $this->handleWriteError( $e );
235 return false;
238 return true;
241 public function delete( $key, $time = 0 ) {
242 $db = $this->getDB();
244 try {
245 $db->begin( __METHOD__ );
246 $db->delete(
247 $this->getTableByKey( $key ),
248 array( 'keyname' => $key ),
249 __METHOD__ );
250 $db->commit( __METHOD__ );
251 } catch ( DBQueryError $e ) {
252 $this->handleWriteError( $e );
254 return false;
257 return true;
260 public function incr( $key, $step = 1 ) {
261 $db = $this->getDB();
262 $tableName = $this->getTableByKey( $key );
263 $step = intval( $step );
265 try {
266 $db->begin( __METHOD__ );
267 $row = $db->selectRow(
268 $tableName,
269 array( 'value', 'exptime' ),
270 array( 'keyname' => $key ),
271 __METHOD__,
272 array( 'FOR UPDATE' ) );
273 if ( $row === false ) {
274 // Missing
275 $db->commit( __METHOD__ );
277 return null;
279 $db->delete( $tableName, array( 'keyname' => $key ), __METHOD__ );
280 if ( $this->isExpired( $row->exptime ) ) {
281 // Expired, do not reinsert
282 $db->commit( __METHOD__ );
284 return null;
287 $oldValue = intval( $this->unserialize( $db->decodeBlob( $row->value ) ) );
288 $newValue = $oldValue + $step;
289 $db->insert( $tableName,
290 array(
291 'keyname' => $key,
292 'value' => $db->encodeBlob( $this->serialize( $newValue ) ),
293 'exptime' => $row->exptime
294 ), __METHOD__, 'IGNORE' );
296 if ( $db->affectedRows() == 0 ) {
297 // Race condition. See bug 28611
298 $newValue = null;
300 $db->commit( __METHOD__ );
301 } catch ( DBQueryError $e ) {
302 $this->handleWriteError( $e );
304 return null;
307 return $newValue;
310 public function keys() {
311 $db = $this->getDB();
312 $result = array();
314 for ( $i = 0; $i < $this->shards; $i++ ) {
315 $res = $db->select( $this->getTableByShard( $i ),
316 array( 'keyname' ), false, __METHOD__ );
317 foreach ( $res as $row ) {
318 $result[] = $row->keyname;
322 return $result;
325 protected function isExpired( $exptime ) {
326 return $exptime != $this->getMaxDateTime() && wfTimestamp( TS_UNIX, $exptime ) < time();
329 protected function getMaxDateTime() {
330 if ( time() > 0x7fffffff ) {
331 return $this->getDB()->timestamp( 1 << 62 );
332 } else {
333 return $this->getDB()->timestamp( 0x7fffffff );
337 protected function garbageCollect() {
338 if ( !$this->purgePeriod ) {
339 // Disabled
340 return;
342 // Only purge on one in every $this->purgePeriod requests.
343 if ( $this->purgePeriod !== 1 && mt_rand( 0, $this->purgePeriod - 1 ) ) {
344 return;
346 $now = time();
347 // Avoid repeating the delete within a few seconds
348 if ( $now > ( $this->lastExpireAll + 1 ) ) {
349 $this->lastExpireAll = $now;
350 $this->expireAll();
354 public function expireAll() {
355 $this->deleteObjectsExpiringBefore( wfTimestampNow() );
359 * Delete objects from the database which expire before a certain date.
360 * @return bool
362 public function deleteObjectsExpiringBefore( $timestamp, $progressCallback = false ) {
363 $db = $this->getDB();
364 $dbTimestamp = $db->timestamp( $timestamp );
365 $totalSeconds = false;
366 $baseConds = array( 'exptime < ' . $db->addQuotes( $dbTimestamp ) );
368 try {
369 for ( $i = 0; $i < $this->shards; $i++ ) {
370 $maxExpTime = false;
371 while ( true ) {
372 $conds = $baseConds;
373 if ( $maxExpTime !== false ) {
374 $conds[] = 'exptime > ' . $db->addQuotes( $maxExpTime );
376 $rows = $db->select(
377 $this->getTableByShard( $i ),
378 array( 'keyname', 'exptime' ),
379 $conds,
380 __METHOD__,
381 array( 'LIMIT' => 100, 'ORDER BY' => 'exptime' ) );
382 if ( !$rows->numRows() ) {
383 break;
385 $keys = array();
386 $row = $rows->current();
387 $minExpTime = $row->exptime;
388 if ( $totalSeconds === false ) {
389 $totalSeconds = wfTimestamp( TS_UNIX, $timestamp )
390 - wfTimestamp( TS_UNIX, $minExpTime );
392 foreach ( $rows as $row ) {
393 $keys[] = $row->keyname;
394 $maxExpTime = $row->exptime;
397 $db->begin( __METHOD__ );
398 $db->delete(
399 $this->getTableByShard( $i ),
400 array(
401 'exptime >= ' . $db->addQuotes( $minExpTime ),
402 'exptime < ' . $db->addQuotes( $dbTimestamp ),
403 'keyname' => $keys
405 __METHOD__ );
406 $db->commit( __METHOD__ );
408 if ( $progressCallback ) {
409 if ( intval( $totalSeconds ) === 0 ) {
410 $percent = 0;
411 } else {
412 $remainingSeconds = wfTimestamp( TS_UNIX, $timestamp )
413 - wfTimestamp( TS_UNIX, $maxExpTime );
414 if ( $remainingSeconds > $totalSeconds ) {
415 $totalSeconds = $remainingSeconds;
417 $percent = ( $i + $remainingSeconds / $totalSeconds )
418 / $this->shards * 100;
420 call_user_func( $progressCallback, $percent );
424 } catch ( DBQueryError $e ) {
425 $this->handleWriteError( $e );
427 return true;
430 public function deleteAll() {
431 $db = $this->getDB();
433 try {
434 for ( $i = 0; $i < $this->shards; $i++ ) {
435 $db->begin( __METHOD__ );
436 $db->delete( $this->getTableByShard( $i ), '*', __METHOD__ );
437 $db->commit( __METHOD__ );
439 } catch ( DBQueryError $e ) {
440 $this->handleWriteError( $e );
445 * Serialize an object and, if possible, compress the representation.
446 * On typical message and page data, this can provide a 3X decrease
447 * in storage requirements.
449 * @param $data mixed
450 * @return string
452 protected function serialize( &$data ) {
453 $serial = serialize( $data );
455 if ( function_exists( 'gzdeflate' ) ) {
456 return gzdeflate( $serial );
457 } else {
458 return $serial;
463 * Unserialize and, if necessary, decompress an object.
464 * @param $serial string
465 * @return mixed
467 protected function unserialize( $serial ) {
468 if ( function_exists( 'gzinflate' ) ) {
469 wfSuppressWarnings();
470 $decomp = gzinflate( $serial );
471 wfRestoreWarnings();
473 if ( false !== $decomp ) {
474 $serial = $decomp;
478 $ret = unserialize( $serial );
480 return $ret;
484 * Handle a DBQueryError which occurred during a write operation.
485 * Ignore errors which are due to a read-only database, rethrow others.
487 protected function handleWriteError( $exception ) {
488 $db = $this->getDB();
490 if ( !$db->wasReadOnlyError() ) {
491 throw $exception;
494 try {
495 $db->rollback( __METHOD__ );
496 } catch ( DBQueryError $e ) {
499 wfDebug( __METHOD__ . ": ignoring query error\n" );
500 $db->ignoreErrors( false );
504 * Create shard tables. For use from eval.php.
506 public function createTables() {
507 $db = $this->getDB();
508 if ( $db->getType() !== 'mysql'
509 || version_compare( $db->getServerVersion(), '4.1.0', '<' ) )
511 throw new MWException( __METHOD__ . ' is not supported on this DB server' );
514 for ( $i = 0; $i < $this->shards; $i++ ) {
515 $db->begin( __METHOD__ );
516 $db->query(
517 'CREATE TABLE ' . $db->tableName( $this->getTableByShard( $i ) ) .
518 ' LIKE ' . $db->tableName( 'objectcache' ),
519 __METHOD__ );
520 $db->commit( __METHOD__ );
526 * Backwards compatibility alias
528 class MediaWikiBagOStuff extends SqlBagOStuff { }