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 ) == false ) {
106 $this->set( $key, $value, $exptime );
111 public function add_multi( $hash, $exptime = 0 ) {
112 foreach ( $hash as $key => $value ) {
113 $this->add( $key, $value, $exptime );
117 public function delete_multi( $keys, $time = 0 ) {
118 foreach ( $keys as $key ) {
119 $this->delete( $key, $time );
123 public function replace( $key, $value, $exptime = 0 ) {
124 if ( $this->get( $key ) !== false ) {
125 $this->set( $key, $value, $exptime );
129 public function incr( $key, $value = 1 ) {
130 if ( !$this->lock( $key ) ) {
133 $value = intval( $value );
136 if ( ( $n = $this->get( $key ) ) !== false ) {
138 $this->set( $key, $n ); // exptime?
140 $this->unlock( $key );
144 public function decr( $key, $value = 1 ) {
145 return $this->incr( $key, - $value );
148 public function debug( $text ) {
149 if ( $this->debugMode
)
150 wfDebug( "BagOStuff debug: $text\n" );
154 * Convert an optionally relative time to an absolute time
156 protected function convertExpiry( $exptime ) {
157 if ( ( $exptime != 0 ) && ( $exptime < 3600 * 24 * 30 ) ) {
158 return time() +
$exptime;
166 * Functional versions!
167 * This is a test of the interface, mainly. It stores things in an associative
168 * array, which is not going to persist between program runs.
172 class HashBagOStuff
extends BagOStuff
{
175 function __construct() {
176 $this->bag
= array();
179 protected function expire( $key ) {
180 $et = $this->bag
[$key][1];
181 if ( ( $et == 0 ) ||
( $et > time() ) ) {
184 $this->delete( $key );
188 function get( $key ) {
189 if ( !isset( $this->bag
[$key] ) ) {
192 if ( $this->expire( $key ) ) {
195 return $this->bag
[$key][0];
198 function set( $key, $value, $exptime = 0 ) {
199 $this->bag
[$key] = array( $value, $this->convertExpiry( $exptime ) );
202 function delete( $key, $time = 0 ) {
203 if ( !isset( $this->bag
[$key] ) ) {
206 unset( $this->bag
[$key] );
211 return array_keys( $this->bag
);
216 * Class to store objects in the database
220 class SqlBagOStuff
extends BagOStuff
{
222 var $lastExpireAll = 0;
224 protected function getDB() {
226 if ( !isset( $this->db
) ) {
227 /* We must keep a separate connection to MySQL in order to avoid deadlocks
228 * However, SQLite has an opposite behaviour.
229 * @todo Investigate behaviour for other databases
231 if ( $wgDBtype == 'sqlite' ) {
232 $this->db
= wfGetDB( DB_MASTER
);
234 $this->lb
= wfGetLBFactory()->newMainLB();
235 $this->db
= $this->lb
->getConnection( DB_MASTER
);
236 $this->db
->clearFlag( DBO_TRX
);
242 public function get( $key ) {
243 # expire old entries if any
244 $this->garbageCollect();
245 $db = $this->getDB();
246 $row = $db->selectRow( 'objectcache', array( 'value', 'exptime' ),
247 array( 'keyname' => $key ), __METHOD__
);
249 $this->debug( 'get: no matching rows' );
253 $this->debug( "get: retrieved data; expiry time is " . $row->exptime
);
254 if ( $this->isExpired( $row->exptime
) ) {
255 $this->debug( "get: key has expired, deleting" );
258 # Put the expiry time in the WHERE condition to avoid deleting a
259 # newly-inserted value
260 $db->delete( 'objectcache',
263 'exptime' => $row->exptime
266 } catch ( DBQueryError
$e ) {
267 $this->handleWriteError( $e );
271 return $this->unserialize( $db->decodeBlob( $row->value
) );
274 public function set( $key, $value, $exptime = 0 ) {
275 $db = $this->getDB();
276 $exptime = intval( $exptime );
277 if ( $exptime < 0 ) $exptime = 0;
278 if ( $exptime == 0 ) {
279 $encExpiry = $this->getMaxDateTime();
281 if ( $exptime < 3.16e8
) # ~10 years
283 $encExpiry = $db->timestamp( $exptime );
287 $db->delete( 'objectcache', array( 'keyname' => $key ), __METHOD__
);
288 $db->insert( 'objectcache',
291 'value' => $db->encodeBlob( $this->serialize( $value ) ),
292 'exptime' => $encExpiry
295 } catch ( DBQueryError
$e ) {
296 $this->handleWriteError( $e );
302 public function delete( $key, $time = 0 ) {
303 $db = $this->getDB();
306 $db->delete( 'objectcache', array( 'keyname' => $key ), __METHOD__
);
308 } catch ( DBQueryError
$e ) {
309 $this->handleWriteError( $e );
315 public function incr( $key, $step = 1 ) {
316 $db = $this->getDB();
317 $step = intval( $step );
321 $row = $db->selectRow( 'objectcache', array( 'value', 'exptime' ),
322 array( 'keyname' => $key ), __METHOD__
, array( 'FOR UPDATE' ) );
323 if ( $row === false ) {
328 $db->delete( 'objectcache', array( 'keyname' => $key ), __METHOD__
);
329 if ( $this->isExpired( $row->exptime
) ) {
330 // Expired, do not reinsert
335 $oldValue = intval( $this->unserialize( $db->decodeBlob( $row->value
) ) );
336 $newValue = $oldValue +
$step;
337 $db->insert( 'objectcache',
340 'value' => $db->encodeBlob( $this->serialize( $newValue ) ),
341 'exptime' => $row->exptime
344 } catch ( DBQueryError
$e ) {
345 $this->handleWriteError( $e );
351 public function keys() {
352 $db = $this->getDB();
353 $res = $db->select( 'objectcache', array( 'keyname' ), false, __METHOD__
);
355 foreach ( $res as $row ) {
356 $result[] = $row->keyname
;
361 protected function isExpired( $exptime ) {
362 return $exptime != $this->getMaxDateTime() && wfTimestamp( TS_UNIX
, $exptime ) < time();
365 protected function getMaxDateTime() {
366 if ( time() > 0x7fffffff ) {
367 return $this->getDB()->timestamp( 1 << 62 );
369 return $this->getDB()->timestamp( 0x7fffffff );
373 protected function garbageCollect() {
374 /* Ignore 99% of requests */
375 if ( !mt_rand( 0, 100 ) ) {
377 /* Avoid repeating the delete within a few seconds */
378 if ( $now > ( $this->lastExpireAll +
1 ) ) {
379 $this->lastExpireAll
= $now;
385 public function expireAll() {
386 $db = $this->getDB();
387 $now = $db->timestamp();
390 $db->delete( 'objectcache', array( 'exptime < ' . $db->addQuotes( $now ) ), __METHOD__
);
392 } catch ( DBQueryError
$e ) {
393 $this->handleWriteError( $e );
397 public function deleteAll() {
398 $db = $this->getDB();
401 $db->delete( 'objectcache', '*', __METHOD__
);
403 } catch ( DBQueryError
$e ) {
404 $this->handleWriteError( $e );
409 * Serialize an object and, if possible, compress the representation.
410 * On typical message and page data, this can provide a 3X decrease
411 * in storage requirements.
416 protected function serialize( &$data ) {
417 $serial = serialize( $data );
418 if ( function_exists( 'gzdeflate' ) ) {
419 return gzdeflate( $serial );
426 * Unserialize and, if necessary, decompress an object.
427 * @param $serial string
430 protected function unserialize( $serial ) {
431 if ( function_exists( 'gzinflate' ) ) {
432 $decomp = @gzinflate
( $serial );
433 if ( false !== $decomp ) {
437 $ret = unserialize( $serial );
442 * Handle a DBQueryError which occurred during a write operation.
443 * Ignore errors which are due to a read-only database, rethrow others.
445 protected function handleWriteError( $exception ) {
446 $db = $this->getDB();
447 if ( !$db->wasReadOnlyError() ) {
452 } catch ( DBQueryError
$e ) {
454 wfDebug( __METHOD__
. ": ignoring query error\n" );
455 $db->ignoreErrors( false );
460 * Backwards compatibility alias
462 class MediaWikiBagOStuff
extends SqlBagOStuff
{ }
465 * This is a wrapper for Turck MMCache's shared memory functions.
467 * You can store objects with mmcache_put() and mmcache_get(), but Turck seems
468 * to use a weird custom serializer that randomly segfaults. So we wrap calls
469 * with serialize()/unserialize().
471 * The thing I noticed about the Turck serialized data was that unlike ordinary
472 * serialize(), it contained the names of methods, and judging by the amount of
473 * binary data, perhaps even the bytecode of the methods themselves. It may be
474 * that Turck's serializer is faster, so a possible future extension would be
475 * to use it for arrays but not for objects.
479 class TurckBagOStuff
extends BagOStuff
{
480 public function get( $key ) {
481 $val = mmcache_get( $key );
482 if ( is_string( $val ) ) {
483 $val = unserialize( $val );
488 public function set( $key, $value, $exptime = 0 ) {
489 mmcache_put( $key, serialize( $value ), $exptime );
493 public function delete( $key, $time = 0 ) {
498 public function lock( $key, $waitTimeout = 0 ) {
499 mmcache_lock( $key );
503 public function unlock( $key ) {
504 mmcache_unlock( $key );
510 * This is a wrapper for APC's shared memory functions
514 class APCBagOStuff
extends BagOStuff
{
515 public function get( $key ) {
516 $val = apc_fetch( $key );
517 if ( is_string( $val ) ) {
518 $val = unserialize( $val );
523 public function set( $key, $value, $exptime = 0 ) {
524 apc_store( $key, serialize( $value ), $exptime );
528 public function delete( $key, $time = 0 ) {
533 public function keys() {
534 $info = apc_cache_info( 'user' );
535 $list = $info['cache_list'];
537 foreach ( $list as $entry ) {
538 $keys[] = $entry['info'];
545 * This is a wrapper for eAccelerator's shared memory functions.
547 * This is basically identical to the Turck MMCache version,
548 * mostly because eAccelerator is based on Turck MMCache.
552 class eAccelBagOStuff
extends BagOStuff
{
553 public function get( $key ) {
554 $val = eaccelerator_get( $key );
555 if ( is_string( $val ) ) {
556 $val = unserialize( $val );
561 public function set( $key, $value, $exptime = 0 ) {
562 eaccelerator_put( $key, serialize( $value ), $exptime );
566 public function delete( $key, $time = 0 ) {
567 eaccelerator_rm( $key );
571 public function lock( $key, $waitTimeout = 0 ) {
572 eaccelerator_lock( $key );
576 public function unlock( $key ) {
577 eaccelerator_unlock( $key );
583 * Wrapper for XCache object caching functions; identical interface
588 class XCacheBagOStuff
extends BagOStuff
{
591 * Get a value from the XCache object cache
593 * @param $key String: cache key
596 public function get( $key ) {
597 $val = xcache_get( $key );
598 if ( is_string( $val ) )
599 $val = unserialize( $val );
604 * Store a value in the XCache object cache
606 * @param $key String: cache key
607 * @param $value Mixed: object to store
608 * @param $expire Int: expiration time
611 public function set( $key, $value, $expire = 0 ) {
612 xcache_set( $key, serialize( $value ), $expire );
617 * Remove a value from the XCache object cache
619 * @param $key String: cache key
620 * @param $time Int: not used in this implementation
623 public function delete( $key, $time = 0 ) {
624 xcache_unset( $key );
630 * Cache that uses DBA as a backend.
631 * Slow due to the need to constantly open and close the file to avoid holding
632 * writer locks. Intended for development use only, as a memcached workalike
633 * for systems that don't have it.
637 class DBABagOStuff
extends BagOStuff
{
638 var $mHandler, $mFile, $mReader, $mWriter, $mDisabled;
640 public function __construct( $dir = false ) {
641 global $wgDBAhandler;
642 if ( $dir === false ) {
643 global $wgTmpDirectory;
644 $dir = $wgTmpDirectory;
646 $this->mFile
= "$dir/mw-cache-" . wfWikiID();
647 $this->mFile
.= '.db';
648 wfDebug( __CLASS__
. ": using cache file {$this->mFile}\n" );
649 $this->mHandler
= $wgDBAhandler;
653 * Encode value and expiry for storage
655 function encode( $value, $expiry ) {
656 # Convert to absolute time
657 $expiry = $this->convertExpiry( $expiry );
658 return sprintf( '%010u', intval( $expiry ) ) . ' ' . serialize( $value );
662 * @return list containing value first and expiry second
664 function decode( $blob ) {
665 if ( !is_string( $blob ) ) {
666 return array( null, 0 );
669 unserialize( substr( $blob, 11 ) ),
670 intval( substr( $blob, 0, 10 ) )
675 function getReader() {
676 if ( file_exists( $this->mFile
) ) {
677 $handle = dba_open( $this->mFile
, 'rl', $this->mHandler
);
679 $handle = $this->getWriter();
682 wfDebug( "Unable to open DBA cache file {$this->mFile}\n" );
687 function getWriter() {
688 $handle = dba_open( $this->mFile
, 'cl', $this->mHandler
);
690 wfDebug( "Unable to open DBA cache file {$this->mFile}\n" );
695 function get( $key ) {
696 wfProfileIn( __METHOD__
);
697 wfDebug( __METHOD__
. "($key)\n" );
698 $handle = $this->getReader();
702 $val = dba_fetch( $key, $handle );
703 list( $val, $expiry ) = $this->decode( $val );
704 # Must close ASAP because locks are held
705 dba_close( $handle );
707 if ( !is_null( $val ) && $expiry && $expiry < time() ) {
708 # Key is expired, delete it
709 $handle = $this->getWriter();
710 dba_delete( $key, $handle );
711 dba_close( $handle );
712 wfDebug( __METHOD__
. ": $key expired\n" );
715 wfProfileOut( __METHOD__
);
719 function set( $key, $value, $exptime = 0 ) {
720 wfProfileIn( __METHOD__
);
721 wfDebug( __METHOD__
. "($key)\n" );
722 $blob = $this->encode( $value, $exptime );
723 $handle = $this->getWriter();
727 $ret = dba_replace( $key, $blob, $handle );
728 dba_close( $handle );
729 wfProfileOut( __METHOD__
);
733 function delete( $key, $time = 0 ) {
734 wfProfileIn( __METHOD__
);
735 wfDebug( __METHOD__
. "($key)\n" );
736 $handle = $this->getWriter();
740 $ret = dba_delete( $key, $handle );
741 dba_close( $handle );
742 wfProfileOut( __METHOD__
);
746 function add( $key, $value, $exptime = 0 ) {
747 wfProfileIn( __METHOD__
);
748 $blob = $this->encode( $value, $exptime );
749 $handle = $this->getWriter();
753 $ret = dba_insert( $key, $blob, $handle );
754 # Insert failed, check to see if it failed due to an expired key
756 list( $value, $expiry ) = $this->decode( dba_fetch( $key, $handle ) );
757 if ( $expiry < time() ) {
758 # Yes expired, delete and try again
759 dba_delete( $key, $handle );
760 $ret = dba_insert( $key, $blob, $handle );
761 # This time if it failed then it will be handled by the caller like any other race
765 dba_close( $handle );
766 wfProfileOut( __METHOD__
);
771 $reader = $this->getReader();
772 $k1 = dba_firstkey( $reader );
777 while ( $key = dba_nextkey( $reader ) ) {