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( @$args['servers'] );
249 $this->_debug
= @$args['debug'];
250 $this->stats
= array();
251 $this->_compress_threshold
= @$args['compress_threshold'];
252 $this->_persistant
= array_key_exists( 'persistant', $args ) ?
( @$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 @$this->stats
['delete']++
;
322 $cmd = "delete $key $time\r\n";
323 if( !$this->_safe_fwrite( $sock, $cmd, strlen( $cmd ) ) ) {
324 $this->_dead_sock( $sock );
327 $res = trim( fgets( $sock ) );
329 if ( $this->_debug
) {
330 $this->_debugprint( sprintf( "MemCache: delete %s (%s)\n", $key, $res ) );
333 if ( $res == "DELETED" ) {
340 // {{{ disconnect_all()
343 * Disconnects all connected sockets
345 public function disconnect_all() {
346 foreach ( $this->_cache_sock
as $sock ) {
350 $this->_cache_sock
= array();
354 // {{{ enable_compress()
357 * Enable / Disable compression
359 * @param $enable Boolean: TRUE to enable, FALSE to disable
361 public function enable_compress( $enable ) {
362 $this->_compress_enable
= $enable;
366 // {{{ forget_dead_hosts()
369 * Forget about all of the dead hosts
371 public function forget_dead_hosts() {
372 $this->_host_dead
= array();
379 * Retrieves the value associated with the key from the memcache server
381 * @param $key Mixed: key to retrieve
385 public function get( $key ) {
386 wfProfileIn( __METHOD__
);
388 if ( $this->_debug
) {
389 $this->_debugprint( "get($key)\n" );
392 if ( !$this->_active
) {
393 wfProfileOut( __METHOD__
);
397 $sock = $this->get_sock( $key );
399 if ( !is_resource( $sock ) ) {
400 wfProfileOut( __METHOD__
);
404 @$this->stats
['get']++
;
406 $cmd = "get $key\r\n";
407 if ( !$this->_safe_fwrite( $sock, $cmd, strlen( $cmd ) ) ) {
408 $this->_dead_sock( $sock );
409 wfProfileOut( __METHOD__
);
414 $this->_load_items( $sock, $val );
416 if ( $this->_debug
) {
417 foreach ( $val as $k => $v ) {
418 $this->_debugprint( sprintf( "MemCache: sock %s got %s\n", serialize( $sock ), $k ) );
422 wfProfileOut( __METHOD__
);
430 * Get multiple keys from the server(s)
432 * @param $keys Array: keys to retrieve
436 public function get_multi( $keys ) {
437 if ( !$this->_active
) {
441 @$this->stats
['get_multi']++
;
442 $sock_keys = array();
444 foreach ( $keys as $key ) {
445 $sock = $this->get_sock( $key );
446 if ( !is_resource( $sock ) ) {
449 $key = is_array( $key ) ?
$key[1] : $key;
450 if ( !isset( $sock_keys[$sock] ) ) {
451 $sock_keys[$sock] = array();
454 $sock_keys[$sock][] = $key;
457 // Send out the requests
458 foreach ( $socks as $sock ) {
460 foreach ( $sock_keys[$sock] as $key ) {
465 if ( $this->_safe_fwrite( $sock, $cmd, strlen( $cmd ) ) ) {
468 $this->_dead_sock( $sock );
474 foreach ( $gather as $sock ) {
475 $this->_load_items( $sock, $val );
478 if ( $this->_debug
) {
479 foreach ( $val as $k => $v ) {
480 $this->_debugprint( sprintf( "MemCache: got %s\n", $k ) );
491 * Increments $key (optionally) by $amt
493 * @param $key String: key to increment
494 * @param $amt Integer: (optional) amount to increment
496 * @return Integer: new key value?
498 public function incr( $key, $amt = 1 ) {
499 return $this->_incrdecr( 'incr', $key, $amt );
506 * Overwrites an existing value for key; only works if key is already set
508 * @param $key String: key to set value as
509 * @param $value Mixed: value to store
510 * @param $exp Integer: (optional) experiation time
514 public function replace( $key, $value, $exp = 0 ) {
515 return $this->_set( 'replace', $key, $value, $exp );
522 * Passes through $cmd to the memcache server connected by $sock; returns
523 * output as an array (null array if no output)
525 * NOTE: due to a possible bug in how PHP reads while using fgets(), each
526 * line may not be terminated by a \r\n. More specifically, my testing
527 * has shown that, on FreeBSD at least, each line is terminated only
528 * with a \n. This is with the PHP flag auto_detect_line_endings set
529 * to falase (the default).
531 * @param $sock Ressource: socket to send command on
532 * @param $cmd String: command to run
534 * @return Array: output array
536 public function run_command( $sock, $cmd ) {
537 if ( !is_resource( $sock ) ) {
541 if ( !$this->_safe_fwrite( $sock, $cmd, strlen( $cmd ) ) ) {
546 $res = fgets( $sock );
548 if ( preg_match( '/^END/', $res ) ) {
551 if ( strlen( $res ) == 0 ) {
562 * Unconditionally sets a key to a given value in the memcache. Returns true
563 * if set successfully.
565 * @param $key String: key to set value as
566 * @param $value Mixed: value to set
567 * @param $exp Integer: (optional) Experiation time
569 * @return Boolean: TRUE on success
571 public function set( $key, $value, $exp = 0 ) {
572 return $this->_set( 'set', $key, $value, $exp );
576 // {{{ set_compress_threshold()
579 * Sets the compression threshold
581 * @param $thresh Integer: threshold to compress if larger than
583 public function set_compress_threshold( $thresh ) {
584 $this->_compress_threshold
= $thresh;
591 * Sets the debug flag
593 * @param $dbg Boolean: TRUE for debugging, FALSE otherwise
595 * @see MWMemcached::__construct
597 public function set_debug( $dbg ) {
598 $this->_debug
= $dbg;
605 * Sets the server list to distribute key gets and puts between
607 * @param $list Array of servers to connect to
609 * @see MWMemcached::__construct()
611 public function set_servers( $list ) {
612 $this->_servers
= $list;
613 $this->_active
= count( $list );
614 $this->_buckets
= null;
615 $this->_bucketcount
= 0;
617 $this->_single_sock
= null;
618 if ( $this->_active
== 1 ) {
619 $this->_single_sock
= $this->_servers
[0];
624 * Sets the timeout for new connections
626 * @param $seconds Integer: number of seconds
627 * @param $microseconds Integer: number of microseconds
629 public function set_timeout( $seconds, $microseconds ) {
630 $this->_timeout_seconds
= $seconds;
631 $this->_timeout_microseconds
= $microseconds;
636 // {{{ private methods
640 * Close the specified socket
642 * @param $sock String: socket to close
646 function _close_sock( $sock ) {
647 $host = array_search( $sock, $this->_cache_sock
);
648 fclose( $this->_cache_sock
[$host] );
649 unset( $this->_cache_sock
[$host] );
653 // {{{ _connect_sock()
656 * Connects $sock to $host, timing out after $timeout
658 * @param $sock Integer: socket to connect
659 * @param $host String: Host:IP to connect to
664 function _connect_sock( &$sock, $host ) {
665 list( $ip, $port ) = explode( ':', $host );
667 $timeout = $this->_connect_timeout
;
668 $errno = $errstr = null;
669 for( $i = 0; !$sock && $i < $this->_connect_attempts
; $i++
) {
670 if ( $this->_persistant
== 1 ) {
671 $sock = @pfsockopen
( $ip, $port, $errno, $errstr, $timeout );
673 $sock = @fsockopen
( $ip, $port, $errno, $errstr, $timeout );
677 if ( $this->_debug
) {
678 $this->_debugprint( "Error connecting to $host: $errstr\n" );
683 // Initialise timeout
684 stream_set_timeout( $sock, $this->_timeout_seconds
, $this->_timeout_microseconds
);
693 * Marks a host as dead until 30-40 seconds in the future
695 * @param $sock String: socket to mark as dead
699 function _dead_sock( $sock ) {
700 $host = array_search( $sock, $this->_cache_sock
);
701 $this->_dead_host( $host );
704 function _dead_host( $host ) {
705 @list
( $ip, /* $port */) = explode( ':', $host );
706 $this->_host_dead
[$ip] = time() +
30 +
intval( rand( 0, 10 ) );
707 $this->_host_dead
[$host] = $this->_host_dead
[$ip];
708 unset( $this->_cache_sock
[$host] );
717 * @param $key String: key to retrieve value for;
719 * @return Mixed: resource on success, false on failure
722 function get_sock( $key ) {
723 if ( !$this->_active
) {
727 if ( $this->_single_sock
!== null ) {
728 $this->_flush_read_buffer( $this->_single_sock
);
729 return $this->sock_to_host( $this->_single_sock
);
732 $hv = is_array( $key ) ?
intval( $key[0] ) : $this->_hashfunc( $key );
734 if ( $this->_buckets
=== null ) {
735 foreach ( $this->_servers
as $v ) {
736 if ( is_array( $v ) ) {
737 for( $i = 0; $i < $v[1]; $i++
) {
744 $this->_buckets
= $bu;
745 $this->_bucketcount
= count( $bu );
748 $realkey = is_array( $key ) ?
$key[1] : $key;
749 for( $tries = 0; $tries < 20; $tries++
) {
750 $host = $this->_buckets
[$hv %
$this->_bucketcount
];
751 $sock = $this->sock_to_host( $host );
752 if ( is_resource( $sock ) ) {
753 $this->_flush_read_buffer( $sock );
756 $hv = $this->_hashfunc( $hv . $realkey );
766 * Creates a hash integer based on the $key
768 * @param $key String: key to hash
770 * @return Integer: hash value
773 function _hashfunc( $key ) {
774 # Hash function must on [0,0x7ffffff]
775 # We take the first 31 bits of the MD5 hash, which unlike the hash
776 # function used in a previous version of this client, works
777 return hexdec( substr( md5( $key ), 0, 8 ) ) & 0x7fffffff;
784 * Perform increment/decriment on $key
786 * @param $cmd String: command to perform
787 * @param $key String: key to perform it on
788 * @param $amt Integer: amount to adjust
790 * @return Integer: new value of $key
793 function _incrdecr( $cmd, $key, $amt = 1 ) {
794 if ( !$this->_active
) {
798 $sock = $this->get_sock( $key );
799 if ( !is_resource( $sock ) ) {
803 $key = is_array( $key ) ?
$key[1] : $key;
804 @$this->stats
[$cmd]++
;
805 if ( !$this->_safe_fwrite( $sock, "$cmd $key $amt\r\n" ) ) {
806 return $this->_dead_sock( $sock );
809 $line = fgets( $sock );
811 if ( !preg_match( '/^(\d+)/', $line, $match ) ) {
821 * Load items into $ret from $sock
823 * @param $sock Ressource: socket to read from
824 * @param $ret Array: returned values
828 function _load_items( $sock, &$ret ) {
830 $decl = fgets( $sock );
831 if ( $decl == "END\r\n" ) {
833 } elseif ( preg_match( '/^VALUE (\S+) (\d+) (\d+)\r\n$/', $decl, $match ) ) {
834 list( $rkey, $flags, $len ) = array( $match[1], $match[2], $match[3] );
838 while ( $bneed > 0 ) {
839 $data = fread( $sock, $bneed );
840 $n = strlen( $data );
846 @$ret[$rkey] .= $data;
849 if ( $offset != $len +
2 ) {
850 // Something is borked!
851 if ( $this->_debug
) {
852 $this->_debugprint( sprintf( "Something is borked! key %s expecting %d got %d length\n", $rkey, $len +
2, $offset ) );
855 unset( $ret[$rkey] );
856 $this->_close_sock( $sock );
860 if ( $this->_have_zlib
&& $flags & self
::COMPRESSED
) {
861 $ret[$rkey] = gzuncompress( $ret[$rkey] );
864 $ret[$rkey] = rtrim( $ret[$rkey] );
866 if ( $flags & self
::SERIALIZED
) {
867 $ret[$rkey] = unserialize( $ret[$rkey] );
871 $this->_debugprint( "Error parsing memcached response\n" );
881 * Performs the requested storage operation to the memcache server
883 * @param $cmd String: command to perform
884 * @param $key String: key to act on
885 * @param $val Mixed: what we need to store
886 * @param $exp Integer: when it should expire
891 function _set( $cmd, $key, $val, $exp ) {
892 if ( !$this->_active
) {
896 $sock = $this->get_sock( $key );
897 if ( !is_resource( $sock ) ) {
901 @$this->stats
[$cmd]++
;
905 if ( !is_scalar( $val ) ) {
906 $val = serialize( $val );
907 $flags |
= self
::SERIALIZED
;
908 if ( $this->_debug
) {
909 $this->_debugprint( sprintf( "client: serializing data as it is not scalar\n" ) );
913 $len = strlen( $val );
915 if ( $this->_have_zlib
&& $this->_compress_enable
&&
916 $this->_compress_threshold
&& $len >= $this->_compress_threshold
)
918 $c_val = gzcompress( $val, 9 );
919 $c_len = strlen( $c_val );
921 if ( $c_len < $len * ( 1 - self
::COMPRESSION_SAVINGS
) ) {
922 if ( $this->_debug
) {
923 $this->_debugprint( sprintf( "client: compressing data; was %d bytes is now %d bytes\n", $len, $c_len ) );
927 $flags |
= self
::COMPRESSED
;
930 if ( !$this->_safe_fwrite( $sock, "$cmd $key $flags $exp $len\r\n$val\r\n" ) ) {
931 return $this->_dead_sock( $sock );
934 $line = trim( fgets( $sock ) );
936 if ( $this->_debug
) {
937 $this->_debugprint( sprintf( "%s %s (%s)\n", $cmd, $key, $line ) );
939 if ( $line == "STORED" ) {
946 // {{{ sock_to_host()
949 * Returns the socket for the host
951 * @param $host String: Host:IP to get socket for
953 * @return Mixed: IO Stream or false
956 function sock_to_host( $host ) {
957 if ( isset( $this->_cache_sock
[$host] ) ) {
958 return $this->_cache_sock
[$host];
963 list( $ip, /* $port */) = explode( ':', $host );
964 if ( isset( $this->_host_dead
[$host] ) && $this->_host_dead
[$host] > $now ||
965 isset( $this->_host_dead
[$ip] ) && $this->_host_dead
[$ip] > $now
970 if ( !$this->_connect_sock( $sock, $host ) ) {
971 return $this->_dead_host( $host );
974 // Do not buffer writes
975 stream_set_write_buffer( $sock, 0 );
977 $this->_cache_sock
[$host] = $sock;
979 return $this->_cache_sock
[$host];
982 function _debugprint( $str ) {
987 * Write to a stream, timing out after the correct amount of time
989 * @return Boolean: false on failure, true on success
992 function _safe_fwrite( $f, $buf, $len = false ) {
993 stream_set_blocking( $f, 0 );
995 if ( $len === false ) {
996 wfDebug( "Writing " . strlen( $buf ) . " bytes\n" );
997 $bytesWritten = fwrite( $f, $buf );
999 wfDebug( "Writing $len bytes\n" );
1000 $bytesWritten = fwrite( $f, $buf, $len );
1002 $n = stream_select( $r = null, $w = array( $f ), $e = null, 10, 0 );
1003 # $this->_timeout_seconds, $this->_timeout_microseconds );
1005 wfDebug( "stream_select returned $n\n" );
1006 stream_set_blocking( $f, 1 );
1008 return $bytesWritten;
1012 * Original behaviour
1014 function _safe_fwrite( $f, $buf, $len = false ) {
1015 if ( $len === false ) {
1016 $bytesWritten = fwrite( $f, $buf );
1018 $bytesWritten = fwrite( $f, $buf, $len );
1020 return $bytesWritten;
1024 * Flush the read buffer of a stream
1026 function _flush_read_buffer( $f ) {
1027 if ( !is_resource( $f ) ) {
1030 $n = stream_select( $r = array( $f ), $w = null, $e = null, 0, 0 );
1031 while ( $n == 1 && !feof( $f ) ) {
1033 $n = stream_select( $r = array( $f ), $w = null, $e = null, 0, 0 );
1042 // vim: sts=3 sw=3 et
1046 class MemCachedClientforWiki
extends MWMemcached
{
1047 function _debugprint( $text ) {
1048 wfDebug( "memcached: $text" );