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 SqlBagOStuff(); # connect to db first
40 abstract class BagOStuff
{
41 var $debugMode = false;
43 public function set_debug( $bool ) {
44 $this->debugMode
= $bool;
47 /* *** THE GUTS OF THE OPERATION *** */
48 /* Override these with functional things in subclasses */
51 * Get an item with the given key. Returns false if it does not exist.
54 abstract public function get( $key );
60 * @param $exptime int Either an interval in seconds or a unix timestamp for expiry
62 abstract public function set( $key, $value, $exptime = 0 );
67 * @param $time int Amount of time to delay the operation (mostly memcached-specific)
69 abstract public function delete( $key, $time = 0 );
71 public function lock( $key, $timeout = 0 ) {
76 public function unlock( $key ) {
81 public function keys() {
86 /* *** Emulated functions *** */
87 /* Better performance can likely be got with custom written versions */
88 public function get_multi( $keys ) {
91 foreach ( $keys as $key ) {
92 $out[$key] = $this->get( $key );
98 public function set_multi( $hash, $exptime = 0 ) {
99 foreach ( $hash as $key => $value ) {
100 $this->set( $key, $value, $exptime );
104 public function add( $key, $value, $exptime = 0 ) {
105 if ( !$this->get( $key ) ) {
106 $this->set( $key, $value, $exptime );
112 public function add_multi( $hash, $exptime = 0 ) {
113 foreach ( $hash as $key => $value ) {
114 $this->add( $key, $value, $exptime );
118 public function delete_multi( $keys, $time = 0 ) {
119 foreach ( $keys as $key ) {
120 $this->delete( $key, $time );
124 public function replace( $key, $value, $exptime = 0 ) {
125 if ( $this->get( $key ) !== false ) {
126 $this->set( $key, $value, $exptime );
130 public function incr( $key, $value = 1 ) {
131 if ( !$this->lock( $key ) ) {
135 $value = intval( $value );
138 if ( ( $n = $this->get( $key ) ) !== false ) {
140 $this->set( $key, $n ); // exptime?
142 $this->unlock( $key );
147 public function decr( $key, $value = 1 ) {
148 return $this->incr( $key, - $value );
151 public function debug( $text ) {
152 if ( $this->debugMode
) {
153 wfDebug( "BagOStuff debug: $text\n" );
158 * Convert an optionally relative time to an absolute time
160 protected function convertExpiry( $exptime ) {
161 if ( ( $exptime != 0 ) && ( $exptime < 86400 * 3650 /* 10 years */ ) ) {
162 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 protected function expire( $key ) {
184 $et = $this->bag
[$key][1];
186 if ( ( $et == 0 ) ||
( $et > time() ) ) {
190 $this->delete( $key );
195 function get( $key ) {
196 if ( !isset( $this->bag
[$key] ) ) {
200 if ( $this->expire( $key ) ) {
204 return $this->bag
[$key][0];
207 function set( $key, $value, $exptime = 0 ) {
208 $this->bag
[$key] = array( $value, $this->convertExpiry( $exptime ) );
211 function delete( $key, $time = 0 ) {
212 if ( !isset( $this->bag
[$key] ) ) {
216 unset( $this->bag
[$key] );
222 return array_keys( $this->bag
);
227 * Class to store objects in the database
231 class SqlBagOStuff
extends BagOStuff
{
233 var $lastExpireAll = 0;
235 protected function getDB() {
238 if ( !isset( $this->db
) ) {
239 /* We must keep a separate connection to MySQL in order to avoid deadlocks
240 * However, SQLite has an opposite behaviour.
241 * @todo Investigate behaviour for other databases
243 if ( $wgDBtype == 'sqlite' ) {
244 $this->db
= wfGetDB( DB_MASTER
);
246 $this->lb
= wfGetLBFactory()->newMainLB();
247 $this->db
= $this->lb
->getConnection( DB_MASTER
);
248 $this->db
->clearFlag( DBO_TRX
);
255 public function get( $key ) {
256 # expire old entries if any
257 $this->garbageCollect();
258 $db = $this->getDB();
259 $row = $db->selectRow( 'objectcache', array( 'value', 'exptime' ),
260 array( 'keyname' => $key ), __METHOD__
);
263 $this->debug( 'get: no matching rows' );
267 $this->debug( "get: retrieved data; expiry time is " . $row->exptime
);
269 if ( $this->isExpired( $row->exptime
) ) {
270 $this->debug( "get: key has expired, deleting" );
273 # Put the expiry time in the WHERE condition to avoid deleting a
274 # newly-inserted value
275 $db->delete( 'objectcache',
278 'exptime' => $row->exptime
281 } catch ( DBQueryError
$e ) {
282 $this->handleWriteError( $e );
288 return $this->unserialize( $db->decodeBlob( $row->value
) );
291 public function set( $key, $value, $exptime = 0 ) {
292 $db = $this->getDB();
293 $exptime = intval( $exptime );
295 if ( $exptime < 0 ) {
299 if ( $exptime == 0 ) {
300 $encExpiry = $this->getMaxDateTime();
302 if ( $exptime < 3.16e8
) { # ~10 years
306 $encExpiry = $db->timestamp( $exptime );
310 // (bug 24425) use a replace if the db supports it instead of
311 // delete/insert to avoid clashes with conflicting keynames
312 $db->replace( 'objectcache', array( 'keyname' ),
315 'value' => $db->encodeBlob( $this->serialize( $value ) ),
316 'exptime' => $encExpiry
319 } catch ( DBQueryError
$e ) {
320 $this->handleWriteError( $e );
328 public function delete( $key, $time = 0 ) {
329 $db = $this->getDB();
333 $db->delete( 'objectcache', array( 'keyname' => $key ), __METHOD__
);
335 } catch ( DBQueryError
$e ) {
336 $this->handleWriteError( $e );
344 public function incr( $key, $step = 1 ) {
345 $db = $this->getDB();
346 $step = intval( $step );
350 $row = $db->selectRow( 'objectcache', array( 'value', 'exptime' ),
351 array( 'keyname' => $key ), __METHOD__
, array( 'FOR UPDATE' ) );
352 if ( $row === false ) {
358 $db->delete( 'objectcache', array( 'keyname' => $key ), __METHOD__
);
359 if ( $this->isExpired( $row->exptime
) ) {
360 // Expired, do not reinsert
366 $oldValue = intval( $this->unserialize( $db->decodeBlob( $row->value
) ) );
367 $newValue = $oldValue +
$step;
368 $db->insert( 'objectcache',
371 'value' => $db->encodeBlob( $this->serialize( $newValue ) ),
372 'exptime' => $row->exptime
375 } catch ( DBQueryError
$e ) {
376 $this->handleWriteError( $e );
384 public function keys() {
385 $db = $this->getDB();
386 $res = $db->select( 'objectcache', array( 'keyname' ), false, __METHOD__
);
389 foreach ( $res as $row ) {
390 $result[] = $row->keyname
;
396 protected function isExpired( $exptime ) {
397 return $exptime != $this->getMaxDateTime() && wfTimestamp( TS_UNIX
, $exptime ) < time();
400 protected function getMaxDateTime() {
401 if ( time() > 0x7fffffff ) {
402 return $this->getDB()->timestamp( 1 << 62 );
404 return $this->getDB()->timestamp( 0x7fffffff );
408 protected function garbageCollect() {
409 /* Ignore 99% of requests */
410 if ( !mt_rand( 0, 100 ) ) {
412 /* Avoid repeating the delete within a few seconds */
413 if ( $now > ( $this->lastExpireAll +
1 ) ) {
414 $this->lastExpireAll
= $now;
420 public function expireAll() {
421 $db = $this->getDB();
422 $now = $db->timestamp();
426 $db->delete( 'objectcache', array( 'exptime < ' . $db->addQuotes( $now ) ), __METHOD__
);
428 } catch ( DBQueryError
$e ) {
429 $this->handleWriteError( $e );
433 public function deleteAll() {
434 $db = $this->getDB();
438 $db->delete( 'objectcache', '*', __METHOD__
);
440 } catch ( DBQueryError
$e ) {
441 $this->handleWriteError( $e );
446 * Serialize an object and, if possible, compress the representation.
447 * On typical message and page data, this can provide a 3X decrease
448 * in storage requirements.
453 protected function serialize( &$data ) {
454 $serial = serialize( $data );
456 if ( function_exists( 'gzdeflate' ) ) {
457 return gzdeflate( $serial );
464 * Unserialize and, if necessary, decompress an object.
465 * @param $serial string
468 protected function unserialize( $serial ) {
469 if ( function_exists( 'gzinflate' ) ) {
470 $decomp = @gzinflate
( $serial );
472 if ( false !== $decomp ) {
477 $ret = unserialize( $serial );
483 * Handle a DBQueryError which occurred during a write operation.
484 * Ignore errors which are due to a read-only database, rethrow others.
486 protected function handleWriteError( $exception ) {
487 $db = $this->getDB();
489 if ( !$db->wasReadOnlyError() ) {
495 } catch ( DBQueryError
$e ) {
498 wfDebug( __METHOD__
. ": ignoring query error\n" );
499 $db->ignoreErrors( false );
504 * Backwards compatibility alias
506 class MediaWikiBagOStuff
extends SqlBagOStuff
{ }
509 * This is a wrapper for APC's shared memory functions
513 class APCBagOStuff
extends BagOStuff
{
514 public function get( $key ) {
515 $val = apc_fetch( $key );
517 if ( is_string( $val ) ) {
518 $val = unserialize( $val );
524 public function set( $key, $value, $exptime = 0 ) {
525 apc_store( $key, serialize( $value ), $exptime );
530 public function delete( $key, $time = 0 ) {
536 public function keys() {
537 $info = apc_cache_info( 'user' );
538 $list = $info['cache_list'];
541 foreach ( $list as $entry ) {
542 $keys[] = $entry['info'];
550 * This is a wrapper for eAccelerator's shared memory functions.
552 * This is basically identical to the deceased Turck MMCache version,
553 * mostly because eAccelerator is based on Turck MMCache.
557 class eAccelBagOStuff
extends BagOStuff
{
558 public function get( $key ) {
559 $val = eaccelerator_get( $key );
561 if ( is_string( $val ) ) {
562 $val = unserialize( $val );
568 public function set( $key, $value, $exptime = 0 ) {
569 eaccelerator_put( $key, serialize( $value ), $exptime );
574 public function delete( $key, $time = 0 ) {
575 eaccelerator_rm( $key );
580 public function lock( $key, $waitTimeout = 0 ) {
581 eaccelerator_lock( $key );
586 public function unlock( $key ) {
587 eaccelerator_unlock( $key );
594 * Wrapper for XCache object caching functions; identical interface
599 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 );
609 if ( is_string( $val ) ) {
610 $val = unserialize( $val );
617 * Store a value in the XCache object cache
619 * @param $key String: cache key
620 * @param $value Mixed: object to store
621 * @param $expire Int: expiration time
624 public function set( $key, $value, $expire = 0 ) {
625 xcache_set( $key, serialize( $value ), $expire );
631 * Remove a value from the XCache object cache
633 * @param $key String: cache key
634 * @param $time Int: not used in this implementation
637 public function delete( $key, $time = 0 ) {
638 xcache_unset( $key );
645 * Cache that uses DBA as a backend.
646 * Slow due to the need to constantly open and close the file to avoid holding
647 * writer locks. Intended for development use only, as a memcached workalike
648 * for systems that don't have it.
652 class DBABagOStuff
extends BagOStuff
{
653 var $mHandler, $mFile, $mReader, $mWriter, $mDisabled;
655 public function __construct( $dir = false ) {
656 global $wgDBAhandler;
658 if ( $dir === false ) {
659 global $wgTmpDirectory;
660 $dir = $wgTmpDirectory;
663 $this->mFile
= "$dir/mw-cache-" . wfWikiID();
664 $this->mFile
.= '.db';
665 wfDebug( __CLASS__
. ": using cache file {$this->mFile}\n" );
666 $this->mHandler
= $wgDBAhandler;
670 * Encode value and expiry for storage
672 function encode( $value, $expiry ) {
673 # Convert to absolute time
674 $expiry = $this->convertExpiry( $expiry );
676 return sprintf( '%010u', intval( $expiry ) ) . ' ' . serialize( $value );
680 * @return list containing value first and expiry second
682 function decode( $blob ) {
683 if ( !is_string( $blob ) ) {
684 return array( null, 0 );
687 unserialize( substr( $blob, 11 ) ),
688 intval( substr( $blob, 0, 10 ) )
693 function getReader() {
694 if ( file_exists( $this->mFile
) ) {
695 $handle = dba_open( $this->mFile
, 'rl', $this->mHandler
);
697 $handle = $this->getWriter();
701 wfDebug( "Unable to open DBA cache file {$this->mFile}\n" );
707 function getWriter() {
708 $handle = dba_open( $this->mFile
, 'cl', $this->mHandler
);
711 wfDebug( "Unable to open DBA cache file {$this->mFile}\n" );
717 function get( $key ) {
718 wfProfileIn( __METHOD__
);
719 wfDebug( __METHOD__
. "($key)\n" );
721 $handle = $this->getReader();
726 $val = dba_fetch( $key, $handle );
727 list( $val, $expiry ) = $this->decode( $val );
729 # Must close ASAP because locks are held
730 dba_close( $handle );
732 if ( !is_null( $val ) && $expiry && $expiry < time() ) {
733 # Key is expired, delete it
734 $handle = $this->getWriter();
735 dba_delete( $key, $handle );
736 dba_close( $handle );
737 wfDebug( __METHOD__
. ": $key expired\n" );
741 wfProfileOut( __METHOD__
);
745 function set( $key, $value, $exptime = 0 ) {
746 wfProfileIn( __METHOD__
);
747 wfDebug( __METHOD__
. "($key)\n" );
749 $blob = $this->encode( $value, $exptime );
751 $handle = $this->getWriter();
756 $ret = dba_replace( $key, $blob, $handle );
757 dba_close( $handle );
759 wfProfileOut( __METHOD__
);
763 function delete( $key, $time = 0 ) {
764 wfProfileIn( __METHOD__
);
765 wfDebug( __METHOD__
. "($key)\n" );
767 $handle = $this->getWriter();
772 $ret = dba_delete( $key, $handle );
773 dba_close( $handle );
775 wfProfileOut( __METHOD__
);
779 function add( $key, $value, $exptime = 0 ) {
780 wfProfileIn( __METHOD__
);
782 $blob = $this->encode( $value, $exptime );
784 $handle = $this->getWriter();
790 $ret = dba_insert( $key, $blob, $handle );
792 # Insert failed, check to see if it failed due to an expired key
794 list( $value, $expiry ) = $this->decode( dba_fetch( $key, $handle ) );
796 if ( $expiry < time() ) {
797 # Yes expired, delete and try again
798 dba_delete( $key, $handle );
799 $ret = dba_insert( $key, $blob, $handle );
800 # This time if it failed then it will be handled by the caller like any other race
804 dba_close( $handle );
806 wfProfileOut( __METHOD__
);
811 $reader = $this->getReader();
812 $k1 = dba_firstkey( $reader );
820 while ( $key = dba_nextkey( $reader ) ) {
829 * Wrapper for WinCache object caching functions; identical interface
834 class WinCacheBagOStuff
extends BagOStuff
{
837 * Get a value from the WinCache object cache
839 * @param $key String: cache key
842 public function get( $key ) {
843 $val = wincache_ucache_get( $key );
845 if ( is_string( $val ) ) {
846 $val = unserialize( $val );
853 * Store a value in the WinCache object cache
855 * @param $key String: cache key
856 * @param $value Mixed: object to store
857 * @param $expire Int: expiration time
860 public function set( $key, $value, $expire = 0 ) {
861 wincache_ucache_set( $key, serialize( $value ), $expire );
867 * Remove a value from the WinCache object cache
869 * @param $key String: cache key
870 * @param $time Int: not used in this implementation
873 public function delete( $key, $time = 0 ) {
874 wincache_ucache_delete( $key );
879 public function keys() {
880 $info = wincache_ucache_info();
881 $list = $info['ucache_entries'];
884 foreach ( $list as $entry ) {
885 $keys[] = $entry['key_name'];