Preserve Special:Preferences tab state across reload, open in new tab/window.
[mediawiki.git] / includes / BagOStuff.php
blob7f400013331c2f5bd532c224e5cbade38beafd8f
1 <?php
2 /**
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
23 * @file
24 * @ingroup Cache
27 /**
28 * @defgroup Cache Cache
31 /**
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:
36 * <code>
37 * $bag = new HashBagOStuff();
38 * $bag = new SqlBagOStuff(); # connect to db first
39 * </code>
41 * @ingroup Cache
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 */
53 /**
54 * Get an item with the given key. Returns false if it does not exist.
55 * @param $key string
57 abstract public function get( $key );
59 /**
60 * Set an item.
61 * @param $key string
62 * @param $value mixed
63 * @param $exptime int Either an interval in seconds or a unix timestamp for expiry
65 abstract public function set( $key, $value, $exptime = 0 );
68 * Delete an item.
69 * @param $key string
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 ) {
75 /* stub */
76 return true;
79 public function unlock( $key ) {
80 /* stub */
81 return true;
84 public function keys() {
85 /* stub */
86 return array();
89 /* *** Emulated functions *** */
90 /* Better performance can likely be got with custom written versions */
91 public function get_multi( $keys ) {
92 $out = array();
94 foreach ( $keys as $key ) {
95 $out[$key] = $this->get( $key );
98 return $out;
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 );
111 return true;
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 );
134 * @param $key String: Key to increase
135 * @param $value Integer: Value to add to $key (Default 1)
136 * @return null if lock is not possible else $key value increased by $value
138 public function incr( $key, $value = 1 ) {
139 if ( !$this->lock( $key ) ) {
140 return null;
143 $value = intval( $value );
145 if ( ( $n = $this->get( $key ) ) !== false ) {
146 $n += $value;
147 $this->set( $key, $n ); // exptime?
149 $this->unlock( $key );
151 return $n;
154 public function decr( $key, $value = 1 ) {
155 return $this->incr( $key, - $value );
158 public function debug( $text ) {
159 if ( $this->debugMode ) {
160 wfDebug( "BagOStuff debug: $text\n" );
165 * Convert an optionally relative time to an absolute time
167 protected function convertExpiry( $exptime ) {
168 if ( ( $exptime != 0 ) && ( $exptime < 86400 * 3650 /* 10 years */ ) ) {
169 return time() + $exptime;
170 } else {
171 return $exptime;
177 * Functional versions!
178 * This is a test of the interface, mainly. It stores things in an associative
179 * array, which is not going to persist between program runs.
181 * @ingroup Cache
183 class HashBagOStuff extends BagOStuff {
184 var $bag;
186 function __construct() {
187 $this->bag = array();
190 protected function expire( $key ) {
191 $et = $this->bag[$key][1];
193 if ( ( $et == 0 ) || ( $et > time() ) ) {
194 return false;
197 $this->delete( $key );
199 return true;
202 function get( $key ) {
203 if ( !isset( $this->bag[$key] ) ) {
204 return false;
207 if ( $this->expire( $key ) ) {
208 return false;
211 return $this->bag[$key][0];
214 function set( $key, $value, $exptime = 0 ) {
215 $this->bag[$key] = array( $value, $this->convertExpiry( $exptime ) );
218 function delete( $key, $time = 0 ) {
219 if ( !isset( $this->bag[$key] ) ) {
220 return false;
223 unset( $this->bag[$key] );
225 return true;
228 function keys() {
229 return array_keys( $this->bag );
234 * Class to store objects in the database
236 * @ingroup Cache
238 class SqlBagOStuff extends BagOStuff {
239 var $lb, $db;
240 var $lastExpireAll = 0;
242 protected function getDB() {
243 if ( !isset( $this->db ) ) {
244 /* We must keep a separate connection to MySQL in order to avoid deadlocks
245 * However, SQLite has an opposite behaviour.
246 * @todo Investigate behaviour for other databases
248 if ( wfGetDB( DB_MASTER )->getType() == 'sqlite' ) {
249 $this->db = wfGetDB( DB_MASTER );
250 } else {
251 $this->lb = wfGetLBFactory()->newMainLB();
252 $this->db = $this->lb->getConnection( DB_MASTER );
253 $this->db->clearFlag( DBO_TRX );
257 return $this->db;
260 public function get( $key ) {
261 # expire old entries if any
262 $this->garbageCollect();
263 $db = $this->getDB();
264 $row = $db->selectRow( 'objectcache', array( 'value', 'exptime' ),
265 array( 'keyname' => $key ), __METHOD__ );
267 if ( !$row ) {
268 $this->debug( 'get: no matching rows' );
269 return false;
272 $this->debug( "get: retrieved data; expiry time is " . $row->exptime );
274 if ( $this->isExpired( $row->exptime ) ) {
275 $this->debug( "get: key has expired, deleting" );
276 try {
277 $db->begin();
278 # Put the expiry time in the WHERE condition to avoid deleting a
279 # newly-inserted value
280 $db->delete( 'objectcache',
281 array(
282 'keyname' => $key,
283 'exptime' => $row->exptime
284 ), __METHOD__ );
285 $db->commit();
286 } catch ( DBQueryError $e ) {
287 $this->handleWriteError( $e );
290 return false;
293 return $this->unserialize( $db->decodeBlob( $row->value ) );
296 public function set( $key, $value, $exptime = 0 ) {
297 $db = $this->getDB();
298 $exptime = intval( $exptime );
300 if ( $exptime < 0 ) {
301 $exptime = 0;
304 if ( $exptime == 0 ) {
305 $encExpiry = $this->getMaxDateTime();
306 } else {
307 if ( $exptime < 3.16e8 ) { # ~10 years
308 $exptime += time();
311 $encExpiry = $db->timestamp( $exptime );
313 try {
314 $db->begin();
315 // (bug 24425) use a replace if the db supports it instead of
316 // delete/insert to avoid clashes with conflicting keynames
317 $db->replace( 'objectcache', array( 'keyname' ),
318 array(
319 'keyname' => $key,
320 'value' => $db->encodeBlob( $this->serialize( $value ) ),
321 'exptime' => $encExpiry
322 ), __METHOD__ );
323 $db->commit();
324 } catch ( DBQueryError $e ) {
325 $this->handleWriteError( $e );
327 return false;
330 return true;
333 public function delete( $key, $time = 0 ) {
334 $db = $this->getDB();
336 try {
337 $db->begin();
338 $db->delete( 'objectcache', array( 'keyname' => $key ), __METHOD__ );
339 $db->commit();
340 } catch ( DBQueryError $e ) {
341 $this->handleWriteError( $e );
343 return false;
346 return true;
349 public function incr( $key, $step = 1 ) {
350 $db = $this->getDB();
351 $step = intval( $step );
353 try {
354 $db->begin();
355 $row = $db->selectRow( 'objectcache', array( 'value', 'exptime' ),
356 array( 'keyname' => $key ), __METHOD__, array( 'FOR UPDATE' ) );
357 if ( $row === false ) {
358 // Missing
359 $db->commit();
361 return null;
363 $db->delete( 'objectcache', array( 'keyname' => $key ), __METHOD__ );
364 if ( $this->isExpired( $row->exptime ) ) {
365 // Expired, do not reinsert
366 $db->commit();
368 return null;
371 $oldValue = intval( $this->unserialize( $db->decodeBlob( $row->value ) ) );
372 $newValue = $oldValue + $step;
373 $db->insert( 'objectcache',
374 array(
375 'keyname' => $key,
376 'value' => $db->encodeBlob( $this->serialize( $newValue ) ),
377 'exptime' => $row->exptime
378 ), __METHOD__ );
379 $db->commit();
380 } catch ( DBQueryError $e ) {
381 $this->handleWriteError( $e );
383 return null;
386 return $newValue;
389 public function keys() {
390 $db = $this->getDB();
391 $res = $db->select( 'objectcache', array( 'keyname' ), false, __METHOD__ );
392 $result = array();
394 foreach ( $res as $row ) {
395 $result[] = $row->keyname;
398 return $result;
401 protected function isExpired( $exptime ) {
402 return $exptime != $this->getMaxDateTime() && wfTimestamp( TS_UNIX, $exptime ) < time();
405 protected function getMaxDateTime() {
406 if ( time() > 0x7fffffff ) {
407 return $this->getDB()->timestamp( 1 << 62 );
408 } else {
409 return $this->getDB()->timestamp( 0x7fffffff );
413 protected function garbageCollect() {
414 /* Ignore 99% of requests */
415 if ( !mt_rand( 0, 100 ) ) {
416 $now = time();
417 /* Avoid repeating the delete within a few seconds */
418 if ( $now > ( $this->lastExpireAll + 1 ) ) {
419 $this->lastExpireAll = $now;
420 $this->expireAll();
425 public function expireAll() {
426 $db = $this->getDB();
427 $now = $db->timestamp();
429 try {
430 $db->begin();
431 $db->delete( 'objectcache', array( 'exptime < ' . $db->addQuotes( $now ) ), __METHOD__ );
432 $db->commit();
433 } catch ( DBQueryError $e ) {
434 $this->handleWriteError( $e );
438 public function deleteAll() {
439 $db = $this->getDB();
441 try {
442 $db->begin();
443 $db->delete( 'objectcache', '*', __METHOD__ );
444 $db->commit();
445 } catch ( DBQueryError $e ) {
446 $this->handleWriteError( $e );
451 * Serialize an object and, if possible, compress the representation.
452 * On typical message and page data, this can provide a 3X decrease
453 * in storage requirements.
455 * @param $data mixed
456 * @return string
458 protected function serialize( &$data ) {
459 $serial = serialize( $data );
461 if ( function_exists( 'gzdeflate' ) ) {
462 return gzdeflate( $serial );
463 } else {
464 return $serial;
469 * Unserialize and, if necessary, decompress an object.
470 * @param $serial string
471 * @return mixed
473 protected function unserialize( $serial ) {
474 if ( function_exists( 'gzinflate' ) ) {
475 $decomp = @gzinflate( $serial );
477 if ( false !== $decomp ) {
478 $serial = $decomp;
482 $ret = unserialize( $serial );
484 return $ret;
488 * Handle a DBQueryError which occurred during a write operation.
489 * Ignore errors which are due to a read-only database, rethrow others.
491 protected function handleWriteError( $exception ) {
492 $db = $this->getDB();
494 if ( !$db->wasReadOnlyError() ) {
495 throw $exception;
498 try {
499 $db->rollback();
500 } catch ( DBQueryError $e ) {
503 wfDebug( __METHOD__ . ": ignoring query error\n" );
504 $db->ignoreErrors( false );
509 * Backwards compatibility alias
511 class MediaWikiBagOStuff extends SqlBagOStuff { }
514 * This is a wrapper for APC's shared memory functions
516 * @ingroup Cache
518 class APCBagOStuff extends BagOStuff {
519 public function get( $key ) {
520 $val = apc_fetch( $key );
522 if ( is_string( $val ) ) {
523 $val = unserialize( $val );
526 return $val;
529 public function set( $key, $value, $exptime = 0 ) {
530 apc_store( $key, serialize( $value ), $exptime );
532 return true;
535 public function delete( $key, $time = 0 ) {
536 apc_delete( $key );
538 return true;
541 public function keys() {
542 $info = apc_cache_info( 'user' );
543 $list = $info['cache_list'];
544 $keys = array();
546 foreach ( $list as $entry ) {
547 $keys[] = $entry['info'];
550 return $keys;
555 * This is a wrapper for eAccelerator's shared memory functions.
557 * This is basically identical to the deceased Turck MMCache version,
558 * mostly because eAccelerator is based on Turck MMCache.
560 * @ingroup Cache
562 class eAccelBagOStuff extends BagOStuff {
563 public function get( $key ) {
564 $val = eaccelerator_get( $key );
566 if ( is_string( $val ) ) {
567 $val = unserialize( $val );
570 return $val;
573 public function set( $key, $value, $exptime = 0 ) {
574 eaccelerator_put( $key, serialize( $value ), $exptime );
576 return true;
579 public function delete( $key, $time = 0 ) {
580 eaccelerator_rm( $key );
582 return true;
585 public function lock( $key, $waitTimeout = 0 ) {
586 eaccelerator_lock( $key );
588 return true;
591 public function unlock( $key ) {
592 eaccelerator_unlock( $key );
594 return true;
599 * Wrapper for XCache object caching functions; identical interface
600 * to the APC wrapper
602 * @ingroup Cache
604 class XCacheBagOStuff extends BagOStuff {
606 * Get a value from the XCache object cache
608 * @param $key String: cache key
609 * @return mixed
611 public function get( $key ) {
612 $val = xcache_get( $key );
614 if ( is_string( $val ) ) {
615 $val = unserialize( $val );
618 return $val;
622 * Store a value in the XCache object cache
624 * @param $key String: cache key
625 * @param $value Mixed: object to store
626 * @param $expire Int: expiration time
627 * @return bool
629 public function set( $key, $value, $expire = 0 ) {
630 xcache_set( $key, serialize( $value ), $expire );
632 return true;
636 * Remove a value from the XCache object cache
638 * @param $key String: cache key
639 * @param $time Int: not used in this implementation
640 * @return bool
642 public function delete( $key, $time = 0 ) {
643 xcache_unset( $key );
645 return true;
650 * Cache that uses DBA as a backend.
651 * Slow due to the need to constantly open and close the file to avoid holding
652 * writer locks. Intended for development use only, as a memcached workalike
653 * for systems that don't have it.
655 * @ingroup Cache
657 class DBABagOStuff extends BagOStuff {
658 var $mHandler, $mFile, $mReader, $mWriter, $mDisabled;
660 public function __construct( $dir = false ) {
661 global $wgDBAhandler;
663 if ( $dir === false ) {
664 global $wgTmpDirectory;
665 $dir = $wgTmpDirectory;
668 $this->mFile = "$dir/mw-cache-" . wfWikiID();
669 $this->mFile .= '.db';
670 wfDebug( __CLASS__ . ": using cache file {$this->mFile}\n" );
671 $this->mHandler = $wgDBAhandler;
675 * Encode value and expiry for storage
677 function encode( $value, $expiry ) {
678 # Convert to absolute time
679 $expiry = $this->convertExpiry( $expiry );
681 return sprintf( '%010u', intval( $expiry ) ) . ' ' . serialize( $value );
685 * @return list containing value first and expiry second
687 function decode( $blob ) {
688 if ( !is_string( $blob ) ) {
689 return array( null, 0 );
690 } else {
691 return array(
692 unserialize( substr( $blob, 11 ) ),
693 intval( substr( $blob, 0, 10 ) )
698 function getReader() {
699 if ( file_exists( $this->mFile ) ) {
700 $handle = dba_open( $this->mFile, 'rl', $this->mHandler );
701 } else {
702 $handle = $this->getWriter();
705 if ( !$handle ) {
706 wfDebug( "Unable to open DBA cache file {$this->mFile}\n" );
709 return $handle;
712 function getWriter() {
713 $handle = dba_open( $this->mFile, 'cl', $this->mHandler );
715 if ( !$handle ) {
716 wfDebug( "Unable to open DBA cache file {$this->mFile}\n" );
719 return $handle;
722 function get( $key ) {
723 wfProfileIn( __METHOD__ );
724 wfDebug( __METHOD__ . "($key)\n" );
726 $handle = $this->getReader();
727 if ( !$handle ) {
728 return null;
731 $val = dba_fetch( $key, $handle );
732 list( $val, $expiry ) = $this->decode( $val );
734 # Must close ASAP because locks are held
735 dba_close( $handle );
737 if ( !is_null( $val ) && $expiry && $expiry < time() ) {
738 # Key is expired, delete it
739 $handle = $this->getWriter();
740 dba_delete( $key, $handle );
741 dba_close( $handle );
742 wfDebug( __METHOD__ . ": $key expired\n" );
743 $val = null;
746 wfProfileOut( __METHOD__ );
747 return $val;
750 function set( $key, $value, $exptime = 0 ) {
751 wfProfileIn( __METHOD__ );
752 wfDebug( __METHOD__ . "($key)\n" );
754 $blob = $this->encode( $value, $exptime );
756 $handle = $this->getWriter();
757 if ( !$handle ) {
758 return false;
761 $ret = dba_replace( $key, $blob, $handle );
762 dba_close( $handle );
764 wfProfileOut( __METHOD__ );
765 return $ret;
768 function delete( $key, $time = 0 ) {
769 wfProfileIn( __METHOD__ );
770 wfDebug( __METHOD__ . "($key)\n" );
772 $handle = $this->getWriter();
773 if ( !$handle ) {
774 return false;
777 $ret = dba_delete( $key, $handle );
778 dba_close( $handle );
780 wfProfileOut( __METHOD__ );
781 return $ret;
784 function add( $key, $value, $exptime = 0 ) {
785 wfProfileIn( __METHOD__ );
787 $blob = $this->encode( $value, $exptime );
789 $handle = $this->getWriter();
791 if ( !$handle ) {
792 return false;
795 $ret = dba_insert( $key, $blob, $handle );
797 # Insert failed, check to see if it failed due to an expired key
798 if ( !$ret ) {
799 list( $value, $expiry ) = $this->decode( dba_fetch( $key, $handle ) );
801 if ( $expiry < time() ) {
802 # Yes expired, delete and try again
803 dba_delete( $key, $handle );
804 $ret = dba_insert( $key, $blob, $handle );
805 # This time if it failed then it will be handled by the caller like any other race
809 dba_close( $handle );
811 wfProfileOut( __METHOD__ );
812 return $ret;
815 function keys() {
816 $reader = $this->getReader();
817 $k1 = dba_firstkey( $reader );
819 if ( !$k1 ) {
820 return array();
823 $result[] = $k1;
825 while ( $key = dba_nextkey( $reader ) ) {
826 $result[] = $key;
829 return $result;
834 * Wrapper for WinCache object caching functions; identical interface
835 * to the APC wrapper
837 * @ingroup Cache
839 class WinCacheBagOStuff extends BagOStuff {
842 * Get a value from the WinCache object cache
844 * @param $key String: cache key
845 * @return mixed
847 public function get( $key ) {
848 $val = wincache_ucache_get( $key );
850 if ( is_string( $val ) ) {
851 $val = unserialize( $val );
854 return $val;
858 * Store a value in the WinCache object cache
860 * @param $key String: cache key
861 * @param $value Mixed: object to store
862 * @param $expire Int: expiration time
863 * @return bool
865 public function set( $key, $value, $expire = 0 ) {
866 $result = wincache_ucache_set( $key, serialize( $value ), $expire );
868 /* wincache_ucache_set returns an empty array on success if $value
869 was an array, bool otherwise */
870 return ( is_array( $result ) && $result === array() ) || $result;
874 * Remove a value from the WinCache object cache
876 * @param $key String: cache key
877 * @param $time Int: not used in this implementation
878 * @return bool
880 public function delete( $key, $time = 0 ) {
881 wincache_ucache_delete( $key );
883 return true;
886 public function keys() {
887 $info = wincache_ucache_info();
888 $list = $info['ucache_entries'];
889 $keys = array();
891 if ( is_null( $list ) ) {
892 return array();
895 foreach ( $list as $entry ) {
896 $keys[] = $entry['key_name'];
899 return $keys;