3 # Copyright (C) 2003-2004 Brion Vibber <brion@pobox.com>
4 # http://www.mediawiki.org/
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License along
17 # with this program; if not, write to the Free Software Foundation, Inc.,
18 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 # http://www.gnu.org/copyleft/gpl.html
22 * @defgroup Cache Cache
29 * interface is intended to be more or less compatible with
30 * the PHP memcached client.
32 * backends for local hash array and SQL table included:
34 * $bag = new HashBagOStuff();
35 * $bag = new MediaWikiBagOStuff($tablename); # connect to db first
43 function __construct() {
44 $this->set_debug( false );
47 function set_debug($bool) {
48 $this->debugmode
= $bool;
51 /* *** THE GUTS OF THE OPERATION *** */
52 /* Override these with functional things in subclasses */
59 function set($key, $value, $exptime=0) {
64 function delete($key, $time=0) {
69 function lock($key, $timeout = 0) {
74 function unlock($key) {
84 /* *** Emulated functions *** */
85 /* Better performance can likely be got with custom written versions */
86 function get_multi($keys) {
88 foreach($keys as $key)
89 $out[$key] = $this->get($key);
93 function set_multi($hash, $exptime=0) {
94 foreach($hash as $key => $value)
95 $this->set($key, $value, $exptime);
98 function add($key, $value, $exptime=0) {
99 if( $this->get($key) == false ) {
100 $this->set($key, $value, $exptime);
105 function add_multi($hash, $exptime=0) {
106 foreach($hash as $key => $value)
107 $this->add($key, $value, $exptime);
110 function delete_multi($keys, $time=0) {
111 foreach($keys as $key)
112 $this->delete($key, $time);
115 function replace($key, $value, $exptime=0) {
116 if( $this->get($key) !== false )
117 $this->set($key, $value, $exptime);
120 function incr($key, $value=1) {
121 if ( !$this->lock($key) ) {
124 $value = intval($value);
125 if($value < 0) $value = 0;
128 if( ($n = $this->get($key)) !== false ) {
130 $this->set($key, $n); // exptime?
136 function decr($key, $value=1) {
137 if ( !$this->lock($key) ) {
140 $value = intval($value);
141 if($value < 0) $value = 0;
144 if( ($n = $this->get($key)) !== false ) {
147 $this->set($key, $m); // exptime?
153 function _debug($text) {
155 wfDebug("BagOStuff debug: $text\n");
159 * Convert an optionally relative time to an absolute time
161 static function convertExpiry( $exptime ) {
162 if(($exptime != 0) && ($exptime < 3600*24*30)) {
163 return time() +
$exptime;
172 * Functional versions!
173 * This is a test of the interface, mainly. It stores things in an associative
174 * array, which is not going to persist between program runs.
178 class HashBagOStuff
extends BagOStuff
{
181 function __construct() {
182 $this->bag
= array();
185 function _expire($key) {
186 $et = $this->bag
[$key][1];
187 if(($et == 0) ||
($et > time()))
194 if(!$this->bag
[$key])
196 if($this->_expire($key))
198 return $this->bag
[$key][0];
201 function set($key,$value,$exptime=0) {
202 $this->bag
[$key] = array( $value, BagOStuff
::convertExpiry( $exptime ) );
205 function delete($key,$time=0) {
206 if(!$this->bag
[$key])
208 unset($this->bag
[$key]);
213 return array_keys( $this->bag
);
218 * Generic class to store objects in a database
222 abstract class SqlBagOStuff
extends BagOStuff
{
224 var $lastexpireall = 0;
229 * @param $tablename String: name of the table to use
231 function __construct($tablename = 'objectcache') {
232 $this->table
= $tablename;
236 /* expire old entries if any */
237 $this->garbageCollect();
239 $res = $this->_query(
240 "SELECT value,exptime FROM $0 WHERE keyname='$1'", $key);
242 $this->_debug("get: ** error: " . $this->_dberror($res) . " **");
245 if($row=$this->_fetchobject($res)) {
246 $this->_debug("get: retrieved data; exp time is " . $row->exptime
);
247 if ( $row->exptime
!= $this->_maxdatetime() &&
248 wfTimestamp( TS_UNIX
, $row->exptime
) < time() )
250 $this->_debug("get: key has expired, deleting");
254 return $this->_unserialize($this->_blobdecode($row->value
));
256 $this->_debug('get: no matching rows');
261 function set($key,$value,$exptime=0) {
262 if ( $this->_readonly() ) {
265 $exptime = intval($exptime);
266 if($exptime < 0) $exptime = 0;
268 $exp = $this->_maxdatetime();
270 if($exptime < 3.16e8
) # ~10 years
272 $exp = $this->_fromunixtime($exptime);
274 $this->delete( $key );
275 $this->_doinsert($this->getTableName(), array(
277 'value' => $this->_blobencode($this->_serialize($value)),
283 function delete($key,$time=0) {
284 if ( $this->_readonly() ) {
288 "DELETE FROM $0 WHERE keyname='$1'", $key );
293 $res = $this->_query( "SELECT keyname FROM $0" );
295 $this->_debug("keys: ** error: " . $this->_dberror($res) . " **");
299 while( $row = $this->_fetchobject($res) ) {
300 $result[] = $row->keyname
;
305 function getTableName() {
309 function _query($sql) {
310 $reps = func_get_args();
311 $reps[0] = $this->getTableName();
313 for($i=0;$i<count($reps);$i++
) {
316 $i > 0 ?
$this->_strencode($reps[$i]) : $reps[$i],
319 $res = $this->_doquery($sql);
321 $this->_debug('query failed: ' . $this->_dberror($res));
326 function _strencode($str) {
327 /* Protect strings in SQL */
328 return str_replace( "'", "''", $str );
330 function _blobencode($str) {
333 function _blobdecode($str) {
337 abstract function _doinsert($table, $vals);
338 abstract function _doquery($sql);
340 abstract function _readonly();
342 function _freeresult($result) {
347 function _dberror($result) {
349 return 'unknown error';
352 abstract function _maxdatetime();
353 abstract function _fromunixtime($ts);
355 function garbageCollect() {
356 /* Ignore 99% of requests */
357 if ( !mt_rand( 0, 100 ) ) {
359 /* Avoid repeating the delete within a few seconds */
360 if ( $nowtime > ($this->lastexpireall +
1) ) {
361 $this->lastexpireall
= $nowtime;
367 function expireall() {
368 /* Remove any items that have expired */
369 if ( $this->_readonly() ) {
372 $now = $this->_fromunixtime( time() );
373 $this->_query( "DELETE FROM $0 WHERE exptime < '$now'" );
376 function deleteall() {
377 /* Clear *all* items from cache table */
378 if ( $this->_readonly() ) {
381 $this->_query( "DELETE FROM $0" );
385 * Serialize an object and, if possible, compress the representation.
386 * On typical message and page data, this can provide a 3X decrease
387 * in storage requirements.
392 function _serialize( &$data ) {
393 $serial = serialize( $data );
394 if( function_exists( 'gzdeflate' ) ) {
395 return gzdeflate( $serial );
402 * Unserialize and, if necessary, decompress an object.
403 * @param $serial string
406 function _unserialize( $serial ) {
407 if( function_exists( 'gzinflate' ) ) {
408 $decomp = @gzinflate
( $serial );
409 if( false !== $decomp ) {
413 $ret = unserialize( $serial );
419 * Stores objects in the main database of the wiki
423 class MediaWikiBagOStuff
extends SqlBagOStuff
{
424 var $tableInitialised = false;
429 $db = wfGetDB( DB_MASTER
);
432 function _doquery($sql) {
433 return $this->_getDB()->query( $sql, __METHOD__
);
435 function _doinsert($t, $v) {
436 return $this->_getDB()->insert($t, $v, __METHOD__
, array( 'IGNORE' ) );
438 function _fetchobject($result) {
439 return $this->_getDB()->fetchObject($result);
441 function _freeresult($result) {
442 return $this->_getDB()->freeResult($result);
444 function _dberror($result) {
445 return $this->_getDB()->lastError();
447 function _maxdatetime() {
448 if ( time() > 0x7fffffff ) {
449 return $this->_fromunixtime( 1<<62 );
451 return $this->_fromunixtime( 0x7fffffff );
454 function _fromunixtime($ts) {
455 return $this->_getDB()->timestamp($ts);
457 function _readonly(){
460 function _strencode($s) {
461 return $this->_getDB()->strencode($s);
463 function _blobencode($s) {
464 return $this->_getDB()->encodeBlob($s);
466 function _blobdecode($s) {
467 return $this->_getDB()->decodeBlob($s);
469 function getTableName() {
470 if ( !$this->tableInitialised
) {
471 $dbw = $this->_getDB();
472 /* This is actually a hack, we should be able
473 to use Language classes here... or not */
475 throw new MWException("Could not connect to database");
476 $this->table
= $dbw->tableName( $this->table
);
477 $this->tableInitialised
= true;
484 * This is a wrapper for Turck MMCache's shared memory functions.
486 * You can store objects with mmcache_put() and mmcache_get(), but Turck seems
487 * to use a weird custom serializer that randomly segfaults. So we wrap calls
488 * with serialize()/unserialize().
490 * The thing I noticed about the Turck serialized data was that unlike ordinary
491 * serialize(), it contained the names of methods, and judging by the amount of
492 * binary data, perhaps even the bytecode of the methods themselves. It may be
493 * that Turck's serializer is faster, so a possible future extension would be
494 * to use it for arrays but not for objects.
498 class TurckBagOStuff
extends BagOStuff
{
500 $val = mmcache_get( $key );
501 if ( is_string( $val ) ) {
502 $val = unserialize( $val );
507 function set($key, $value, $exptime=0) {
508 mmcache_put( $key, serialize( $value ), $exptime );
512 function delete($key, $time=0) {
517 function lock($key, $waitTimeout = 0 ) {
518 mmcache_lock( $key );
522 function unlock($key) {
523 mmcache_unlock( $key );
529 * This is a wrapper for APC's shared memory functions
533 class APCBagOStuff
extends BagOStuff
{
535 $val = apc_fetch($key);
536 if ( is_string( $val ) ) {
537 $val = unserialize( $val );
542 function set($key, $value, $exptime=0) {
543 apc_store($key, serialize($value), $exptime);
547 function delete($key, $time=0) {
555 * This is a wrapper for eAccelerator's shared memory functions.
557 * This is basically identical to the Turck MMCache version,
558 * mostly because eAccelerator is based on Turck MMCache.
562 class eAccelBagOStuff
extends BagOStuff
{
564 $val = eaccelerator_get( $key );
565 if ( is_string( $val ) ) {
566 $val = unserialize( $val );
571 function set($key, $value, $exptime=0) {
572 eaccelerator_put( $key, serialize( $value ), $exptime );
576 function delete($key, $time=0) {
577 eaccelerator_rm( $key );
581 function lock($key, $waitTimeout = 0 ) {
582 eaccelerator_lock( $key );
586 function unlock($key) {
587 eaccelerator_unlock( $key );
593 * Wrapper for XCache object caching functions; identical interface
598 class XCacheBagOStuff
extends BagOStuff
{
601 * Get a value from the XCache object cache
603 * @param $key String: cache key
606 public function get( $key ) {
607 $val = xcache_get( $key );
608 if( is_string( $val ) )
609 $val = unserialize( $val );
614 * Store a value in the XCache object cache
616 * @param $key String: cache key
617 * @param $value Mixed: object to store
618 * @param $expire Int: expiration time
621 public function set( $key, $value, $expire = 0 ) {
622 xcache_set( $key, serialize( $value ), $expire );
627 * Remove a value from the XCache object cache
629 * @param $key String: cache key
630 * @param $time Int: not used in this implementation
633 public function delete( $key, $time = 0 ) {
634 xcache_unset( $key );
644 class DBABagOStuff
extends BagOStuff
{
645 var $mHandler, $mFile, $mReader, $mWriter, $mDisabled;
647 function __construct( $handler = 'db3', $dir = false ) {
648 if ( $dir === false ) {
649 global $wgTmpDirectory;
650 $dir = $wgTmpDirectory;
652 $this->mFile
= "$dir/mw-cache-" . wfWikiID();
653 $this->mFile
.= '.db';
654 wfDebug( __CLASS__
.": using cache file {$this->mFile}\n" );
655 $this->mHandler
= $handler;
659 * Encode value and expiry for storage
661 function encode( $value, $expiry ) {
662 # Convert to absolute time
663 $expiry = BagOStuff
::convertExpiry( $expiry );
664 return sprintf( '%010u', intval( $expiry ) ) . ' ' . serialize( $value );
668 * @return list containing value first and expiry second
670 function decode( $blob ) {
671 if ( !is_string( $blob ) ) {
672 return array( null, 0 );
675 unserialize( substr( $blob, 11 ) ),
676 intval( substr( $blob, 0, 10 ) )
681 function getReader() {
682 if ( file_exists( $this->mFile
) ) {
683 $handle = dba_open( $this->mFile
, 'rl', $this->mHandler
);
685 $handle = $this->getWriter();
688 wfDebug( "Unable to open DBA cache file {$this->mFile}\n" );
693 function getWriter() {
694 $handle = dba_open( $this->mFile
, 'cl', $this->mHandler
);
696 wfDebug( "Unable to open DBA cache file {$this->mFile}\n" );
701 function get( $key ) {
702 wfProfileIn( __METHOD__
);
703 wfDebug( __METHOD__
."($key)\n" );
704 $handle = $this->getReader();
708 $val = dba_fetch( $key, $handle );
709 list( $val, $expiry ) = $this->decode( $val );
710 # Must close ASAP because locks are held
711 dba_close( $handle );
713 if ( !is_null( $val ) && $expiry && $expiry < time() ) {
714 # Key is expired, delete it
715 $handle = $this->getWriter();
716 dba_delete( $key, $handle );
717 dba_close( $handle );
718 wfDebug( __METHOD__
.": $key expired\n" );
721 wfProfileOut( __METHOD__
);
725 function set( $key, $value, $exptime=0 ) {
726 wfProfileIn( __METHOD__
);
727 wfDebug( __METHOD__
."($key)\n" );
728 $blob = $this->encode( $value, $exptime );
729 $handle = $this->getWriter();
733 $ret = dba_replace( $key, $blob, $handle );
734 dba_close( $handle );
735 wfProfileOut( __METHOD__
);
739 function delete( $key, $time = 0 ) {
740 wfProfileIn( __METHOD__
);
741 wfDebug( __METHOD__
."($key)\n" );
742 $handle = $this->getWriter();
746 $ret = dba_delete( $key, $handle );
747 dba_close( $handle );
748 wfProfileOut( __METHOD__
);
752 function add( $key, $value, $exptime = 0 ) {
753 wfProfileIn( __METHOD__
);
754 $blob = $this->encode( $value, $exptime );
755 $handle = $this->getWriter();
759 $ret = dba_insert( $key, $blob, $handle );
760 # Insert failed, check to see if it failed due to an expired key
762 list( $value, $expiry ) = $this->decode( dba_fetch( $key, $handle ) );
763 if ( $expiry < time() ) {
764 # Yes expired, delete and try again
765 dba_delete( $key, $handle );
766 $ret = dba_insert( $key, $blob, $handle );
767 # This time if it failed then it will be handled by the caller like any other race
771 dba_close( $handle );
772 wfProfileOut( __METHOD__
);
777 $reader = $this->getReader();
778 $k1 = dba_firstkey( $reader );
783 while( $key = dba_nextkey( $reader ) ) {