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 // +---------------------------------------------------------------------------+
40 * This is the PHP client for memcached - a distributed memory cache daemon.
41 * More information is available at http://www.danga.com/memcached/
45 * require_once 'memcached.php';
47 * $mc = new MWMemcached(array(
48 * 'servers' => array('127.0.0.1:10000',
49 * array('192.0.0.1:10010', 2),
52 * 'compress_threshold' => 10240,
53 * 'persistant' => true));
55 * $mc->add('key', array('some', 'array'));
56 * $mc->replace('key', 'some random string');
57 * $val = $mc->get('key');
59 * @author Ryan T. Dean <rtdean@cytherianage.net>
66 // {{{ class MWMemcached
68 * memcached client class implemented using (p)fsockopen()
70 * @author Ryan T. Dean <rtdean@cytherianage.net>
81 * Flag: indicates data is serialized
86 * Flag: indicates data is compressed
93 * Minimum savings to store data compressed
95 const COMPRESSION_SAVINGS
= 0.20;
112 * Cached Sockets that are connected
120 * Current debug status; 0 - none to 9 - profiling
128 * Dead hosts, assoc array, 'host'=>'unixtime when ok to check again'
136 * Is compression available?
144 * Do we want to use compression?
149 var $_compress_enable;
152 * At how many bytes should we compress?
157 var $_compress_threshold;
160 * Are we using persistant links?
168 * If only using one server; contains ip:port to connect to
176 * Array containing ip:port or array(ip:port, weight)
192 * Total # of bit buckets we have
200 * # of total servers we have
208 * Stream timeout in seconds. Applies for example to fread()
213 var $_timeout_seconds;
216 * Stream timeout in microseconds
221 var $_timeout_microseconds;
224 * Connect timeout in seconds
226 var $_connect_timeout;
229 * Number of connection attempts for each server
231 var $_connect_attempts;
236 // {{{ public functions
240 * Memcache initializer
242 * @param $args Associative array of settings
246 public function __construct( $args ) {
247 global $wgMemCachedTimeout;
248 $this->set_servers( isset( $args['servers'] ) ?
$args['servers'] : array() );
249 $this->_debug
= isset( $args['debug'] ) ?
$args['debug'] : false;
250 $this->stats
= array();
251 $this->_compress_threshold
= isset( $args['compress_threshold'] ) ?
$args['compress_threshold'] : 0;
252 $this->_persistant
= isset( $args['persistant'] ) ?
$args['persistant'] : false;
253 $this->_compress_enable
= true;
254 $this->_have_zlib
= function_exists( 'gzcompress' );
256 $this->_cache_sock
= array();
257 $this->_host_dead
= array();
259 $this->_timeout_seconds
= 0;
260 $this->_timeout_microseconds
= $wgMemCachedTimeout;
262 $this->_connect_timeout
= 0.01;
263 $this->_connect_attempts
= 2;
270 * Adds a key/value to the memcache server if one isn't already set with
273 * @param $key String: key to set with data
274 * @param $val Mixed: value to store
275 * @param $exp Integer: (optional) time to expire data at
279 public function add( $key, $val, $exp = 0 ) {
280 return $this->_set( 'add', $key, $val, $exp );
287 * Decriment a value stored on the memcache server
289 * @param $key String: key to decriment
290 * @param $amt Integer: (optional) amount to decriment
292 * @return Mixed: FALSE on failure, value on success
294 public function decr( $key, $amt = 1 ) {
295 return $this->_incrdecr( 'decr', $key, $amt );
302 * Deletes a key from the server, optionally after $time
304 * @param $key String: key to delete
305 * @param $time Integer: (optional) how long to wait before deleting
307 * @return Boolean: TRUE on success, FALSE on failure
309 public function delete( $key, $time = 0 ) {
310 if ( !$this->_active
) {
314 $sock = $this->get_sock( $key );
315 if ( !is_resource( $sock ) ) {
319 $key = is_array( $key ) ?
$key[1] : $key;
321 if ( isset( $this->stats
['delete'] ) ) {
322 $this->stats
['delete']++
;
324 $this->stats
['delete'] = 1;
326 $cmd = "delete $key $time\r\n";
327 if( !$this->_safe_fwrite( $sock, $cmd, strlen( $cmd ) ) ) {
328 $this->_dead_sock( $sock );
331 $res = trim( fgets( $sock ) );
333 if ( $this->_debug
) {
334 $this->_debugprint( sprintf( "MemCache: delete %s (%s)\n", $key, $res ) );
337 if ( $res == "DELETED" ) {
344 // {{{ disconnect_all()
347 * Disconnects all connected sockets
349 public function disconnect_all() {
350 foreach ( $this->_cache_sock
as $sock ) {
354 $this->_cache_sock
= array();
358 // {{{ enable_compress()
361 * Enable / Disable compression
363 * @param $enable Boolean: TRUE to enable, FALSE to disable
365 public function enable_compress( $enable ) {
366 $this->_compress_enable
= $enable;
370 // {{{ forget_dead_hosts()
373 * Forget about all of the dead hosts
375 public function forget_dead_hosts() {
376 $this->_host_dead
= array();
383 * Retrieves the value associated with the key from the memcache server
385 * @param $key Mixed: key to retrieve
389 public function get( $key ) {
390 wfProfileIn( __METHOD__
);
392 if ( $this->_debug
) {
393 $this->_debugprint( "get($key)\n" );
396 if ( !$this->_active
) {
397 wfProfileOut( __METHOD__
);
401 $sock = $this->get_sock( $key );
403 if ( !is_resource( $sock ) ) {
404 wfProfileOut( __METHOD__
);
408 if ( isset( $this->stats
['get'] ) ) {
409 $this->stats
['get']++
;
411 $this->stats
['get'] = 1;
414 $cmd = "get $key\r\n";
415 if ( !$this->_safe_fwrite( $sock, $cmd, strlen( $cmd ) ) ) {
416 $this->_dead_sock( $sock );
417 wfProfileOut( __METHOD__
);
422 $this->_load_items( $sock, $val );
424 if ( $this->_debug
) {
425 foreach ( $val as $k => $v ) {
426 $this->_debugprint( sprintf( "MemCache: sock %s got %s\n", serialize( $sock ), $k ) );
430 wfProfileOut( __METHOD__
);
438 * Get multiple keys from the server(s)
440 * @param $keys Array: keys to retrieve
444 public function get_multi( $keys ) {
445 if ( !$this->_active
) {
449 if ( isset( $this->stats
['get_multi'] ) ) {
450 $this->stats
['get_multi']++
;
452 $this->stats
['get_multi'] = 1;
454 $sock_keys = array();
456 foreach ( $keys as $key ) {
457 $sock = $this->get_sock( $key );
458 if ( !is_resource( $sock ) ) {
461 $key = is_array( $key ) ?
$key[1] : $key;
462 if ( !isset( $sock_keys[$sock] ) ) {
463 $sock_keys[$sock] = array();
466 $sock_keys[$sock][] = $key;
469 // Send out the requests
470 foreach ( $socks as $sock ) {
472 foreach ( $sock_keys[$sock] as $key ) {
477 if ( $this->_safe_fwrite( $sock, $cmd, strlen( $cmd ) ) ) {
480 $this->_dead_sock( $sock );
486 foreach ( $gather as $sock ) {
487 $this->_load_items( $sock, $val );
490 if ( $this->_debug
) {
491 foreach ( $val as $k => $v ) {
492 $this->_debugprint( sprintf( "MemCache: got %s\n", $k ) );
503 * Increments $key (optionally) by $amt
505 * @param $key String: key to increment
506 * @param $amt Integer: (optional) amount to increment
508 * @return Integer: new key value?
510 public function incr( $key, $amt = 1 ) {
511 return $this->_incrdecr( 'incr', $key, $amt );
518 * Overwrites an existing value for key; only works if key is already set
520 * @param $key String: key to set value as
521 * @param $value Mixed: value to store
522 * @param $exp Integer: (optional) experiation time
526 public function replace( $key, $value, $exp = 0 ) {
527 return $this->_set( 'replace', $key, $value, $exp );
534 * Passes through $cmd to the memcache server connected by $sock; returns
535 * output as an array (null array if no output)
537 * NOTE: due to a possible bug in how PHP reads while using fgets(), each
538 * line may not be terminated by a \r\n. More specifically, my testing
539 * has shown that, on FreeBSD at least, each line is terminated only
540 * with a \n. This is with the PHP flag auto_detect_line_endings set
541 * to falase (the default).
543 * @param $sock Ressource: socket to send command on
544 * @param $cmd String: command to run
546 * @return Array: output array
548 public function run_command( $sock, $cmd ) {
549 if ( !is_resource( $sock ) ) {
553 if ( !$this->_safe_fwrite( $sock, $cmd, strlen( $cmd ) ) ) {
558 $res = fgets( $sock );
560 if ( preg_match( '/^END/', $res ) ) {
563 if ( strlen( $res ) == 0 ) {
574 * Unconditionally sets a key to a given value in the memcache. Returns true
575 * if set successfully.
577 * @param $key String: key to set value as
578 * @param $value Mixed: value to set
579 * @param $exp Integer: (optional) Experiation time
581 * @return Boolean: TRUE on success
583 public function set( $key, $value, $exp = 0 ) {
584 return $this->_set( 'set', $key, $value, $exp );
588 // {{{ set_compress_threshold()
591 * Sets the compression threshold
593 * @param $thresh Integer: threshold to compress if larger than
595 public function set_compress_threshold( $thresh ) {
596 $this->_compress_threshold
= $thresh;
603 * Sets the debug flag
605 * @param $dbg Boolean: TRUE for debugging, FALSE otherwise
607 * @see MWMemcached::__construct
609 public function set_debug( $dbg ) {
610 $this->_debug
= $dbg;
617 * Sets the server list to distribute key gets and puts between
619 * @param $list Array of servers to connect to
621 * @see MWMemcached::__construct()
623 public function set_servers( $list ) {
624 $this->_servers
= $list;
625 $this->_active
= count( $list );
626 $this->_buckets
= null;
627 $this->_bucketcount
= 0;
629 $this->_single_sock
= null;
630 if ( $this->_active
== 1 ) {
631 $this->_single_sock
= $this->_servers
[0];
636 * Sets the timeout for new connections
638 * @param $seconds Integer: number of seconds
639 * @param $microseconds Integer: number of microseconds
641 public function set_timeout( $seconds, $microseconds ) {
642 $this->_timeout_seconds
= $seconds;
643 $this->_timeout_microseconds
= $microseconds;
648 // {{{ private methods
652 * Close the specified socket
654 * @param $sock String: socket to close
658 function _close_sock( $sock ) {
659 $host = array_search( $sock, $this->_cache_sock
);
660 fclose( $this->_cache_sock
[$host] );
661 unset( $this->_cache_sock
[$host] );
665 // {{{ _connect_sock()
668 * Connects $sock to $host, timing out after $timeout
670 * @param $sock Integer: socket to connect
671 * @param $host String: Host:IP to connect to
676 function _connect_sock( &$sock, $host ) {
677 list( $ip, $port ) = explode( ':', $host );
679 $timeout = $this->_connect_timeout
;
680 $errno = $errstr = null;
681 for( $i = 0; !$sock && $i < $this->_connect_attempts
; $i++
) {
682 wfSuppressWarnings();
683 if ( $this->_persistant
== 1 ) {
684 $sock = pfsockopen( $ip, $port, $errno, $errstr, $timeout );
686 $sock = fsockopen( $ip, $port, $errno, $errstr, $timeout );
691 if ( $this->_debug
) {
692 $this->_debugprint( "Error connecting to $host: $errstr\n" );
697 // Initialise timeout
698 stream_set_timeout( $sock, $this->_timeout_seconds
, $this->_timeout_microseconds
);
707 * Marks a host as dead until 30-40 seconds in the future
709 * @param $sock String: socket to mark as dead
713 function _dead_sock( $sock ) {
714 $host = array_search( $sock, $this->_cache_sock
);
715 $this->_dead_host( $host );
718 function _dead_host( $host ) {
719 $parts = explode( ':', $host );
721 $this->_host_dead
[$ip] = time() +
30 +
intval( rand( 0, 10 ) );
722 $this->_host_dead
[$host] = $this->_host_dead
[$ip];
723 unset( $this->_cache_sock
[$host] );
732 * @param $key String: key to retrieve value for;
734 * @return Mixed: resource on success, false on failure
737 function get_sock( $key ) {
738 if ( !$this->_active
) {
742 if ( $this->_single_sock
!== null ) {
743 $this->_flush_read_buffer( $this->_single_sock
);
744 return $this->sock_to_host( $this->_single_sock
);
747 $hv = is_array( $key ) ?
intval( $key[0] ) : $this->_hashfunc( $key );
749 if ( $this->_buckets
=== null ) {
750 foreach ( $this->_servers
as $v ) {
751 if ( is_array( $v ) ) {
752 for( $i = 0; $i < $v[1]; $i++
) {
759 $this->_buckets
= $bu;
760 $this->_bucketcount
= count( $bu );
763 $realkey = is_array( $key ) ?
$key[1] : $key;
764 for( $tries = 0; $tries < 20; $tries++
) {
765 $host = $this->_buckets
[$hv %
$this->_bucketcount
];
766 $sock = $this->sock_to_host( $host );
767 if ( is_resource( $sock ) ) {
768 $this->_flush_read_buffer( $sock );
771 $hv = $this->_hashfunc( $hv . $realkey );
781 * Creates a hash integer based on the $key
783 * @param $key String: key to hash
785 * @return Integer: hash value
788 function _hashfunc( $key ) {
789 # Hash function must on [0,0x7ffffff]
790 # We take the first 31 bits of the MD5 hash, which unlike the hash
791 # function used in a previous version of this client, works
792 return hexdec( substr( md5( $key ), 0, 8 ) ) & 0x7fffffff;
799 * Perform increment/decriment on $key
801 * @param $cmd String: command to perform
802 * @param $key String: key to perform it on
803 * @param $amt Integer: amount to adjust
805 * @return Integer: new value of $key
808 function _incrdecr( $cmd, $key, $amt = 1 ) {
809 if ( !$this->_active
) {
813 $sock = $this->get_sock( $key );
814 if ( !is_resource( $sock ) ) {
818 $key = is_array( $key ) ?
$key[1] : $key;
819 if ( isset( $this->stats
[$cmd] ) ) {
820 $this->stats
[$cmd]++
;
822 $this->stats
[$cmd] = 1;
824 if ( !$this->_safe_fwrite( $sock, "$cmd $key $amt\r\n" ) ) {
825 return $this->_dead_sock( $sock );
828 $line = fgets( $sock );
830 if ( !preg_match( '/^(\d+)/', $line, $match ) ) {
840 * Load items into $ret from $sock
842 * @param $sock Ressource: socket to read from
843 * @param $ret Array: returned values
847 function _load_items( $sock, &$ret ) {
849 $decl = fgets( $sock );
850 if ( $decl == "END\r\n" ) {
852 } elseif ( preg_match( '/^VALUE (\S+) (\d+) (\d+)\r\n$/', $decl, $match ) ) {
853 list( $rkey, $flags, $len ) = array( $match[1], $match[2], $match[3] );
857 while ( $bneed > 0 ) {
858 $data = fread( $sock, $bneed );
859 $n = strlen( $data );
865 if ( isset( $ret[$rkey] ) ) {
866 $ret[$rkey] .= $data;
872 if ( $offset != $len +
2 ) {
873 // Something is borked!
874 if ( $this->_debug
) {
875 $this->_debugprint( sprintf( "Something is borked! key %s expecting %d got %d length\n", $rkey, $len +
2, $offset ) );
878 unset( $ret[$rkey] );
879 $this->_close_sock( $sock );
883 if ( $this->_have_zlib
&& $flags & self
::COMPRESSED
) {
884 $ret[$rkey] = gzuncompress( $ret[$rkey] );
887 $ret[$rkey] = rtrim( $ret[$rkey] );
889 if ( $flags & self
::SERIALIZED
) {
890 $ret[$rkey] = unserialize( $ret[$rkey] );
894 $this->_debugprint( "Error parsing memcached response\n" );
904 * Performs the requested storage operation to the memcache server
906 * @param $cmd String: command to perform
907 * @param $key String: key to act on
908 * @param $val Mixed: what we need to store
909 * @param $exp Integer: when it should expire
914 function _set( $cmd, $key, $val, $exp ) {
915 if ( !$this->_active
) {
919 $sock = $this->get_sock( $key );
920 if ( !is_resource( $sock ) ) {
924 if ( isset( $this->stats
[$cmd] ) ) {
925 $this->stats
[$cmd]++
;
927 $this->stats
[$cmd] = 1;
932 if ( !is_scalar( $val ) ) {
933 $val = serialize( $val );
934 $flags |
= self
::SERIALIZED
;
935 if ( $this->_debug
) {
936 $this->_debugprint( sprintf( "client: serializing data as it is not scalar\n" ) );
940 $len = strlen( $val );
942 if ( $this->_have_zlib
&& $this->_compress_enable
&&
943 $this->_compress_threshold
&& $len >= $this->_compress_threshold
)
945 $c_val = gzcompress( $val, 9 );
946 $c_len = strlen( $c_val );
948 if ( $c_len < $len * ( 1 - self
::COMPRESSION_SAVINGS
) ) {
949 if ( $this->_debug
) {
950 $this->_debugprint( sprintf( "client: compressing data; was %d bytes is now %d bytes\n", $len, $c_len ) );
954 $flags |
= self
::COMPRESSED
;
957 if ( !$this->_safe_fwrite( $sock, "$cmd $key $flags $exp $len\r\n$val\r\n" ) ) {
958 return $this->_dead_sock( $sock );
961 $line = trim( fgets( $sock ) );
963 if ( $this->_debug
) {
964 $this->_debugprint( sprintf( "%s %s (%s)\n", $cmd, $key, $line ) );
966 if ( $line == "STORED" ) {
973 // {{{ sock_to_host()
976 * Returns the socket for the host
978 * @param $host String: Host:IP to get socket for
980 * @return Mixed: IO Stream or false
983 function sock_to_host( $host ) {
984 if ( isset( $this->_cache_sock
[$host] ) ) {
985 return $this->_cache_sock
[$host];
990 list( $ip, /* $port */) = explode( ':', $host );
991 if ( isset( $this->_host_dead
[$host] ) && $this->_host_dead
[$host] > $now ||
992 isset( $this->_host_dead
[$ip] ) && $this->_host_dead
[$ip] > $now
997 if ( !$this->_connect_sock( $sock, $host ) ) {
998 return $this->_dead_host( $host );
1001 // Do not buffer writes
1002 stream_set_write_buffer( $sock, 0 );
1004 $this->_cache_sock
[$host] = $sock;
1006 return $this->_cache_sock
[$host];
1009 function _debugprint( $str ) {
1014 * Write to a stream, timing out after the correct amount of time
1016 * @return Boolean: false on failure, true on success
1019 function _safe_fwrite( $f, $buf, $len = false ) {
1020 stream_set_blocking( $f, 0 );
1022 if ( $len === false ) {
1023 wfDebug( "Writing " . strlen( $buf ) . " bytes\n" );
1024 $bytesWritten = fwrite( $f, $buf );
1026 wfDebug( "Writing $len bytes\n" );
1027 $bytesWritten = fwrite( $f, $buf, $len );
1029 $n = stream_select( $r = null, $w = array( $f ), $e = null, 10, 0 );
1030 # $this->_timeout_seconds, $this->_timeout_microseconds );
1032 wfDebug( "stream_select returned $n\n" );
1033 stream_set_blocking( $f, 1 );
1035 return $bytesWritten;
1039 * Original behaviour
1041 function _safe_fwrite( $f, $buf, $len = false ) {
1042 if ( $len === false ) {
1043 $bytesWritten = fwrite( $f, $buf );
1045 $bytesWritten = fwrite( $f, $buf, $len );
1047 return $bytesWritten;
1051 * Flush the read buffer of a stream
1053 function _flush_read_buffer( $f ) {
1054 if ( !is_resource( $f ) ) {
1057 $n = stream_select( $r = array( $f ), $w = null, $e = null, 0, 0 );
1058 while ( $n == 1 && !feof( $f ) ) {
1060 $n = stream_select( $r = array( $f ), $w = null, $e = null, 0, 0 );
1069 // vim: sts=3 sw=3 et
1073 class MemCachedClientforWiki
extends MWMemcached
{
1074 function _debugprint( $text ) {
1075 wfDebug( "memcached: $text" );