3 * Classes to cache objects in PHP accelerators, SQL database or DBA files
5 * Copyright © 2003-2004 Brion Vibber <brion@pobox.com>
6 * http://www.mediawiki.org/
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
28 * @defgroup Cache Cache
32 * interface is intended to be more or less compatible with
33 * the PHP memcached client.
35 * backends for local hash array and SQL table included:
37 * $bag = new HashBagOStuff();
38 * $bag = new SqlBagOStuff(); # connect to db first
43 abstract class BagOStuff
{
44 var $debugMode = false;
46 public function set_debug( $bool ) {
47 $this->debugMode
= $bool;
50 /* *** THE GUTS OF THE OPERATION *** */
51 /* Override these with functional things in subclasses */
54 * Get an item with the given key. Returns false if it does not exist.
57 abstract public function get( $key );
63 * @param $exptime int Either an interval in seconds or a unix timestamp for expiry
65 abstract public function set( $key, $value, $exptime = 0 );
70 * @param $time int Amount of time to delay the operation (mostly memcached-specific)
72 abstract public function delete( $key, $time = 0 );
74 public function lock( $key, $timeout = 0 ) {
79 public function unlock( $key ) {
84 public function keys() {
89 /* *** Emulated functions *** */
90 /* Better performance can likely be got with custom written versions */
91 public function get_multi( $keys ) {
94 foreach ( $keys as $key ) {
95 $out[$key] = $this->get( $key );
101 public function set_multi( $hash, $exptime = 0 ) {
102 foreach ( $hash as $key => $value ) {
103 $this->set( $key, $value, $exptime );
107 public function add( $key, $value, $exptime = 0 ) {
108 if ( !$this->get( $key ) ) {
109 $this->set( $key, $value, $exptime );
115 public function add_multi( $hash, $exptime = 0 ) {
116 foreach ( $hash as $key => $value ) {
117 $this->add( $key, $value, $exptime );
121 public function delete_multi( $keys, $time = 0 ) {
122 foreach ( $keys as $key ) {
123 $this->delete( $key, $time );
127 public function replace( $key, $value, $exptime = 0 ) {
128 if ( $this->get( $key ) !== false ) {
129 $this->set( $key, $value, $exptime );
133 public function incr( $key, $value = 1 ) {
134 if ( !$this->lock( $key ) ) {
138 $value = intval( $value );
140 if ( ( $n = $this->get( $key ) ) !== false ) {
142 $this->set( $key, $n ); // exptime?
144 $this->unlock( $key );
149 public function decr( $key, $value = 1 ) {
150 return $this->incr( $key, - $value );
153 public function debug( $text ) {
154 if ( $this->debugMode
) {
155 wfDebug( "BagOStuff debug: $text\n" );
160 * Convert an optionally relative time to an absolute time
162 protected function convertExpiry( $exptime ) {
163 if ( ( $exptime != 0 ) && ( $exptime < 86400 * 3650 /* 10 years */ ) ) {
164 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 protected function expire( $key ) {
186 $et = $this->bag
[$key][1];
188 if ( ( $et == 0 ) ||
( $et > time() ) ) {
192 $this->delete( $key );
197 function get( $key ) {
198 if ( !isset( $this->bag
[$key] ) ) {
202 if ( $this->expire( $key ) ) {
206 return $this->bag
[$key][0];
209 function set( $key, $value, $exptime = 0 ) {
210 $this->bag
[$key] = array( $value, $this->convertExpiry( $exptime ) );
213 function delete( $key, $time = 0 ) {
214 if ( !isset( $this->bag
[$key] ) ) {
218 unset( $this->bag
[$key] );
224 return array_keys( $this->bag
);
229 * Class to store objects in the database
233 class SqlBagOStuff
extends BagOStuff
{
235 var $lastExpireAll = 0;
237 protected function getDB() {
240 if ( !isset( $this->db
) ) {
241 /* We must keep a separate connection to MySQL in order to avoid deadlocks
242 * However, SQLite has an opposite behaviour.
243 * @todo Investigate behaviour for other databases
245 if ( $wgDBtype == 'sqlite' ) {
246 $this->db
= wfGetDB( DB_MASTER
);
248 $this->lb
= wfGetLBFactory()->newMainLB();
249 $this->db
= $this->lb
->getConnection( DB_MASTER
);
250 $this->db
->clearFlag( DBO_TRX
);
257 public function get( $key ) {
258 # expire old entries if any
259 $this->garbageCollect();
260 $db = $this->getDB();
261 $row = $db->selectRow( 'objectcache', array( 'value', 'exptime' ),
262 array( 'keyname' => $key ), __METHOD__
);
265 $this->debug( 'get: no matching rows' );
269 $this->debug( "get: retrieved data; expiry time is " . $row->exptime
);
271 if ( $this->isExpired( $row->exptime
) ) {
272 $this->debug( "get: key has expired, deleting" );
275 # Put the expiry time in the WHERE condition to avoid deleting a
276 # newly-inserted value
277 $db->delete( 'objectcache',
280 'exptime' => $row->exptime
283 } catch ( DBQueryError
$e ) {
284 $this->handleWriteError( $e );
290 return $this->unserialize( $db->decodeBlob( $row->value
) );
293 public function set( $key, $value, $exptime = 0 ) {
294 $db = $this->getDB();
295 $exptime = intval( $exptime );
297 if ( $exptime < 0 ) {
301 if ( $exptime == 0 ) {
302 $encExpiry = $this->getMaxDateTime();
304 if ( $exptime < 3.16e8
) { # ~10 years
308 $encExpiry = $db->timestamp( $exptime );
312 // (bug 24425) use a replace if the db supports it instead of
313 // delete/insert to avoid clashes with conflicting keynames
314 $db->replace( 'objectcache', array( 'keyname' ),
317 'value' => $db->encodeBlob( $this->serialize( $value ) ),
318 'exptime' => $encExpiry
321 } catch ( DBQueryError
$e ) {
322 $this->handleWriteError( $e );
330 public function delete( $key, $time = 0 ) {
331 $db = $this->getDB();
335 $db->delete( 'objectcache', array( 'keyname' => $key ), __METHOD__
);
337 } catch ( DBQueryError
$e ) {
338 $this->handleWriteError( $e );
346 public function incr( $key, $step = 1 ) {
347 $db = $this->getDB();
348 $step = intval( $step );
352 $row = $db->selectRow( 'objectcache', array( 'value', 'exptime' ),
353 array( 'keyname' => $key ), __METHOD__
, array( 'FOR UPDATE' ) );
354 if ( $row === false ) {
360 $db->delete( 'objectcache', array( 'keyname' => $key ), __METHOD__
);
361 if ( $this->isExpired( $row->exptime
) ) {
362 // Expired, do not reinsert
368 $oldValue = intval( $this->unserialize( $db->decodeBlob( $row->value
) ) );
369 $newValue = $oldValue +
$step;
370 $db->insert( 'objectcache',
373 'value' => $db->encodeBlob( $this->serialize( $newValue ) ),
374 'exptime' => $row->exptime
377 } catch ( DBQueryError
$e ) {
378 $this->handleWriteError( $e );
386 public function keys() {
387 $db = $this->getDB();
388 $res = $db->select( 'objectcache', array( 'keyname' ), false, __METHOD__
);
391 foreach ( $res as $row ) {
392 $result[] = $row->keyname
;
398 protected function isExpired( $exptime ) {
399 return $exptime != $this->getMaxDateTime() && wfTimestamp( TS_UNIX
, $exptime ) < time();
402 protected function getMaxDateTime() {
403 if ( time() > 0x7fffffff ) {
404 return $this->getDB()->timestamp( 1 << 62 );
406 return $this->getDB()->timestamp( 0x7fffffff );
410 protected function garbageCollect() {
411 /* Ignore 99% of requests */
412 if ( !mt_rand( 0, 100 ) ) {
414 /* Avoid repeating the delete within a few seconds */
415 if ( $now > ( $this->lastExpireAll +
1 ) ) {
416 $this->lastExpireAll
= $now;
422 public function expireAll() {
423 $db = $this->getDB();
424 $now = $db->timestamp();
428 $db->delete( 'objectcache', array( 'exptime < ' . $db->addQuotes( $now ) ), __METHOD__
);
430 } catch ( DBQueryError
$e ) {
431 $this->handleWriteError( $e );
435 public function deleteAll() {
436 $db = $this->getDB();
440 $db->delete( 'objectcache', '*', __METHOD__
);
442 } catch ( DBQueryError
$e ) {
443 $this->handleWriteError( $e );
448 * Serialize an object and, if possible, compress the representation.
449 * On typical message and page data, this can provide a 3X decrease
450 * in storage requirements.
455 protected function serialize( &$data ) {
456 $serial = serialize( $data );
458 if ( function_exists( 'gzdeflate' ) ) {
459 return gzdeflate( $serial );
466 * Unserialize and, if necessary, decompress an object.
467 * @param $serial string
470 protected function unserialize( $serial ) {
471 if ( function_exists( 'gzinflate' ) ) {
472 $decomp = @gzinflate
( $serial );
474 if ( false !== $decomp ) {
479 $ret = unserialize( $serial );
485 * Handle a DBQueryError which occurred during a write operation.
486 * Ignore errors which are due to a read-only database, rethrow others.
488 protected function handleWriteError( $exception ) {
489 $db = $this->getDB();
491 if ( !$db->wasReadOnlyError() ) {
497 } catch ( DBQueryError
$e ) {
500 wfDebug( __METHOD__
. ": ignoring query error\n" );
501 $db->ignoreErrors( false );
506 * Backwards compatibility alias
508 class MediaWikiBagOStuff
extends SqlBagOStuff
{ }
511 * This is a wrapper for APC's shared memory functions
515 class APCBagOStuff
extends BagOStuff
{
516 public function get( $key ) {
517 $val = apc_fetch( $key );
519 if ( is_string( $val ) ) {
520 $val = unserialize( $val );
526 public function set( $key, $value, $exptime = 0 ) {
527 apc_store( $key, serialize( $value ), $exptime );
532 public function delete( $key, $time = 0 ) {
538 public function keys() {
539 $info = apc_cache_info( 'user' );
540 $list = $info['cache_list'];
543 foreach ( $list as $entry ) {
544 $keys[] = $entry['info'];
552 * This is a wrapper for eAccelerator's shared memory functions.
554 * This is basically identical to the deceased Turck MMCache version,
555 * mostly because eAccelerator is based on Turck MMCache.
559 class eAccelBagOStuff
extends BagOStuff
{
560 public function get( $key ) {
561 $val = eaccelerator_get( $key );
563 if ( is_string( $val ) ) {
564 $val = unserialize( $val );
570 public function set( $key, $value, $exptime = 0 ) {
571 eaccelerator_put( $key, serialize( $value ), $exptime );
576 public function delete( $key, $time = 0 ) {
577 eaccelerator_rm( $key );
582 public function lock( $key, $waitTimeout = 0 ) {
583 eaccelerator_lock( $key );
588 public function unlock( $key ) {
589 eaccelerator_unlock( $key );
596 * Wrapper for XCache object caching functions; identical interface
601 class XCacheBagOStuff
extends BagOStuff
{
603 * Get a value from the XCache object cache
605 * @param $key String: cache key
608 public function get( $key ) {
609 $val = xcache_get( $key );
611 if ( is_string( $val ) ) {
612 $val = unserialize( $val );
619 * Store a value in the XCache object cache
621 * @param $key String: cache key
622 * @param $value Mixed: object to store
623 * @param $expire Int: expiration time
626 public function set( $key, $value, $expire = 0 ) {
627 xcache_set( $key, serialize( $value ), $expire );
633 * Remove a value from the XCache object cache
635 * @param $key String: cache key
636 * @param $time Int: not used in this implementation
639 public function delete( $key, $time = 0 ) {
640 xcache_unset( $key );
647 * Cache that uses DBA as a backend.
648 * Slow due to the need to constantly open and close the file to avoid holding
649 * writer locks. Intended for development use only, as a memcached workalike
650 * for systems that don't have it.
654 class DBABagOStuff
extends BagOStuff
{
655 var $mHandler, $mFile, $mReader, $mWriter, $mDisabled;
657 public function __construct( $dir = false ) {
658 global $wgDBAhandler;
660 if ( $dir === false ) {
661 global $wgTmpDirectory;
662 $dir = $wgTmpDirectory;
665 $this->mFile
= "$dir/mw-cache-" . wfWikiID();
666 $this->mFile
.= '.db';
667 wfDebug( __CLASS__
. ": using cache file {$this->mFile}\n" );
668 $this->mHandler
= $wgDBAhandler;
672 * Encode value and expiry for storage
674 function encode( $value, $expiry ) {
675 # Convert to absolute time
676 $expiry = $this->convertExpiry( $expiry );
678 return sprintf( '%010u', intval( $expiry ) ) . ' ' . serialize( $value );
682 * @return list containing value first and expiry second
684 function decode( $blob ) {
685 if ( !is_string( $blob ) ) {
686 return array( null, 0 );
689 unserialize( substr( $blob, 11 ) ),
690 intval( substr( $blob, 0, 10 ) )
695 function getReader() {
696 if ( file_exists( $this->mFile
) ) {
697 $handle = dba_open( $this->mFile
, 'rl', $this->mHandler
);
699 $handle = $this->getWriter();
703 wfDebug( "Unable to open DBA cache file {$this->mFile}\n" );
709 function getWriter() {
710 $handle = dba_open( $this->mFile
, 'cl', $this->mHandler
);
713 wfDebug( "Unable to open DBA cache file {$this->mFile}\n" );
719 function get( $key ) {
720 wfProfileIn( __METHOD__
);
721 wfDebug( __METHOD__
. "($key)\n" );
723 $handle = $this->getReader();
728 $val = dba_fetch( $key, $handle );
729 list( $val, $expiry ) = $this->decode( $val );
731 # Must close ASAP because locks are held
732 dba_close( $handle );
734 if ( !is_null( $val ) && $expiry && $expiry < time() ) {
735 # Key is expired, delete it
736 $handle = $this->getWriter();
737 dba_delete( $key, $handle );
738 dba_close( $handle );
739 wfDebug( __METHOD__
. ": $key expired\n" );
743 wfProfileOut( __METHOD__
);
747 function set( $key, $value, $exptime = 0 ) {
748 wfProfileIn( __METHOD__
);
749 wfDebug( __METHOD__
. "($key)\n" );
751 $blob = $this->encode( $value, $exptime );
753 $handle = $this->getWriter();
758 $ret = dba_replace( $key, $blob, $handle );
759 dba_close( $handle );
761 wfProfileOut( __METHOD__
);
765 function delete( $key, $time = 0 ) {
766 wfProfileIn( __METHOD__
);
767 wfDebug( __METHOD__
. "($key)\n" );
769 $handle = $this->getWriter();
774 $ret = dba_delete( $key, $handle );
775 dba_close( $handle );
777 wfProfileOut( __METHOD__
);
781 function add( $key, $value, $exptime = 0 ) {
782 wfProfileIn( __METHOD__
);
784 $blob = $this->encode( $value, $exptime );
786 $handle = $this->getWriter();
792 $ret = dba_insert( $key, $blob, $handle );
794 # Insert failed, check to see if it failed due to an expired key
796 list( $value, $expiry ) = $this->decode( dba_fetch( $key, $handle ) );
798 if ( $expiry < time() ) {
799 # Yes expired, delete and try again
800 dba_delete( $key, $handle );
801 $ret = dba_insert( $key, $blob, $handle );
802 # This time if it failed then it will be handled by the caller like any other race
806 dba_close( $handle );
808 wfProfileOut( __METHOD__
);
813 $reader = $this->getReader();
814 $k1 = dba_firstkey( $reader );
822 while ( $key = dba_nextkey( $reader ) ) {
831 * Wrapper for WinCache object caching functions; identical interface
836 class WinCacheBagOStuff
extends BagOStuff
{
839 * Get a value from the WinCache object cache
841 * @param $key String: cache key
844 public function get( $key ) {
845 $val = wincache_ucache_get( $key );
847 if ( is_string( $val ) ) {
848 $val = unserialize( $val );
855 * Store a value in the WinCache object cache
857 * @param $key String: cache key
858 * @param $value Mixed: object to store
859 * @param $expire Int: expiration time
862 public function set( $key, $value, $expire = 0 ) {
863 wincache_ucache_set( $key, serialize( $value ), $expire );
869 * Remove a value from the WinCache object cache
871 * @param $key String: cache key
872 * @param $time Int: not used in this implementation
875 public function delete( $key, $time = 0 ) {
876 wincache_ucache_delete( $key );
881 public function keys() {
882 $info = wincache_ucache_info();
883 $list = $info['ucache_entries'];
886 foreach ( $list as $entry ) {
887 $keys[] = $entry['key_name'];