Implement keys() for APCBagOStuff
[mediawiki.git] / includes / BagOStuff.php
blobd940028b5dd0ea42676a04ab942431b6d310b3a8
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();
90 foreach ( $keys as $key ) {
91 $out[$key] = $this->get( $key );
93 return $out;
96 public function set_multi( $hash, $exptime = 0 ) {
97 foreach ( $hash as $key => $value ) {
98 $this->set( $key, $value, $exptime );
102 public function add( $key, $value, $exptime = 0 ) {
103 if ( $this->get( $key ) == false ) {
104 $this->set( $key, $value, $exptime );
105 return true;
109 public function add_multi( $hash, $exptime = 0 ) {
110 foreach ( $hash as $key => $value ) {
111 $this->add( $key, $value, $exptime );
115 public function delete_multi( $keys, $time = 0 ) {
116 foreach ( $keys as $key ) {
117 $this->delete( $key, $time );
121 public function replace( $key, $value, $exptime = 0 ) {
122 if ( $this->get( $key ) !== false ) {
123 $this->set( $key, $value, $exptime );
127 public function incr( $key, $value = 1 ) {
128 if ( !$this->lock( $key ) ) {
129 return false;
131 $value = intval( $value );
133 $n = false;
134 if ( ( $n = $this->get( $key ) ) !== false ) {
135 $n += $value;
136 $this->set( $key, $n ); // exptime?
138 $this->unlock( $key );
139 return $n;
142 public function decr( $key, $value = 1 ) {
143 return $this->incr( $key, -$value );
146 public function debug( $text ) {
147 if ( $this->debugMode )
148 wfDebug( "BagOStuff debug: $text\n" );
152 * Convert an optionally relative time to an absolute time
154 protected function convertExpiry( $exptime ) {
155 if ( ( $exptime != 0 ) && ( $exptime < 3600 * 24 * 30 ) ) {
156 return time() + $exptime;
157 } else {
158 return $exptime;
165 * Functional versions!
166 * This is a test of the interface, mainly. It stores things in an associative
167 * array, which is not going to persist between program runs.
169 * @ingroup Cache
171 class HashBagOStuff extends BagOStuff {
172 var $bag;
174 function __construct() {
175 $this->bag = array();
178 protected function expire( $key ) {
179 $et = $this->bag[$key][1];
180 if ( ( $et == 0 ) || ( $et > time() ) ) {
181 return false;
183 $this->delete( $key );
184 return true;
187 function get( $key ) {
188 if ( !isset( $this->bag[$key] ) ) {
189 return false;
191 if ( $this->expire( $key ) ) {
192 return false;
194 return $this->bag[$key][0];
197 function set( $key, $value, $exptime = 0 ) {
198 $this->bag[$key] = array( $value, $this->convertExpiry( $exptime ) );
201 function delete( $key, $time = 0 ) {
202 if ( !isset( $this->bag[$key] ) ) {
203 return false;
205 unset( $this->bag[$key] );
206 return true;
209 function keys() {
210 return array_keys( $this->bag );
215 * Class to store objects in the database
217 * @ingroup Cache
219 class SqlBagOStuff extends BagOStuff {
220 var $lb, $db;
221 var $lastExpireAll = 0;
223 protected function getDB() {
224 global $wgDBtype;
225 if ( !isset( $this->db ) ) {
226 /* We must keep a separate connection to MySQL in order to avoid deadlocks
227 * However, SQLite has an opposite behaviour.
228 * @todo Investigate behaviour for other databases
230 if ( $wgDBtype == 'sqlite' ) {
231 $this->db = wfGetDB( DB_MASTER );
232 } else {
233 $this->lb = wfGetLBFactory()->newMainLB();
234 $this->db = $this->lb->getConnection( DB_MASTER );
235 $this->db->clearFlag( DBO_TRX );
238 return $this->db;
241 public function get( $key ) {
242 # expire old entries if any
243 $this->garbageCollect();
244 $db = $this->getDB();
245 $row = $db->selectRow( 'objectcache', array( 'value', 'exptime' ),
246 array( 'keyname' => $key ), __METHOD__ );
247 if ( !$row ) {
248 $this->debug( 'get: no matching rows' );
249 return false;
252 $this->debug( "get: retrieved data; expiry time is " . $row->exptime );
253 if ( $this->isExpired( $row->exptime ) ) {
254 $this->debug( "get: key has expired, deleting" );
255 try {
256 $db->begin();
257 # Put the expiry time in the WHERE condition to avoid deleting a
258 # newly-inserted value
259 $db->delete( 'objectcache',
260 array(
261 'keyname' => $key,
262 'exptime' => $row->exptime
263 ), __METHOD__ );
264 $db->commit();
265 } catch ( DBQueryError $e ) {
266 $this->handleWriteError( $e );
268 return false;
270 return $this->unserialize( $db->decodeBlob( $row->value ) );
273 public function set( $key, $value, $exptime = 0 ) {
274 $db = $this->getDB();
275 $exptime = intval( $exptime );
276 if ( $exptime < 0 ) $exptime = 0;
277 if ( $exptime == 0 ) {
278 $encExpiry = $this->getMaxDateTime();
279 } else {
280 if ( $exptime < 3.16e8 ) # ~10 years
281 $exptime += time();
282 $encExpiry = $db->timestamp( $exptime );
284 try {
285 $db->begin();
286 $db->delete( 'objectcache', array( 'keyname' => $key ), __METHOD__ );
287 $db->insert( 'objectcache',
288 array(
289 'keyname' => $key,
290 'value' => $db->encodeBlob( $this->serialize( $value ) ),
291 'exptime' => $encExpiry
292 ), __METHOD__ );
293 $db->commit();
294 } catch ( DBQueryError $e ) {
295 $this->handleWriteError( $e );
296 return false;
298 return true;
301 public function delete( $key, $time = 0 ) {
302 $db = $this->getDB();
303 try {
304 $db->begin();
305 $db->delete( 'objectcache', array( 'keyname' => $key ), __METHOD__ );
306 $db->commit();
307 } catch ( DBQueryError $e ) {
308 $this->handleWriteError( $e );
309 return false;
311 return true;
314 public function incr( $key, $step = 1 ) {
315 $db = $this->getDB();
316 $step = intval( $step );
318 try {
319 $db->begin();
320 $row = $db->selectRow( 'objectcache', array( 'value', 'exptime' ),
321 array( 'keyname' => $key ), __METHOD__, array( 'FOR UPDATE' ) );
322 if ( $row === false ) {
323 // Missing
324 $db->commit();
325 return false;
327 $db->delete( 'objectcache', array( 'keyname' => $key ), __METHOD__ );
328 if ( $this->isExpired( $row->exptime ) ) {
329 // Expired, do not reinsert
330 $db->commit();
331 return false;
334 $oldValue = intval( $this->unserialize( $db->decodeBlob( $row->value ) ) );
335 $newValue = $oldValue + $step;
336 $db->insert( 'objectcache',
337 array(
338 'keyname' => $key,
339 'value' => $db->encodeBlob( $this->serialize( $newValue ) ),
340 'exptime' => $row->exptime
341 ), __METHOD__ );
342 $db->commit();
343 } catch ( DBQueryError $e ) {
344 $this->handleWriteError( $e );
345 return false;
347 return $newValue;
350 public function keys() {
351 $db = $this->getDB();
352 $res = $db->select( 'objectcache', array( 'keyname' ), false, __METHOD__ );
353 $result = array();
354 foreach ( $res as $row ) {
355 $result[] = $row->keyname;
357 return $result;
360 protected function isExpired( $exptime ) {
361 return $exptime != $this->getMaxDateTime() && wfTimestamp( TS_UNIX, $exptime ) < time();
364 protected function getMaxDateTime() {
365 if ( time() > 0x7fffffff ) {
366 return $this->getDB()->timestamp( 1 << 62 );
367 } else {
368 return $this->getDB()->timestamp( 0x7fffffff );
372 protected function garbageCollect() {
373 /* Ignore 99% of requests */
374 if ( !mt_rand( 0, 100 ) ) {
375 $now = time();
376 /* Avoid repeating the delete within a few seconds */
377 if ( $now > ( $this->lastExpireAll + 1 ) ) {
378 $this->lastExpireAll = $now;
379 $this->expireAll();
384 public function expireAll() {
385 $db = $this->getDB();
386 $now = $db->timestamp();
387 try {
388 $db->begin();
389 $db->delete( 'objectcache', array( 'exptime < ' . $db->addQuotes( $now ) ), __METHOD__ );
390 $db->commit();
391 } catch ( DBQueryError $e ) {
392 $this->handleWriteError( $e );
396 public function deleteAll() {
397 $db = $this->getDB();
398 try {
399 $db->begin();
400 $db->delete( 'objectcache', '*', __METHOD__ );
401 $db->commit();
402 } catch ( DBQueryError $e ) {
403 $this->handleWriteError( $e );
408 * Serialize an object and, if possible, compress the representation.
409 * On typical message and page data, this can provide a 3X decrease
410 * in storage requirements.
412 * @param $data mixed
413 * @return string
415 protected function serialize( &$data ) {
416 $serial = serialize( $data );
417 if ( function_exists( 'gzdeflate' ) ) {
418 return gzdeflate( $serial );
419 } else {
420 return $serial;
425 * Unserialize and, if necessary, decompress an object.
426 * @param $serial string
427 * @return mixed
429 protected function unserialize( $serial ) {
430 if ( function_exists( 'gzinflate' ) ) {
431 $decomp = @gzinflate( $serial );
432 if ( false !== $decomp ) {
433 $serial = $decomp;
436 $ret = unserialize( $serial );
437 return $ret;
441 * Handle a DBQueryError which occurred during a write operation.
442 * Ignore errors which are due to a read-only database, rethrow others.
444 protected function handleWriteError( $exception ) {
445 $db = $this->getDB();
446 if ( !$db->wasReadOnlyError() ) {
447 throw $exception;
449 try {
450 $db->rollback();
451 } catch ( DBQueryError $e ) {
453 wfDebug( __METHOD__ . ": ignoring query error\n" );
454 $db->ignoreErrors( false );
459 * Backwards compatibility alias
461 class MediaWikiBagOStuff extends SqlBagOStuff {}
464 * This is a wrapper for Turck MMCache's shared memory functions.
466 * You can store objects with mmcache_put() and mmcache_get(), but Turck seems
467 * to use a weird custom serializer that randomly segfaults. So we wrap calls
468 * with serialize()/unserialize().
470 * The thing I noticed about the Turck serialized data was that unlike ordinary
471 * serialize(), it contained the names of methods, and judging by the amount of
472 * binary data, perhaps even the bytecode of the methods themselves. It may be
473 * that Turck's serializer is faster, so a possible future extension would be
474 * to use it for arrays but not for objects.
476 * @ingroup Cache
478 class TurckBagOStuff extends BagOStuff {
479 public function get( $key ) {
480 $val = mmcache_get( $key );
481 if ( is_string( $val ) ) {
482 $val = unserialize( $val );
484 return $val;
487 public function set( $key, $value, $exptime = 0 ) {
488 mmcache_put( $key, serialize( $value ), $exptime );
489 return true;
492 public function delete( $key, $time = 0 ) {
493 mmcache_rm( $key );
494 return true;
497 public function lock( $key, $waitTimeout = 0 ) {
498 mmcache_lock( $key );
499 return true;
502 public function unlock( $key ) {
503 mmcache_unlock( $key );
504 return true;
509 * This is a wrapper for APC's shared memory functions
511 * @ingroup Cache
513 class APCBagOStuff extends BagOStuff {
514 public function get( $key ) {
515 $val = apc_fetch( $key );
516 if ( is_string( $val ) ) {
517 $val = unserialize( $val );
519 return $val;
522 public function set( $key, $value, $exptime = 0 ) {
523 apc_store( $key, serialize( $value ), $exptime );
524 return true;
527 public function delete( $key, $time = 0 ) {
528 apc_delete( $key );
529 return true;
532 public function keys() {
533 $info = apc_cache_info( 'user' );
534 $list = $info['cache_list'];
535 $keys = array();
536 foreach( $list as $entry ) {
537 $keys[] = $entry['info'];
539 return $keys;
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.
550 * @ingroup Cache
552 class eAccelBagOStuff extends BagOStuff {
553 public function get( $key ) {
554 $val = eaccelerator_get( $key );
555 if ( is_string( $val ) ) {
556 $val = unserialize( $val );
558 return $val;
561 public function set( $key, $value, $exptime = 0 ) {
562 eaccelerator_put( $key, serialize( $value ), $exptime );
563 return true;
566 public function delete( $key, $time = 0 ) {
567 eaccelerator_rm( $key );
568 return true;
571 public function lock( $key, $waitTimeout = 0 ) {
572 eaccelerator_lock( $key );
573 return true;
576 public function unlock( $key ) {
577 eaccelerator_unlock( $key );
578 return true;
583 * Wrapper for XCache object caching functions; identical interface
584 * to the APC wrapper
586 * @ingroup Cache
588 class XCacheBagOStuff extends BagOStuff {
591 * Get a value from the XCache object cache
593 * @param $key String: cache key
594 * @return mixed
596 public function get( $key ) {
597 $val = xcache_get( $key );
598 if ( is_string( $val ) )
599 $val = unserialize( $val );
600 return $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
609 * @return bool
611 public function set( $key, $value, $expire = 0 ) {
612 xcache_set( $key, serialize( $value ), $expire );
613 return true;
617 * Remove a value from the XCache object cache
619 * @param $key String: cache key
620 * @param $time Int: not used in this implementation
621 * @return bool
623 public function delete( $key, $time = 0 ) {
624 xcache_unset( $key );
625 return true;
631 * Cache that uses DBA as a backend.
632 * Slow due to the need to constantly open and close the file to avoid holding
633 * writer locks. Intended for development use only, as a memcached workalike
634 * for systems that don't have it.
636 * @ingroup Cache
638 class DBABagOStuff extends BagOStuff {
639 var $mHandler, $mFile, $mReader, $mWriter, $mDisabled;
641 public function __construct( $dir = false ) {
642 global $wgDBAhandler;
643 if ( $dir === false ) {
644 global $wgTmpDirectory;
645 $dir = $wgTmpDirectory;
647 $this->mFile = "$dir/mw-cache-" . wfWikiID();
648 $this->mFile .= '.db';
649 wfDebug( __CLASS__ . ": using cache file {$this->mFile}\n" );
650 $this->mHandler = $wgDBAhandler;
654 * Encode value and expiry for storage
656 function encode( $value, $expiry ) {
657 # Convert to absolute time
658 $expiry = $this->convertExpiry( $expiry );
659 return sprintf( '%010u', intval( $expiry ) ) . ' ' . serialize( $value );
663 * @return list containing value first and expiry second
665 function decode( $blob ) {
666 if ( !is_string( $blob ) ) {
667 return array( null, 0 );
668 } else {
669 return array(
670 unserialize( substr( $blob, 11 ) ),
671 intval( substr( $blob, 0, 10 ) )
676 function getReader() {
677 if ( file_exists( $this->mFile ) ) {
678 $handle = dba_open( $this->mFile, 'rl', $this->mHandler );
679 } else {
680 $handle = $this->getWriter();
682 if ( !$handle ) {
683 wfDebug( "Unable to open DBA cache file {$this->mFile}\n" );
685 return $handle;
688 function getWriter() {
689 $handle = dba_open( $this->mFile, 'cl', $this->mHandler );
690 if ( !$handle ) {
691 wfDebug( "Unable to open DBA cache file {$this->mFile}\n" );
693 return $handle;
696 function get( $key ) {
697 wfProfileIn( __METHOD__ );
698 wfDebug( __METHOD__ . "($key)\n" );
699 $handle = $this->getReader();
700 if ( !$handle ) {
701 return null;
703 $val = dba_fetch( $key, $handle );
704 list( $val, $expiry ) = $this->decode( $val );
705 # Must close ASAP because locks are held
706 dba_close( $handle );
708 if ( !is_null( $val ) && $expiry && $expiry < time() ) {
709 # Key is expired, delete it
710 $handle = $this->getWriter();
711 dba_delete( $key, $handle );
712 dba_close( $handle );
713 wfDebug( __METHOD__ . ": $key expired\n" );
714 $val = null;
716 wfProfileOut( __METHOD__ );
717 return $val;
720 function set( $key, $value, $exptime = 0 ) {
721 wfProfileIn( __METHOD__ );
722 wfDebug( __METHOD__ . "($key)\n" );
723 $blob = $this->encode( $value, $exptime );
724 $handle = $this->getWriter();
725 if ( !$handle ) {
726 return false;
728 $ret = dba_replace( $key, $blob, $handle );
729 dba_close( $handle );
730 wfProfileOut( __METHOD__ );
731 return $ret;
734 function delete( $key, $time = 0 ) {
735 wfProfileIn( __METHOD__ );
736 wfDebug( __METHOD__ . "($key)\n" );
737 $handle = $this->getWriter();
738 if ( !$handle ) {
739 return false;
741 $ret = dba_delete( $key, $handle );
742 dba_close( $handle );
743 wfProfileOut( __METHOD__ );
744 return $ret;
747 function add( $key, $value, $exptime = 0 ) {
748 wfProfileIn( __METHOD__ );
749 $blob = $this->encode( $value, $exptime );
750 $handle = $this->getWriter();
751 if ( !$handle ) {
752 return false;
754 $ret = dba_insert( $key, $blob, $handle );
755 # Insert failed, check to see if it failed due to an expired key
756 if ( !$ret ) {
757 list( $value, $expiry ) = $this->decode( dba_fetch( $key, $handle ) );
758 if ( $expiry < time() ) {
759 # Yes expired, delete and try again
760 dba_delete( $key, $handle );
761 $ret = dba_insert( $key, $blob, $handle );
762 # This time if it failed then it will be handled by the caller like any other race
766 dba_close( $handle );
767 wfProfileOut( __METHOD__ );
768 return $ret;
771 function keys() {
772 $reader = $this->getReader();
773 $k1 = dba_firstkey( $reader );
774 if ( !$k1 ) {
775 return array();
777 $result[] = $k1;
778 while ( $key = dba_nextkey( $reader ) ) {
779 $result[] = $key;
781 return $result;