3 * +---------------------------------------------------------------------------+
4 * | memcached client, PHP |
5 * +---------------------------------------------------------------------------+
6 * | Copyright (c) 2003 Ryan T. Dean <rtdean@cytherianage.net> |
7 * | All rights reserved. |
9 * | Redistribution and use in source and binary forms, with or without |
10 * | modification, are permitted provided that the following conditions |
13 * | 1. Redistributions of source code must retain the above copyright |
14 * | notice, this list of conditions and the following disclaimer. |
15 * | 2. Redistributions in binary form must reproduce the above copyright |
16 * | notice, this list of conditions and the following disclaimer in the |
17 * | documentation and/or other materials provided with the distribution. |
19 * | THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR |
20 * | IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES |
21 * | OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. |
22 * | IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, |
23 * | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT |
24 * | NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
25 * | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY |
26 * | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT |
27 * | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF |
28 * | THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
29 * +---------------------------------------------------------------------------+
30 * | Author: Ryan T. Dean <rtdean@cytherianage.net> |
31 * | Heavily influenced by the Perl memcached client by Brad Fitzpatrick. |
32 * | Permission granted by Brad Fitzpatrick for relicense of ported Perl |
33 * | client logic under 2-clause BSD license. |
34 * +---------------------------------------------------------------------------+
41 * This is the PHP client for memcached - a distributed memory cache daemon.
42 * More information is available at http://www.danga.com/memcached/
46 * require_once 'memcached.php';
48 * $mc = new MWMemcached(array(
49 * 'servers' => array('127.0.0.1:10000',
50 * array('192.0.0.1:10010', 2),
53 * 'compress_threshold' => 10240,
54 * 'persistant' => true));
56 * $mc->add('key', array('some', 'array'));
57 * $mc->replace('key', 'some random string');
58 * $val = $mc->get('key');
60 * @author Ryan T. Dean <rtdean@cytherianage.net>
67 // {{{ class MWMemcached
69 * memcached client class implemented using (p)fsockopen()
71 * @author Ryan T. Dean <rtdean@cytherianage.net>
82 * Flag: indicates data is serialized
87 * Flag: indicates data is compressed
94 * Minimum savings to store data compressed
96 const COMPRESSION_SAVINGS
= 0.20;
113 * Cached Sockets that are connected
121 * Current debug status; 0 - none to 9 - profiling
129 * Dead hosts, assoc array, 'host'=>'unixtime when ok to check again'
137 * Is compression available?
145 * Do we want to use compression?
150 var $_compress_enable;
153 * At how many bytes should we compress?
158 var $_compress_threshold;
161 * Are we using persistant links?
169 * If only using one server; contains ip:port to connect to
177 * Array containing ip:port or array(ip:port, weight)
193 * Total # of bit buckets we have
201 * # of total servers we have
209 * Stream timeout in seconds. Applies for example to fread()
214 var $_timeout_seconds;
217 * Stream timeout in microseconds
222 var $_timeout_microseconds;
225 * Connect timeout in seconds
227 var $_connect_timeout;
230 * Number of connection attempts for each server
232 var $_connect_attempts;
237 // {{{ public functions
241 * Memcache initializer
243 * @param $args Associative array of settings
247 public function __construct( $args ) {
248 global $wgMemCachedTimeout;
249 $this->set_servers( isset( $args['servers'] ) ?
$args['servers'] : array() );
250 $this->_debug
= isset( $args['debug'] ) ?
$args['debug'] : false;
251 $this->stats
= array();
252 $this->_compress_threshold
= isset( $args['compress_threshold'] ) ?
$args['compress_threshold'] : 0;
253 $this->_persistant
= isset( $args['persistant'] ) ?
$args['persistant'] : false;
254 $this->_compress_enable
= true;
255 $this->_have_zlib
= function_exists( 'gzcompress' );
257 $this->_cache_sock
= array();
258 $this->_host_dead
= array();
260 $this->_timeout_seconds
= 0;
261 $this->_timeout_microseconds
= $wgMemCachedTimeout;
263 $this->_connect_timeout
= 0.01;
264 $this->_connect_attempts
= 2;
271 * Adds a key/value to the memcache server if one isn't already set with
274 * @param $key String: key to set with data
275 * @param $val Mixed: value to store
276 * @param $exp Integer: (optional) time to expire data at
280 public function add( $key, $val, $exp = 0 ) {
281 return $this->_set( 'add', $key, $val, $exp );
288 * Decriment a value stored on the memcache server
290 * @param $key String: key to decriment
291 * @param $amt Integer: (optional) amount to decriment
293 * @return Mixed: FALSE on failure, value on success
295 public function decr( $key, $amt = 1 ) {
296 return $this->_incrdecr( 'decr', $key, $amt );
303 * Deletes a key from the server, optionally after $time
305 * @param $key String: key to delete
306 * @param $time Integer: (optional) how long to wait before deleting
308 * @return Boolean: TRUE on success, FALSE on failure
310 public function delete( $key, $time = 0 ) {
311 if ( !$this->_active
) {
315 $sock = $this->get_sock( $key );
316 if ( !is_resource( $sock ) ) {
320 $key = is_array( $key ) ?
$key[1] : $key;
322 if ( isset( $this->stats
['delete'] ) ) {
323 $this->stats
['delete']++
;
325 $this->stats
['delete'] = 1;
327 $cmd = "delete $key $time\r\n";
328 if( !$this->_safe_fwrite( $sock, $cmd, strlen( $cmd ) ) ) {
329 $this->_dead_sock( $sock );
332 $res = trim( fgets( $sock ) );
334 if ( $this->_debug
) {
335 $this->_debugprint( sprintf( "MemCache: delete %s (%s)\n", $key, $res ) );
338 if ( $res == "DELETED" ) {
345 // {{{ disconnect_all()
348 * Disconnects all connected sockets
350 public function disconnect_all() {
351 foreach ( $this->_cache_sock
as $sock ) {
355 $this->_cache_sock
= array();
359 // {{{ enable_compress()
362 * Enable / Disable compression
364 * @param $enable Boolean: TRUE to enable, FALSE to disable
366 public function enable_compress( $enable ) {
367 $this->_compress_enable
= $enable;
371 // {{{ forget_dead_hosts()
374 * Forget about all of the dead hosts
376 public function forget_dead_hosts() {
377 $this->_host_dead
= array();
384 * Retrieves the value associated with the key from the memcache server
386 * @param $key Mixed: key to retrieve
390 public function get( $key ) {
391 wfProfileIn( __METHOD__
);
393 if ( $this->_debug
) {
394 $this->_debugprint( "get($key)\n" );
397 if ( !$this->_active
) {
398 wfProfileOut( __METHOD__
);
402 $sock = $this->get_sock( $key );
404 if ( !is_resource( $sock ) ) {
405 wfProfileOut( __METHOD__
);
409 if ( isset( $this->stats
['get'] ) ) {
410 $this->stats
['get']++
;
412 $this->stats
['get'] = 1;
415 $cmd = "get $key\r\n";
416 if ( !$this->_safe_fwrite( $sock, $cmd, strlen( $cmd ) ) ) {
417 $this->_dead_sock( $sock );
418 wfProfileOut( __METHOD__
);
423 $this->_load_items( $sock, $val );
425 if ( $this->_debug
) {
426 foreach ( $val as $k => $v ) {
427 $this->_debugprint( sprintf( "MemCache: sock %s got %s\n", serialize( $sock ), $k ) );
431 wfProfileOut( __METHOD__
);
439 * Get multiple keys from the server(s)
441 * @param $keys Array: keys to retrieve
445 public function get_multi( $keys ) {
446 if ( !$this->_active
) {
450 if ( isset( $this->stats
['get_multi'] ) ) {
451 $this->stats
['get_multi']++
;
453 $this->stats
['get_multi'] = 1;
455 $sock_keys = array();
457 foreach ( $keys as $key ) {
458 $sock = $this->get_sock( $key );
459 if ( !is_resource( $sock ) ) {
462 $key = is_array( $key ) ?
$key[1] : $key;
463 if ( !isset( $sock_keys[$sock] ) ) {
464 $sock_keys[$sock] = array();
467 $sock_keys[$sock][] = $key;
470 // Send out the requests
471 foreach ( $socks as $sock ) {
473 foreach ( $sock_keys[$sock] as $key ) {
478 if ( $this->_safe_fwrite( $sock, $cmd, strlen( $cmd ) ) ) {
481 $this->_dead_sock( $sock );
487 foreach ( $gather as $sock ) {
488 $this->_load_items( $sock, $val );
491 if ( $this->_debug
) {
492 foreach ( $val as $k => $v ) {
493 $this->_debugprint( sprintf( "MemCache: got %s\n", $k ) );
504 * Increments $key (optionally) by $amt
506 * @param $key String: key to increment
507 * @param $amt Integer: (optional) amount to increment
509 * @return Integer: new key value?
511 public function incr( $key, $amt = 1 ) {
512 return $this->_incrdecr( 'incr', $key, $amt );
519 * Overwrites an existing value for key; only works if key is already set
521 * @param $key String: key to set value as
522 * @param $value Mixed: value to store
523 * @param $exp Integer: (optional) experiation time
527 public function replace( $key, $value, $exp = 0 ) {
528 return $this->_set( 'replace', $key, $value, $exp );
535 * Passes through $cmd to the memcache server connected by $sock; returns
536 * output as an array (null array if no output)
538 * NOTE: due to a possible bug in how PHP reads while using fgets(), each
539 * line may not be terminated by a \r\n. More specifically, my testing
540 * has shown that, on FreeBSD at least, each line is terminated only
541 * with a \n. This is with the PHP flag auto_detect_line_endings set
542 * to falase (the default).
544 * @param $sock Ressource: socket to send command on
545 * @param $cmd String: command to run
547 * @return Array: output array
549 public function run_command( $sock, $cmd ) {
550 if ( !is_resource( $sock ) ) {
554 if ( !$this->_safe_fwrite( $sock, $cmd, strlen( $cmd ) ) ) {
559 $res = fgets( $sock );
561 if ( preg_match( '/^END/', $res ) ) {
564 if ( strlen( $res ) == 0 ) {
575 * Unconditionally sets a key to a given value in the memcache. Returns true
576 * if set successfully.
578 * @param $key String: key to set value as
579 * @param $value Mixed: value to set
580 * @param $exp Integer: (optional) Experiation time
582 * @return Boolean: TRUE on success
584 public function set( $key, $value, $exp = 0 ) {
585 return $this->_set( 'set', $key, $value, $exp );
589 // {{{ set_compress_threshold()
592 * Sets the compression threshold
594 * @param $thresh Integer: threshold to compress if larger than
596 public function set_compress_threshold( $thresh ) {
597 $this->_compress_threshold
= $thresh;
604 * Sets the debug flag
606 * @param $dbg Boolean: TRUE for debugging, FALSE otherwise
608 * @see MWMemcached::__construct
610 public function set_debug( $dbg ) {
611 $this->_debug
= $dbg;
618 * Sets the server list to distribute key gets and puts between
620 * @param $list Array of servers to connect to
622 * @see MWMemcached::__construct()
624 public function set_servers( $list ) {
625 $this->_servers
= $list;
626 $this->_active
= count( $list );
627 $this->_buckets
= null;
628 $this->_bucketcount
= 0;
630 $this->_single_sock
= null;
631 if ( $this->_active
== 1 ) {
632 $this->_single_sock
= $this->_servers
[0];
637 * Sets the timeout for new connections
639 * @param $seconds Integer: number of seconds
640 * @param $microseconds Integer: number of microseconds
642 public function set_timeout( $seconds, $microseconds ) {
643 $this->_timeout_seconds
= $seconds;
644 $this->_timeout_microseconds
= $microseconds;
649 // {{{ private methods
653 * Close the specified socket
655 * @param $sock String: socket to close
659 function _close_sock( $sock ) {
660 $host = array_search( $sock, $this->_cache_sock
);
661 fclose( $this->_cache_sock
[$host] );
662 unset( $this->_cache_sock
[$host] );
666 // {{{ _connect_sock()
669 * Connects $sock to $host, timing out after $timeout
671 * @param $sock Integer: socket to connect
672 * @param $host String: Host:IP to connect to
677 function _connect_sock( &$sock, $host ) {
678 list( $ip, $port ) = explode( ':', $host );
680 $timeout = $this->_connect_timeout
;
681 $errno = $errstr = null;
682 for( $i = 0; !$sock && $i < $this->_connect_attempts
; $i++
) {
683 wfSuppressWarnings();
684 if ( $this->_persistant
== 1 ) {
685 $sock = pfsockopen( $ip, $port, $errno, $errstr, $timeout );
687 $sock = fsockopen( $ip, $port, $errno, $errstr, $timeout );
692 if ( $this->_debug
) {
693 $this->_debugprint( "Error connecting to $host: $errstr\n" );
698 // Initialise timeout
699 stream_set_timeout( $sock, $this->_timeout_seconds
, $this->_timeout_microseconds
);
708 * Marks a host as dead until 30-40 seconds in the future
710 * @param $sock String: socket to mark as dead
714 function _dead_sock( $sock ) {
715 $host = array_search( $sock, $this->_cache_sock
);
716 $this->_dead_host( $host );
719 function _dead_host( $host ) {
720 $parts = explode( ':', $host );
722 $this->_host_dead
[$ip] = time() +
30 +
intval( rand( 0, 10 ) );
723 $this->_host_dead
[$host] = $this->_host_dead
[$ip];
724 unset( $this->_cache_sock
[$host] );
733 * @param $key String: key to retrieve value for;
735 * @return Mixed: resource on success, false on failure
738 function get_sock( $key ) {
739 if ( !$this->_active
) {
743 if ( $this->_single_sock
!== null ) {
744 $this->_flush_read_buffer( $this->_single_sock
);
745 return $this->sock_to_host( $this->_single_sock
);
748 $hv = is_array( $key ) ?
intval( $key[0] ) : $this->_hashfunc( $key );
750 if ( $this->_buckets
=== null ) {
751 foreach ( $this->_servers
as $v ) {
752 if ( is_array( $v ) ) {
753 for( $i = 0; $i < $v[1]; $i++
) {
760 $this->_buckets
= $bu;
761 $this->_bucketcount
= count( $bu );
764 $realkey = is_array( $key ) ?
$key[1] : $key;
765 for( $tries = 0; $tries < 20; $tries++
) {
766 $host = $this->_buckets
[$hv %
$this->_bucketcount
];
767 $sock = $this->sock_to_host( $host );
768 if ( is_resource( $sock ) ) {
769 $this->_flush_read_buffer( $sock );
772 $hv = $this->_hashfunc( $hv . $realkey );
782 * Creates a hash integer based on the $key
784 * @param $key String: key to hash
786 * @return Integer: hash value
789 function _hashfunc( $key ) {
790 # Hash function must on [0,0x7ffffff]
791 # We take the first 31 bits of the MD5 hash, which unlike the hash
792 # function used in a previous version of this client, works
793 return hexdec( substr( md5( $key ), 0, 8 ) ) & 0x7fffffff;
800 * Perform increment/decriment on $key
802 * @param $cmd String: command to perform
803 * @param $key String: key to perform it on
804 * @param $amt Integer: amount to adjust
806 * @return Integer: new value of $key
809 function _incrdecr( $cmd, $key, $amt = 1 ) {
810 if ( !$this->_active
) {
814 $sock = $this->get_sock( $key );
815 if ( !is_resource( $sock ) ) {
819 $key = is_array( $key ) ?
$key[1] : $key;
820 if ( isset( $this->stats
[$cmd] ) ) {
821 $this->stats
[$cmd]++
;
823 $this->stats
[$cmd] = 1;
825 if ( !$this->_safe_fwrite( $sock, "$cmd $key $amt\r\n" ) ) {
826 return $this->_dead_sock( $sock );
829 $line = fgets( $sock );
831 if ( !preg_match( '/^(\d+)/', $line, $match ) ) {
841 * Load items into $ret from $sock
843 * @param $sock Ressource: socket to read from
844 * @param $ret Array: returned values
848 function _load_items( $sock, &$ret ) {
850 $decl = fgets( $sock );
851 if ( $decl == "END\r\n" ) {
853 } elseif ( preg_match( '/^VALUE (\S+) (\d+) (\d+)\r\n$/', $decl, $match ) ) {
854 list( $rkey, $flags, $len ) = array( $match[1], $match[2], $match[3] );
858 while ( $bneed > 0 ) {
859 $data = fread( $sock, $bneed );
860 $n = strlen( $data );
866 if ( isset( $ret[$rkey] ) ) {
867 $ret[$rkey] .= $data;
873 if ( $offset != $len +
2 ) {
874 // Something is borked!
875 if ( $this->_debug
) {
876 $this->_debugprint( sprintf( "Something is borked! key %s expecting %d got %d length\n", $rkey, $len +
2, $offset ) );
879 unset( $ret[$rkey] );
880 $this->_close_sock( $sock );
884 if ( $this->_have_zlib
&& $flags & self
::COMPRESSED
) {
885 $ret[$rkey] = gzuncompress( $ret[$rkey] );
888 $ret[$rkey] = rtrim( $ret[$rkey] );
890 if ( $flags & self
::SERIALIZED
) {
891 $ret[$rkey] = unserialize( $ret[$rkey] );
895 $this->_debugprint( "Error parsing memcached response\n" );
905 * Performs the requested storage operation to the memcache server
907 * @param $cmd String: command to perform
908 * @param $key String: key to act on
909 * @param $val Mixed: what we need to store
910 * @param $exp Integer: when it should expire
915 function _set( $cmd, $key, $val, $exp ) {
916 if ( !$this->_active
) {
920 $sock = $this->get_sock( $key );
921 if ( !is_resource( $sock ) ) {
925 if ( isset( $this->stats
[$cmd] ) ) {
926 $this->stats
[$cmd]++
;
928 $this->stats
[$cmd] = 1;
933 if ( !is_scalar( $val ) ) {
934 $val = serialize( $val );
935 $flags |
= self
::SERIALIZED
;
936 if ( $this->_debug
) {
937 $this->_debugprint( sprintf( "client: serializing data as it is not scalar\n" ) );
941 $len = strlen( $val );
943 if ( $this->_have_zlib
&& $this->_compress_enable
&&
944 $this->_compress_threshold
&& $len >= $this->_compress_threshold
)
946 $c_val = gzcompress( $val, 9 );
947 $c_len = strlen( $c_val );
949 if ( $c_len < $len * ( 1 - self
::COMPRESSION_SAVINGS
) ) {
950 if ( $this->_debug
) {
951 $this->_debugprint( sprintf( "client: compressing data; was %d bytes is now %d bytes\n", $len, $c_len ) );
955 $flags |
= self
::COMPRESSED
;
958 if ( !$this->_safe_fwrite( $sock, "$cmd $key $flags $exp $len\r\n$val\r\n" ) ) {
959 return $this->_dead_sock( $sock );
962 $line = trim( fgets( $sock ) );
964 if ( $this->_debug
) {
965 $this->_debugprint( sprintf( "%s %s (%s)\n", $cmd, $key, $line ) );
967 if ( $line == "STORED" ) {
974 // {{{ sock_to_host()
977 * Returns the socket for the host
979 * @param $host String: Host:IP to get socket for
981 * @return Mixed: IO Stream or false
984 function sock_to_host( $host ) {
985 if ( isset( $this->_cache_sock
[$host] ) ) {
986 return $this->_cache_sock
[$host];
991 list( $ip, /* $port */) = explode( ':', $host );
992 if ( isset( $this->_host_dead
[$host] ) && $this->_host_dead
[$host] > $now ||
993 isset( $this->_host_dead
[$ip] ) && $this->_host_dead
[$ip] > $now
998 if ( !$this->_connect_sock( $sock, $host ) ) {
999 return $this->_dead_host( $host );
1002 // Do not buffer writes
1003 stream_set_write_buffer( $sock, 0 );
1005 $this->_cache_sock
[$host] = $sock;
1007 return $this->_cache_sock
[$host];
1010 function _debugprint( $str ) {
1015 * Write to a stream, timing out after the correct amount of time
1017 * @return Boolean: false on failure, true on success
1020 function _safe_fwrite( $f, $buf, $len = false ) {
1021 stream_set_blocking( $f, 0 );
1023 if ( $len === false ) {
1024 wfDebug( "Writing " . strlen( $buf ) . " bytes\n" );
1025 $bytesWritten = fwrite( $f, $buf );
1027 wfDebug( "Writing $len bytes\n" );
1028 $bytesWritten = fwrite( $f, $buf, $len );
1030 $n = stream_select( $r = null, $w = array( $f ), $e = null, 10, 0 );
1031 # $this->_timeout_seconds, $this->_timeout_microseconds );
1033 wfDebug( "stream_select returned $n\n" );
1034 stream_set_blocking( $f, 1 );
1036 return $bytesWritten;
1040 * Original behaviour
1042 function _safe_fwrite( $f, $buf, $len = false ) {
1043 if ( $len === false ) {
1044 $bytesWritten = fwrite( $f, $buf );
1046 $bytesWritten = fwrite( $f, $buf, $len );
1048 return $bytesWritten;
1052 * Flush the read buffer of a stream
1054 function _flush_read_buffer( $f ) {
1055 if ( !is_resource( $f ) ) {
1058 $n = stream_select( $r = array( $f ), $w = null, $e = null, 0, 0 );
1059 while ( $n == 1 && !feof( $f ) ) {
1061 $n = stream_select( $r = array( $f ), $w = null, $e = null, 0, 0 );
1070 // vim: sts=3 sw=3 et
1074 class MemCachedClientforWiki
extends MWMemcached
{
1075 function _debugprint( $text ) {
1076 wfDebug( "memcached: $text" );