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 APC's shared memory functions
469 class APCBagOStuff
extends BagOStuff
{
470 public function get( $key ) {
471 $val = apc_fetch( $key );
472 if ( is_string( $val ) ) {
473 $val = unserialize( $val );
478 public function set( $key, $value, $exptime = 0 ) {
479 apc_store( $key, serialize( $value ), $exptime );
483 public function delete( $key, $time = 0 ) {
488 public function keys() {
489 $info = apc_cache_info( 'user' );
490 $list = $info['cache_list'];
492 foreach ( $list as $entry ) {
493 $keys[] = $entry['info'];
500 * This is a wrapper for eAccelerator's shared memory functions.
502 * This is basically identical to the deceased Turck MMCache version,
503 * mostly because eAccelerator is based on Turck MMCache.
507 class eAccelBagOStuff
extends BagOStuff
{
508 public function get( $key ) {
509 $val = eaccelerator_get( $key );
510 if ( is_string( $val ) ) {
511 $val = unserialize( $val );
516 public function set( $key, $value, $exptime = 0 ) {
517 eaccelerator_put( $key, serialize( $value ), $exptime );
521 public function delete( $key, $time = 0 ) {
522 eaccelerator_rm( $key );
526 public function lock( $key, $waitTimeout = 0 ) {
527 eaccelerator_lock( $key );
531 public function unlock( $key ) {
532 eaccelerator_unlock( $key );
538 * Wrapper for XCache object caching functions; identical interface
543 class XCacheBagOStuff
extends BagOStuff
{
546 * Get a value from the XCache object cache
548 * @param $key String: cache key
551 public function get( $key ) {
552 $val = xcache_get( $key );
553 if ( is_string( $val ) )
554 $val = unserialize( $val );
559 * Store a value in the XCache object cache
561 * @param $key String: cache key
562 * @param $value Mixed: object to store
563 * @param $expire Int: expiration time
566 public function set( $key, $value, $expire = 0 ) {
567 xcache_set( $key, serialize( $value ), $expire );
572 * Remove a value from the XCache object cache
574 * @param $key String: cache key
575 * @param $time Int: not used in this implementation
578 public function delete( $key, $time = 0 ) {
579 xcache_unset( $key );
585 * Cache that uses DBA as a backend.
586 * Slow due to the need to constantly open and close the file to avoid holding
587 * writer locks. Intended for development use only, as a memcached workalike
588 * for systems that don't have it.
592 class DBABagOStuff
extends BagOStuff
{
593 var $mHandler, $mFile, $mReader, $mWriter, $mDisabled;
595 public function __construct( $dir = false ) {
596 global $wgDBAhandler;
597 if ( $dir === false ) {
598 global $wgTmpDirectory;
599 $dir = $wgTmpDirectory;
601 $this->mFile
= "$dir/mw-cache-" . wfWikiID();
602 $this->mFile
.= '.db';
603 wfDebug( __CLASS__
. ": using cache file {$this->mFile}\n" );
604 $this->mHandler
= $wgDBAhandler;
608 * Encode value and expiry for storage
610 function encode( $value, $expiry ) {
611 # Convert to absolute time
612 $expiry = $this->convertExpiry( $expiry );
613 return sprintf( '%010u', intval( $expiry ) ) . ' ' . serialize( $value );
617 * @return list containing value first and expiry second
619 function decode( $blob ) {
620 if ( !is_string( $blob ) ) {
621 return array( null, 0 );
624 unserialize( substr( $blob, 11 ) ),
625 intval( substr( $blob, 0, 10 ) )
630 function getReader() {
631 if ( file_exists( $this->mFile
) ) {
632 $handle = dba_open( $this->mFile
, 'rl', $this->mHandler
);
634 $handle = $this->getWriter();
637 wfDebug( "Unable to open DBA cache file {$this->mFile}\n" );
642 function getWriter() {
643 $handle = dba_open( $this->mFile
, 'cl', $this->mHandler
);
645 wfDebug( "Unable to open DBA cache file {$this->mFile}\n" );
650 function get( $key ) {
651 wfProfileIn( __METHOD__
);
652 wfDebug( __METHOD__
. "($key)\n" );
653 $handle = $this->getReader();
657 $val = dba_fetch( $key, $handle );
658 list( $val, $expiry ) = $this->decode( $val );
659 # Must close ASAP because locks are held
660 dba_close( $handle );
662 if ( !is_null( $val ) && $expiry && $expiry < time() ) {
663 # Key is expired, delete it
664 $handle = $this->getWriter();
665 dba_delete( $key, $handle );
666 dba_close( $handle );
667 wfDebug( __METHOD__
. ": $key expired\n" );
670 wfProfileOut( __METHOD__
);
674 function set( $key, $value, $exptime = 0 ) {
675 wfProfileIn( __METHOD__
);
676 wfDebug( __METHOD__
. "($key)\n" );
677 $blob = $this->encode( $value, $exptime );
678 $handle = $this->getWriter();
682 $ret = dba_replace( $key, $blob, $handle );
683 dba_close( $handle );
684 wfProfileOut( __METHOD__
);
688 function delete( $key, $time = 0 ) {
689 wfProfileIn( __METHOD__
);
690 wfDebug( __METHOD__
. "($key)\n" );
691 $handle = $this->getWriter();
695 $ret = dba_delete( $key, $handle );
696 dba_close( $handle );
697 wfProfileOut( __METHOD__
);
701 function add( $key, $value, $exptime = 0 ) {
702 wfProfileIn( __METHOD__
);
703 $blob = $this->encode( $value, $exptime );
704 $handle = $this->getWriter();
708 $ret = dba_insert( $key, $blob, $handle );
709 # Insert failed, check to see if it failed due to an expired key
711 list( $value, $expiry ) = $this->decode( dba_fetch( $key, $handle ) );
712 if ( $expiry < time() ) {
713 # Yes expired, delete and try again
714 dba_delete( $key, $handle );
715 $ret = dba_insert( $key, $blob, $handle );
716 # This time if it failed then it will be handled by the caller like any other race
720 dba_close( $handle );
721 wfProfileOut( __METHOD__
);
726 $reader = $this->getReader();
727 $k1 = dba_firstkey( $reader );
732 while ( $key = dba_nextkey( $reader ) ) {