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
25 * Simple generic object store
27 * interface is intended to be more or less compatible with
28 * the PHP memcached client.
30 * backends for local hash array and SQL table included:
32 * $bag = new HashBagOStuff();
33 * $bag = new MediaWikiBagOStuff($tablename); # connect to db first
41 function __construct() {
42 $this->set_debug( false );
45 function set_debug($bool) {
46 $this->debugmode
= $bool;
49 /* *** THE GUTS OF THE OPERATION *** */
50 /* Override these with functional things in subclasses */
57 function set($key, $value, $exptime=0) {
62 function delete($key, $time=0) {
67 function lock($key, $timeout = 0) {
72 function unlock($key) {
82 /* *** Emulated functions *** */
83 /* Better performance can likely be got with custom written versions */
84 function get_multi($keys) {
86 foreach($keys as $key)
87 $out[$key] = $this->get($key);
91 function set_multi($hash, $exptime=0) {
92 foreach($hash as $key => $value)
93 $this->set($key, $value, $exptime);
96 function add($key, $value, $exptime=0) {
97 if( $this->get($key) == false ) {
98 $this->set($key, $value, $exptime);
103 function add_multi($hash, $exptime=0) {
104 foreach($hash as $key => $value)
105 $this->add($key, $value, $exptime);
108 function delete_multi($keys, $time=0) {
109 foreach($keys as $key)
110 $this->delete($key, $time);
113 function replace($key, $value, $exptime=0) {
114 if( $this->get($key) !== false )
115 $this->set($key, $value, $exptime);
118 function incr($key, $value=1) {
119 if ( !$this->lock($key) ) {
122 $value = intval($value);
123 if($value < 0) $value = 0;
126 if( ($n = $this->get($key)) !== false ) {
128 $this->set($key, $n); // exptime?
134 function decr($key, $value=1) {
135 if ( !$this->lock($key) ) {
138 $value = intval($value);
139 if($value < 0) $value = 0;
142 if( ($n = $this->get($key)) !== false ) {
145 $this->set($key, $m); // exptime?
151 function _debug($text) {
153 wfDebug("BagOStuff debug: $text\n");
157 * Convert an optionally relative time to an absolute time
159 static function convertExpiry( $exptime ) {
160 if(($exptime != 0) && ($exptime < 3600*24*30)) {
161 return time() +
$exptime;
170 * Functional versions!
171 * This is a test of the interface, mainly. It stores things in an associative
172 * array, which is not going to persist between program runs.
176 class HashBagOStuff
extends BagOStuff
{
179 function __construct() {
180 $this->bag
= array();
183 function _expire($key) {
184 $et = $this->bag
[$key][1];
185 if(($et == 0) ||
($et > time()))
192 if(!$this->bag
[$key])
194 if($this->_expire($key))
196 return $this->bag
[$key][0];
199 function set($key,$value,$exptime=0) {
200 $this->bag
[$key] = array( $value, BagOStuff
::convertExpiry( $exptime ) );
203 function delete($key,$time=0) {
204 if(!$this->bag
[$key])
206 unset($this->bag
[$key]);
211 return array_keys( $this->bag
);
216 * Generic class to store objects in a database
220 abstract class SqlBagOStuff
extends BagOStuff
{
222 var $lastexpireall = 0;
227 * @param string $tablename name of the table to use
229 function __construct($tablename = 'objectcache') {
230 $this->table
= $tablename;
234 /* expire old entries if any */
235 $this->garbageCollect();
237 $res = $this->_query(
238 "SELECT value,exptime FROM $0 WHERE keyname='$1'", $key);
240 $this->_debug("get: ** error: " . $this->_dberror($res) . " **");
243 if($row=$this->_fetchobject($res)) {
244 $this->_debug("get: retrieved data; exp time is " . $row->exptime
);
245 if ( $row->exptime
!= $this->_maxdatetime() &&
246 wfTimestamp( TS_UNIX
, $row->exptime
) < time() )
248 $this->_debug("get: key has expired, deleting");
252 return $this->_unserialize($this->_blobdecode($row->value
));
254 $this->_debug('get: no matching rows');
259 function set($key,$value,$exptime=0) {
260 if ( $this->_readonly() ) {
263 $exptime = intval($exptime);
264 if($exptime < 0) $exptime = 0;
266 $exp = $this->_maxdatetime();
268 if($exptime < 3.16e8
) # ~10 years
270 $exp = $this->_fromunixtime($exptime);
272 $this->delete( $key );
273 $this->_doinsert($this->getTableName(), array(
275 'value' => $this->_blobencode($this->_serialize($value)),
281 function delete($key,$time=0) {
282 if ( $this->_readonly() ) {
286 "DELETE FROM $0 WHERE keyname='$1'", $key );
291 $res = $this->_query( "SELECT keyname FROM $0" );
293 $this->_debug("keys: ** error: " . $this->_dberror($res) . " **");
297 while( $row = $this->_fetchobject($res) ) {
298 $result[] = $row->keyname
;
303 function getTableName() {
307 function _query($sql) {
308 $reps = func_get_args();
309 $reps[0] = $this->getTableName();
311 for($i=0;$i<count($reps);$i++
) {
314 $i > 0 ?
$this->_strencode($reps[$i]) : $reps[$i],
317 $res = $this->_doquery($sql);
319 $this->_debug('query failed: ' . $this->_dberror($res));
324 function _strencode($str) {
325 /* Protect strings in SQL */
326 return str_replace( "'", "''", $str );
328 function _blobencode($str) {
331 function _blobdecode($str) {
335 abstract function _doinsert($table, $vals);
336 abstract function _doquery($sql);
338 abstract function _readonly();
340 function _freeresult($result) {
345 function _dberror($result) {
347 return 'unknown error';
350 abstract function _maxdatetime();
351 abstract function _fromunixtime($ts);
353 function garbageCollect() {
354 /* Ignore 99% of requests */
355 if ( !mt_rand( 0, 100 ) ) {
357 /* Avoid repeating the delete within a few seconds */
358 if ( $nowtime > ($this->lastexpireall +
1) ) {
359 $this->lastexpireall
= $nowtime;
365 function expireall() {
366 /* Remove any items that have expired */
367 if ( $this->_readonly() ) {
370 $now = $this->_fromunixtime( time() );
371 $this->_query( "DELETE FROM $0 WHERE exptime < '$now'" );
374 function deleteall() {
375 /* Clear *all* items from cache table */
376 if ( $this->_readonly() ) {
379 $this->_query( "DELETE FROM $0" );
383 * Serialize an object and, if possible, compress the representation.
384 * On typical message and page data, this can provide a 3X decrease
385 * in storage requirements.
390 function _serialize( &$data ) {
391 $serial = serialize( $data );
392 if( function_exists( 'gzdeflate' ) ) {
393 return gzdeflate( $serial );
400 * Unserialize and, if necessary, decompress an object.
401 * @param string $serial
404 function _unserialize( $serial ) {
405 if( function_exists( 'gzinflate' ) ) {
406 $decomp = @gzinflate
( $serial );
407 if( false !== $decomp ) {
411 $ret = unserialize( $serial );
417 * Stores objects in the main database of the wiki
421 class MediaWikiBagOStuff
extends SqlBagOStuff
{
422 var $tableInitialised = false;
427 $db = wfGetDB( DB_MASTER
);
430 function _doquery($sql) {
431 return $this->_getDB()->query( $sql, __METHOD__
);
433 function _doinsert($t, $v) {
434 return $this->_getDB()->insert($t, $v, __METHOD__
, array( 'IGNORE' ) );
436 function _fetchobject($result) {
437 return $this->_getDB()->fetchObject($result);
439 function _freeresult($result) {
440 return $this->_getDB()->freeResult($result);
442 function _dberror($result) {
443 return $this->_getDB()->lastError();
445 function _maxdatetime() {
446 if ( time() > 0x7fffffff ) {
447 return $this->_fromunixtime( 1<<62 );
449 return $this->_fromunixtime( 0x7fffffff );
452 function _fromunixtime($ts) {
453 return $this->_getDB()->timestamp($ts);
455 function _readonly(){
458 function _strencode($s) {
459 return $this->_getDB()->strencode($s);
461 function _blobencode($s) {
462 return $this->_getDB()->encodeBlob($s);
464 function _blobdecode($s) {
465 return $this->_getDB()->decodeBlob($s);
467 function getTableName() {
468 if ( !$this->tableInitialised
) {
469 $dbw = $this->_getDB();
470 /* This is actually a hack, we should be able
471 to use Language classes here... or not */
473 throw new MWException("Could not connect to database");
474 $this->table
= $dbw->tableName( $this->table
);
475 $this->tableInitialised
= true;
482 * This is a wrapper for Turck MMCache's shared memory functions.
484 * You can store objects with mmcache_put() and mmcache_get(), but Turck seems
485 * to use a weird custom serializer that randomly segfaults. So we wrap calls
486 * with serialize()/unserialize().
488 * The thing I noticed about the Turck serialized data was that unlike ordinary
489 * serialize(), it contained the names of methods, and judging by the amount of
490 * binary data, perhaps even the bytecode of the methods themselves. It may be
491 * that Turck's serializer is faster, so a possible future extension would be
492 * to use it for arrays but not for objects.
496 class TurckBagOStuff
extends BagOStuff
{
498 $val = mmcache_get( $key );
499 if ( is_string( $val ) ) {
500 $val = unserialize( $val );
505 function set($key, $value, $exptime=0) {
506 mmcache_put( $key, serialize( $value ), $exptime );
510 function delete($key, $time=0) {
515 function lock($key, $waitTimeout = 0 ) {
516 mmcache_lock( $key );
520 function unlock($key) {
521 mmcache_unlock( $key );
527 * This is a wrapper for APC's shared memory functions
531 class APCBagOStuff
extends BagOStuff
{
533 $val = apc_fetch($key);
534 if ( is_string( $val ) ) {
535 $val = unserialize( $val );
540 function set($key, $value, $exptime=0) {
541 apc_store($key, serialize($value), $exptime);
545 function delete($key, $time=0) {
553 * This is a wrapper for eAccelerator's shared memory functions.
555 * This is basically identical to the Turck MMCache version,
556 * mostly because eAccelerator is based on Turck MMCache.
560 class eAccelBagOStuff
extends BagOStuff
{
562 $val = eaccelerator_get( $key );
563 if ( is_string( $val ) ) {
564 $val = unserialize( $val );
569 function set($key, $value, $exptime=0) {
570 eaccelerator_put( $key, serialize( $value ), $exptime );
574 function delete($key, $time=0) {
575 eaccelerator_rm( $key );
579 function lock($key, $waitTimeout = 0 ) {
580 eaccelerator_lock( $key );
584 function unlock($key) {
585 eaccelerator_unlock( $key );
591 * Wrapper for XCache object caching functions; identical interface
596 class XCacheBagOStuff
extends BagOStuff
{
599 * Get a value from the XCache object cache
601 * @param string $key Cache key
604 public function get( $key ) {
605 $val = xcache_get( $key );
606 if( is_string( $val ) )
607 $val = unserialize( $val );
612 * Store a value in the XCache object cache
614 * @param string $key Cache key
615 * @param mixed $value Object to store
616 * @param int $expire Expiration time
619 public function set( $key, $value, $expire = 0 ) {
620 xcache_set( $key, serialize( $value ), $expire );
625 * Remove a value from the XCache object cache
627 * @param string $key Cache key
628 * @param int $time Not used in this implementation
631 public function delete( $key, $time = 0 ) {
632 xcache_unset( $key );
642 class DBABagOStuff
extends BagOStuff
{
643 var $mHandler, $mFile, $mReader, $mWriter, $mDisabled;
645 function __construct( $handler = 'db3', $dir = false ) {
646 if ( $dir === false ) {
647 global $wgTmpDirectory;
648 $dir = $wgTmpDirectory;
650 $this->mFile
= "$dir/mw-cache-" . wfWikiID();
651 $this->mFile
.= '.db';
652 wfDebug( __CLASS__
.": using cache file {$this->mFile}\n" );
653 $this->mHandler
= $handler;
657 * Encode value and expiry for storage
659 function encode( $value, $expiry ) {
660 # Convert to absolute time
661 $expiry = BagOStuff
::convertExpiry( $expiry );
662 return sprintf( '%010u', intval( $expiry ) ) . ' ' . serialize( $value );
666 * @return list containing value first and expiry second
668 function decode( $blob ) {
669 if ( !is_string( $blob ) ) {
670 return array( null, 0 );
673 unserialize( substr( $blob, 11 ) ),
674 intval( substr( $blob, 0, 10 ) )
679 function getReader() {
680 if ( file_exists( $this->mFile
) ) {
681 $handle = dba_open( $this->mFile
, 'rl', $this->mHandler
);
683 $handle = $this->getWriter();
686 wfDebug( "Unable to open DBA cache file {$this->mFile}\n" );
691 function getWriter() {
692 $handle = dba_open( $this->mFile
, 'cl', $this->mHandler
);
694 wfDebug( "Unable to open DBA cache file {$this->mFile}\n" );
699 function get( $key ) {
700 wfProfileIn( __METHOD__
);
701 wfDebug( __METHOD__
."($key)\n" );
702 $handle = $this->getReader();
706 $val = dba_fetch( $key, $handle );
707 list( $val, $expiry ) = $this->decode( $val );
708 # Must close ASAP because locks are held
709 dba_close( $handle );
711 if ( !is_null( $val ) && $expiry && $expiry < time() ) {
712 # Key is expired, delete it
713 $handle = $this->getWriter();
714 dba_delete( $key, $handle );
715 dba_close( $handle );
716 wfDebug( __METHOD__
.": $key expired\n" );
719 wfProfileOut( __METHOD__
);
723 function set( $key, $value, $exptime=0 ) {
724 wfProfileIn( __METHOD__
);
725 wfDebug( __METHOD__
."($key)\n" );
726 $blob = $this->encode( $value, $exptime );
727 $handle = $this->getWriter();
731 $ret = dba_replace( $key, $blob, $handle );
732 dba_close( $handle );
733 wfProfileOut( __METHOD__
);
737 function delete( $key, $time = 0 ) {
738 wfProfileIn( __METHOD__
);
739 wfDebug( __METHOD__
."($key)\n" );
740 $handle = $this->getWriter();
744 $ret = dba_delete( $key, $handle );
745 dba_close( $handle );
746 wfProfileOut( __METHOD__
);
750 function add( $key, $value, $exptime = 0 ) {
751 wfProfileIn( __METHOD__
);
752 $blob = $this->encode( $value, $exptime );
753 $handle = $this->getWriter();
757 $ret = dba_insert( $key, $blob, $handle );
758 # Insert failed, check to see if it failed due to an expired key
760 list( $value, $expiry ) = $this->decode( dba_fetch( $key, $handle ) );
761 if ( $expiry < time() ) {
762 # Yes expired, delete and try again
763 dba_delete( $key, $handle );
764 $ret = dba_insert( $key, $blob, $handle );
765 # This time if it failed then it will be handled by the caller like any other race
769 dba_close( $handle );
770 wfProfileOut( __METHOD__
);
775 $reader = $this->getReader();
776 $k1 = dba_firstkey( $reader );
781 while( $key = dba_nextkey( $reader ) ) {