Revert r68598. Broken.
[mediawiki.git] / includes / BagOStuff.php
blobfb57ad023c8ece3ca01b643dbc0af3b42ee6aa6c
1 <?php
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
21 /**
22 * @defgroup Cache Cache
24 * @file
25 * @ingroup Cache
28 /**
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:
33 * <code>
34 * $bag = new HashBagOStuff();
35 * $bag = new SqlBagOStuff(); # connect to db first
36 * </code>
38 * @ingroup Cache
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 */
50 /**
51 * Get an item with the given key. Returns false if it does not exist.
52 * @param $key string
54 abstract public function get( $key );
56 /**
57 * Set an item.
58 * @param $key string
59 * @param $value mixed
60 * @param $exptime int Either an interval in seconds or a unix timestamp for expiry
62 abstract public function set( $key, $value, $exptime = 0 );
65 * Delete an item.
66 * @param $key string
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 ) {
72 /* stub */
73 return true;
76 public function unlock( $key ) {
77 /* stub */
78 return true;
81 public function keys() {
82 /* stub */
83 return array();
86 /* *** Emulated functions *** */
87 /* Better performance can likely be got with custom written versions */
88 public function get_multi( $keys ) {
89 $out = array();
91 foreach ( $keys as $key ) {
92 $out[$key] = $this->get( $key );
95 return $out;
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 );
108 return true;
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 ) ) {
132 return false;
135 $value = intval( $value );
137 $n = false;
138 if ( ( $n = $this->get( $key ) ) !== false ) {
139 $n += $value;
140 $this->set( $key, $n ); // exptime?
142 $this->unlock( $key );
144 return $n;
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;
163 } else {
164 return $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.
174 * @ingroup Cache
176 class HashBagOStuff extends BagOStuff {
177 var $bag;
179 function __construct() {
180 $this->bag = array();
183 protected function expire( $key ) {
184 $et = $this->bag[$key][1];
186 if ( ( $et == 0 ) || ( $et > time() ) ) {
187 return false;
190 $this->delete( $key );
192 return true;
195 function get( $key ) {
196 if ( !isset( $this->bag[$key] ) ) {
197 return false;
200 if ( $this->expire( $key ) ) {
201 return false;
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] ) ) {
213 return false;
216 unset( $this->bag[$key] );
218 return true;
221 function keys() {
222 return array_keys( $this->bag );
227 * Class to store objects in the database
229 * @ingroup Cache
231 class SqlBagOStuff extends BagOStuff {
232 var $lb, $db;
233 var $lastExpireAll = 0;
235 protected function getDB() {
236 global $wgDBtype;
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 );
245 } else {
246 $this->lb = wfGetLBFactory()->newMainLB();
247 $this->db = $this->lb->getConnection( DB_MASTER );
248 $this->db->clearFlag( DBO_TRX );
252 return $this->db;
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__ );
262 if ( !$row ) {
263 $this->debug( 'get: no matching rows' );
264 return false;
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" );
271 try {
272 $db->begin();
273 # Put the expiry time in the WHERE condition to avoid deleting a
274 # newly-inserted value
275 $db->delete( 'objectcache',
276 array(
277 'keyname' => $key,
278 'exptime' => $row->exptime
279 ), __METHOD__ );
280 $db->commit();
281 } catch ( DBQueryError $e ) {
282 $this->handleWriteError( $e );
285 return false;
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 ) {
296 $exptime = 0;
299 if ( $exptime == 0 ) {
300 $encExpiry = $this->getMaxDateTime();
301 } else {
302 if ( $exptime < 3.16e8 ) { # ~10 years
303 $exptime += time();
306 $encExpiry = $db->timestamp( $exptime );
308 try {
309 $db->begin();
310 $db->delete( 'objectcache', array( 'keyname' => $key ), __METHOD__ );
311 $db->insert( 'objectcache',
312 array(
313 'keyname' => $key,
314 'value' => $db->encodeBlob( $this->serialize( $value ) ),
315 'exptime' => $encExpiry
316 ), __METHOD__ );
317 $db->commit();
318 } catch ( DBQueryError $e ) {
319 $this->handleWriteError( $e );
321 return false;
324 return true;
327 public function delete( $key, $time = 0 ) {
328 $db = $this->getDB();
330 try {
331 $db->begin();
332 $db->delete( 'objectcache', array( 'keyname' => $key ), __METHOD__ );
333 $db->commit();
334 } catch ( DBQueryError $e ) {
335 $this->handleWriteError( $e );
337 return false;
340 return true;
343 public function incr( $key, $step = 1 ) {
344 $db = $this->getDB();
345 $step = intval( $step );
347 try {
348 $db->begin();
349 $row = $db->selectRow( 'objectcache', array( 'value', 'exptime' ),
350 array( 'keyname' => $key ), __METHOD__, array( 'FOR UPDATE' ) );
351 if ( $row === false ) {
352 // Missing
353 $db->commit();
355 return false;
357 $db->delete( 'objectcache', array( 'keyname' => $key ), __METHOD__ );
358 if ( $this->isExpired( $row->exptime ) ) {
359 // Expired, do not reinsert
360 $db->commit();
362 return false;
365 $oldValue = intval( $this->unserialize( $db->decodeBlob( $row->value ) ) );
366 $newValue = $oldValue + $step;
367 $db->insert( 'objectcache',
368 array(
369 'keyname' => $key,
370 'value' => $db->encodeBlob( $this->serialize( $newValue ) ),
371 'exptime' => $row->exptime
372 ), __METHOD__ );
373 $db->commit();
374 } catch ( DBQueryError $e ) {
375 $this->handleWriteError( $e );
377 return false;
380 return $newValue;
383 public function keys() {
384 $db = $this->getDB();
385 $res = $db->select( 'objectcache', array( 'keyname' ), false, __METHOD__ );
386 $result = array();
388 foreach ( $res as $row ) {
389 $result[] = $row->keyname;
392 return $result;
395 protected function isExpired( $exptime ) {
396 return $exptime != $this->getMaxDateTime() && wfTimestamp( TS_UNIX, $exptime ) < time();
399 protected function getMaxDateTime() {
400 if ( time() > 0x7fffffff ) {
401 return $this->getDB()->timestamp( 1 << 62 );
402 } else {
403 return $this->getDB()->timestamp( 0x7fffffff );
407 protected function garbageCollect() {
408 /* Ignore 99% of requests */
409 if ( !mt_rand( 0, 100 ) ) {
410 $now = time();
411 /* Avoid repeating the delete within a few seconds */
412 if ( $now > ( $this->lastExpireAll + 1 ) ) {
413 $this->lastExpireAll = $now;
414 $this->expireAll();
419 public function expireAll() {
420 $db = $this->getDB();
421 $now = $db->timestamp();
423 try {
424 $db->begin();
425 $db->delete( 'objectcache', array( 'exptime < ' . $db->addQuotes( $now ) ), __METHOD__ );
426 $db->commit();
427 } catch ( DBQueryError $e ) {
428 $this->handleWriteError( $e );
432 public function deleteAll() {
433 $db = $this->getDB();
435 try {
436 $db->begin();
437 $db->delete( 'objectcache', '*', __METHOD__ );
438 $db->commit();
439 } catch ( DBQueryError $e ) {
440 $this->handleWriteError( $e );
445 * Serialize an object and, if possible, compress the representation.
446 * On typical message and page data, this can provide a 3X decrease
447 * in storage requirements.
449 * @param $data mixed
450 * @return string
452 protected function serialize( &$data ) {
453 $serial = serialize( $data );
455 if ( function_exists( 'gzdeflate' ) ) {
456 return gzdeflate( $serial );
457 } else {
458 return $serial;
463 * Unserialize and, if necessary, decompress an object.
464 * @param $serial string
465 * @return mixed
467 protected function unserialize( $serial ) {
468 if ( function_exists( 'gzinflate' ) ) {
469 $decomp = @gzinflate( $serial );
471 if ( false !== $decomp ) {
472 $serial = $decomp;
476 $ret = unserialize( $serial );
478 return $ret;
482 * Handle a DBQueryError which occurred during a write operation.
483 * Ignore errors which are due to a read-only database, rethrow others.
485 protected function handleWriteError( $exception ) {
486 $db = $this->getDB();
488 if ( !$db->wasReadOnlyError() ) {
489 throw $exception;
492 try {
493 $db->rollback();
494 } catch ( DBQueryError $e ) {
497 wfDebug( __METHOD__ . ": ignoring query error\n" );
498 $db->ignoreErrors( false );
503 * Backwards compatibility alias
505 class MediaWikiBagOStuff extends SqlBagOStuff { }
508 * This is a wrapper for APC's shared memory functions
510 * @ingroup Cache
512 class APCBagOStuff extends BagOStuff {
513 public function get( $key ) {
514 $val = apc_fetch( $key );
516 if ( is_string( $val ) ) {
517 $val = unserialize( $val );
520 return $val;
523 public function set( $key, $value, $exptime = 0 ) {
524 apc_store( $key, serialize( $value ), $exptime );
526 return true;
529 public function delete( $key, $time = 0 ) {
530 apc_delete( $key );
532 return true;
535 public function keys() {
536 $info = apc_cache_info( 'user' );
537 $list = $info['cache_list'];
538 $keys = array();
540 foreach ( $list as $entry ) {
541 $keys[] = $entry['info'];
544 return $keys;
549 * This is a wrapper for eAccelerator's shared memory functions.
551 * This is basically identical to the deceased Turck MMCache version,
552 * mostly because eAccelerator is based on Turck MMCache.
554 * @ingroup Cache
556 class eAccelBagOStuff extends BagOStuff {
557 public function get( $key ) {
558 $val = eaccelerator_get( $key );
560 if ( is_string( $val ) ) {
561 $val = unserialize( $val );
564 return $val;
567 public function set( $key, $value, $exptime = 0 ) {
568 eaccelerator_put( $key, serialize( $value ), $exptime );
570 return true;
573 public function delete( $key, $time = 0 ) {
574 eaccelerator_rm( $key );
576 return true;
579 public function lock( $key, $waitTimeout = 0 ) {
580 eaccelerator_lock( $key );
582 return true;
585 public function unlock( $key ) {
586 eaccelerator_unlock( $key );
588 return true;
593 * Wrapper for XCache object caching functions; identical interface
594 * to the APC wrapper
596 * @ingroup Cache
598 class XCacheBagOStuff extends BagOStuff {
600 * Get a value from the XCache object cache
602 * @param $key String: cache key
603 * @return mixed
605 public function get( $key ) {
606 $val = xcache_get( $key );
608 if ( is_string( $val ) ) {
609 $val = unserialize( $val );
612 return $val;
616 * Store a value in the XCache object cache
618 * @param $key String: cache key
619 * @param $value Mixed: object to store
620 * @param $expire Int: expiration time
621 * @return bool
623 public function set( $key, $value, $expire = 0 ) {
624 xcache_set( $key, serialize( $value ), $expire );
626 return true;
630 * Remove a value from the XCache object cache
632 * @param $key String: cache key
633 * @param $time Int: not used in this implementation
634 * @return bool
636 public function delete( $key, $time = 0 ) {
637 xcache_unset( $key );
639 return true;
644 * Cache that uses DBA as a backend.
645 * Slow due to the need to constantly open and close the file to avoid holding
646 * writer locks. Intended for development use only, as a memcached workalike
647 * for systems that don't have it.
649 * @ingroup Cache
651 class DBABagOStuff extends BagOStuff {
652 var $mHandler, $mFile, $mReader, $mWriter, $mDisabled;
654 public function __construct( $dir = false ) {
655 global $wgDBAhandler;
657 if ( $dir === false ) {
658 global $wgTmpDirectory;
659 $dir = $wgTmpDirectory;
662 $this->mFile = "$dir/mw-cache-" . wfWikiID();
663 $this->mFile .= '.db';
664 wfDebug( __CLASS__ . ": using cache file {$this->mFile}\n" );
665 $this->mHandler = $wgDBAhandler;
669 * Encode value and expiry for storage
671 function encode( $value, $expiry ) {
672 # Convert to absolute time
673 $expiry = $this->convertExpiry( $expiry );
675 return sprintf( '%010u', intval( $expiry ) ) . ' ' . serialize( $value );
679 * @return list containing value first and expiry second
681 function decode( $blob ) {
682 if ( !is_string( $blob ) ) {
683 return array( null, 0 );
684 } else {
685 return array(
686 unserialize( substr( $blob, 11 ) ),
687 intval( substr( $blob, 0, 10 ) )
692 function getReader() {
693 if ( file_exists( $this->mFile ) ) {
694 $handle = dba_open( $this->mFile, 'rl', $this->mHandler );
695 } else {
696 $handle = $this->getWriter();
699 if ( !$handle ) {
700 wfDebug( "Unable to open DBA cache file {$this->mFile}\n" );
703 return $handle;
706 function getWriter() {
707 $handle = dba_open( $this->mFile, 'cl', $this->mHandler );
709 if ( !$handle ) {
710 wfDebug( "Unable to open DBA cache file {$this->mFile}\n" );
713 return $handle;
716 function get( $key ) {
717 wfProfileIn( __METHOD__ );
718 wfDebug( __METHOD__ . "($key)\n" );
720 $handle = $this->getReader();
721 if ( !$handle ) {
722 return null;
725 $val = dba_fetch( $key, $handle );
726 list( $val, $expiry ) = $this->decode( $val );
728 # Must close ASAP because locks are held
729 dba_close( $handle );
731 if ( !is_null( $val ) && $expiry && $expiry < time() ) {
732 # Key is expired, delete it
733 $handle = $this->getWriter();
734 dba_delete( $key, $handle );
735 dba_close( $handle );
736 wfDebug( __METHOD__ . ": $key expired\n" );
737 $val = null;
740 wfProfileOut( __METHOD__ );
741 return $val;
744 function set( $key, $value, $exptime = 0 ) {
745 wfProfileIn( __METHOD__ );
746 wfDebug( __METHOD__ . "($key)\n" );
748 $blob = $this->encode( $value, $exptime );
750 $handle = $this->getWriter();
751 if ( !$handle ) {
752 return false;
755 $ret = dba_replace( $key, $blob, $handle );
756 dba_close( $handle );
758 wfProfileOut( __METHOD__ );
759 return $ret;
762 function delete( $key, $time = 0 ) {
763 wfProfileIn( __METHOD__ );
764 wfDebug( __METHOD__ . "($key)\n" );
766 $handle = $this->getWriter();
767 if ( !$handle ) {
768 return false;
771 $ret = dba_delete( $key, $handle );
772 dba_close( $handle );
774 wfProfileOut( __METHOD__ );
775 return $ret;
778 function add( $key, $value, $exptime = 0 ) {
779 wfProfileIn( __METHOD__ );
781 $blob = $this->encode( $value, $exptime );
783 $handle = $this->getWriter();
785 if ( !$handle ) {
786 return false;
789 $ret = dba_insert( $key, $blob, $handle );
791 # Insert failed, check to see if it failed due to an expired key
792 if ( !$ret ) {
793 list( $value, $expiry ) = $this->decode( dba_fetch( $key, $handle ) );
795 if ( $expiry < time() ) {
796 # Yes expired, delete and try again
797 dba_delete( $key, $handle );
798 $ret = dba_insert( $key, $blob, $handle );
799 # This time if it failed then it will be handled by the caller like any other race
803 dba_close( $handle );
805 wfProfileOut( __METHOD__ );
806 return $ret;
809 function keys() {
810 $reader = $this->getReader();
811 $k1 = dba_firstkey( $reader );
813 if ( !$k1 ) {
814 return array();
817 $result[] = $k1;
819 while ( $key = dba_nextkey( $reader ) ) {
820 $result[] = $key;
823 return $result;
828 * Wrapper for WinCache object caching functions; identical interface
829 * to the APC wrapper
831 * @ingroup Cache
833 class WinCacheBagOStuff extends BagOStuff {
836 * Get a value from the WinCache object cache
838 * @param $key String: cache key
839 * @return mixed
841 public function get( $key ) {
842 $val = wincache_ucache_get( $key );
844 if ( is_string( $val ) ) {
845 $val = unserialize( $val );
848 return $val;
852 * Store a value in the WinCache object cache
854 * @param $key String: cache key
855 * @param $value Mixed: object to store
856 * @param $expire Int: expiration time
857 * @return bool
859 public function set( $key, $value, $expire = 0 ) {
860 wincache_ucache_set( $key, serialize( $value ), $expire );
862 return true;
866 * Remove a value from the WinCache object cache
868 * @param $key String: cache key
869 * @param $time Int: not used in this implementation
870 * @return bool
872 public function delete( $key, $time = 0 ) {
873 wincache_ucache_delete( $key );
875 return true;
878 public function keys() {
879 $info = wincache_ucache_info();
880 $list = $info['ucache_entries'];
881 $keys = array();
883 foreach ( $list as $entry ) {
884 $keys[] = $entry['key_name'];
887 return $keys;