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 memcached(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 memcached
68 * memcached client class implemented using (p)fsockopen()
70 * @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 array $args Associative array of settings
248 function memcached ($args)
250 $this->set_servers(@$args['servers']);
251 $this->_debug
= @$args['debug'];
252 $this->stats
= array();
253 $this->_compress_threshold
= @$args['compress_threshold'];
254 $this->_persistant
= array_key_exists('persistant', $args) ?
(@$args['persistant']) : false;
255 $this->_compress_enable
= true;
256 $this->_have_zlib
= function_exists("gzcompress");
258 $this->_cache_sock
= array();
259 $this->_host_dead
= array();
261 $this->_timeout_seconds
= 1;
262 $this->_timeout_microseconds
= 0;
264 $this->_connect_timeout
= 0.01;
265 $this->_connect_attempts
= 3;
272 * Adds a key/value to the memcache server if one isn't already set with
275 * @param string $key Key to set with data
276 * @param mixed $val Value to store
277 * @param integer $exp (optional) Time to expire data at
282 function add ($key, $val, $exp = 0)
284 return $this->_set('add', $key, $val, $exp);
291 * Decriment a value stored on the memcache server
293 * @param string $key Key to decriment
294 * @param integer $amt (optional) Amount to decriment
296 * @return mixed FALSE on failure, value on success
299 function decr ($key, $amt=1)
301 return $this->_incrdecr('decr', $key, $amt);
308 * Deletes a key from the server, optionally after $time
310 * @param string $key Key to delete
311 * @param integer $time (optional) How long to wait before deleting
313 * @return boolean TRUE on success, FALSE on failure
316 function delete ($key, $time = 0)
321 $sock = $this->get_sock($key);
322 if (!is_resource($sock))
325 $key = is_array($key) ?
$key[1] : $key;
327 @$this->stats
['delete']++
;
328 $cmd = "delete $key $time\r\n";
329 if(!$this->_safe_fwrite($sock, $cmd, strlen($cmd)))
331 $this->_dead_sock($sock);
334 $res = trim(fgets($sock));
337 $this->_debugprint(sprintf("MemCache: delete %s (%s)\n", $key, $res));
339 if ($res == "DELETED")
345 // {{{ disconnect_all()
348 * Disconnects all connected sockets
352 function disconnect_all ()
354 foreach ($this->_cache_sock
as $sock)
357 $this->_cache_sock
= array();
361 // {{{ enable_compress()
364 * Enable / Disable compression
366 * @param boolean $enable TRUE to enable, FALSE to disable
370 function enable_compress ($enable)
372 $this->_compress_enable
= $enable;
376 // {{{ forget_dead_hosts()
379 * Forget about all of the dead hosts
383 function forget_dead_hosts ()
385 $this->_host_dead
= array();
392 * Retrieves the value associated with the key from the memcache server
394 * @param string $key Key to retrieve
401 $fname = 'memcached::get';
402 wfProfileIn( $fname );
404 if ( $this->_debug
) {
405 $this->_debugprint( "get($key)\n" );
408 if (!$this->_active
) {
409 wfProfileOut( $fname );
413 $sock = $this->get_sock($key);
415 if (!is_resource($sock)) {
416 wfProfileOut( $fname );
420 @$this->stats
['get']++
;
422 $cmd = "get $key\r\n";
423 if (!$this->_safe_fwrite($sock, $cmd, strlen($cmd)))
425 $this->_dead_sock($sock);
426 wfProfileOut( $fname );
431 $this->_load_items($sock, $val);
434 foreach ($val as $k => $v)
435 $this->_debugprint(sprintf("MemCache: sock %s got %s\n", serialize($sock), $k));
437 wfProfileOut( $fname );
445 * Get multiple keys from the server(s)
447 * @param array $keys Keys to retrieve
452 function get_multi ($keys)
457 $this->stats
['get_multi']++
;
458 $sock_keys = array();
460 foreach ($keys as $key)
462 $sock = $this->get_sock($key);
463 if (!is_resource($sock)) continue;
464 $key = is_array($key) ?
$key[1] : $key;
465 if (!isset($sock_keys[$sock]))
467 $sock_keys[$sock] = array();
470 $sock_keys[$sock][] = $key;
473 // Send out the requests
474 foreach ($socks as $sock)
477 foreach ($sock_keys[$sock] as $key)
483 if ($this->_safe_fwrite($sock, $cmd, strlen($cmd)))
488 $this->_dead_sock($sock);
494 foreach ($gather as $sock)
496 $this->_load_items($sock, $val);
500 foreach ($val as $k => $v)
501 $this->_debugprint(sprintf("MemCache: got %s\n", $k));
510 * Increments $key (optionally) by $amt
512 * @param string $key Key to increment
513 * @param integer $amt (optional) amount to increment
515 * @return integer New key value?
518 function incr ($key, $amt=1)
520 return $this->_incrdecr('incr', $key, $amt);
527 * Overwrites an existing value for key; only works if key is already set
529 * @param string $key Key to set value as
530 * @param mixed $value Value to store
531 * @param integer $exp (optional) Experiation time
536 function replace ($key, $value, $exp=0)
538 return $this->_set('replace', $key, $value, $exp);
545 * Passes through $cmd to the memcache server connected by $sock; returns
546 * output as an array (null array if no output)
548 * NOTE: due to a possible bug in how PHP reads while using fgets(), each
549 * line may not be terminated by a \r\n. More specifically, my testing
550 * has shown that, on FreeBSD at least, each line is terminated only
551 * with a \n. This is with the PHP flag auto_detect_line_endings set
552 * to falase (the default).
554 * @param resource $sock Socket to send command on
555 * @param string $cmd Command to run
557 * @return array Output array
560 function run_command ($sock, $cmd)
562 if (!is_resource($sock))
565 if (!$this->_safe_fwrite($sock, $cmd, strlen($cmd)))
572 if (preg_match('/^END/', $res))
574 if (strlen($res) == 0)
584 * Unconditionally sets a key to a given value in the memcache. Returns true
585 * if set successfully.
587 * @param string $key Key to set value as
588 * @param mixed $value Value to set
589 * @param integer $exp (optional) Experiation time
591 * @return boolean TRUE on success
594 function set ($key, $value, $exp=0)
596 return $this->_set('set', $key, $value, $exp);
600 // {{{ set_compress_threshold()
603 * Sets the compression threshold
605 * @param integer $thresh Threshold to compress if larger than
609 function set_compress_threshold ($thresh)
611 $this->_compress_threshold
= $thresh;
618 * Sets the debug flag
620 * @param boolean $dbg TRUE for debugging, FALSE otherwise
624 * @see memcahced::memcached
626 function set_debug ($dbg)
628 $this->_debug
= $dbg;
635 * Sets the server list to distribute key gets and puts between
637 * @param array $list Array of servers to connect to
641 * @see memcached::memcached()
643 function set_servers ($list)
645 $this->_servers
= $list;
646 $this->_active
= count($list);
647 $this->_buckets
= null;
648 $this->_bucketcount
= 0;
650 $this->_single_sock
= null;
651 if ($this->_active
== 1)
652 $this->_single_sock
= $this->_servers
[0];
656 * Sets the timeout for new connections
658 * @param integer $seconds Number of seconds
659 * @param integer $microseconds Number of microseconds
663 function set_timeout ($seconds, $microseconds)
665 $this->_timeout_seconds
= $seconds;
666 $this->_timeout_microseconds
= $microseconds;
671 // {{{ private methods
675 * Close the specified socket
677 * @param string $sock Socket to close
681 function _close_sock ($sock)
683 $host = array_search($sock, $this->_cache_sock
);
684 fclose($this->_cache_sock
[$host]);
685 unset($this->_cache_sock
[$host]);
689 // {{{ _connect_sock()
692 * Connects $sock to $host, timing out after $timeout
694 * @param integer $sock Socket to connect
695 * @param string $host Host:IP to connect to
700 function _connect_sock (&$sock, $host)
702 list ($ip, $port) = explode(":", $host);
704 $timeout = $this->_connect_timeout
;
705 $errno = $errstr = null;
706 for ($i = 0; !$sock && $i < $this->_connect_attempts
; $i++
) {
708 # Sleep until the timeout, in case it failed fast
709 $elapsed = microtime(true) - $t;
710 if ( $elapsed < $timeout ) {
711 usleep(($timeout - $elapsed) * 1e6
);
715 $t = microtime(true);
716 if ($this->_persistant
== 1)
718 $sock = @pfsockopen
($ip, $port, $errno, $errstr, $timeout);
721 $sock = @fsockopen
($ip, $port, $errno, $errstr, $timeout);
726 $this->_debugprint( "Error connecting to $host: $errstr\n" );
730 // Initialise timeout
731 stream_set_timeout($sock, $this->_timeout_seconds
, $this->_timeout_microseconds
);
740 * Marks a host as dead until 30-40 seconds in the future
742 * @param string $sock Socket to mark as dead
746 function _dead_sock ($sock)
748 $host = array_search($sock, $this->_cache_sock
);
749 @list
($ip, /* $port */) = explode(":", $host);
750 $this->_host_dead
[$ip] = time() +
30 +
intval(rand(0, 10));
751 $this->_host_dead
[$host] = $this->_host_dead
[$ip];
752 unset($this->_cache_sock
[$host]);
761 * @param string $key Key to retrieve value for;
763 * @return mixed resource on success, false on failure
766 function get_sock ($key)
771 if ($this->_single_sock
!== null) {
772 $this->_flush_read_buffer($this->_single_sock
);
773 return $this->sock_to_host($this->_single_sock
);
776 $hv = is_array($key) ?
intval($key[0]) : $this->_hashfunc($key);
778 if ($this->_buckets
=== null)
780 foreach ($this->_servers
as $v)
784 for ($i=0; $i<$v[1]; $i++
)
791 $this->_buckets
= $bu;
792 $this->_bucketcount
= count($bu);
795 $realkey = is_array($key) ?
$key[1] : $key;
796 for ($tries = 0; $tries<20; $tries++
)
798 // temp logging for strange bug
799 if( !isset($this->_buckets
[$hv %
$this->_bucketcount
]) ) {
800 wfDebugLog( "memcached", "Invalid bucket hash '$hv' from key '$realkey' given!" );
803 $host = $this->_buckets
[$hv %
$this->_bucketcount
];
804 $sock = $this->sock_to_host($host);
805 if (is_resource($sock)) {
806 $this->_flush_read_buffer($sock);
809 $hv +
= $this->_hashfunc($tries . $realkey);
819 * Creates a hash integer based on the $key
821 * @param string $key Key to hash
823 * @return integer Hash value
826 function _hashfunc ($key)
828 # Hash function must on [0,0x7ffffff]
829 # We take the first 31 bits of the MD5 hash, which unlike the hash
830 # function used in a previous version of this client, works
831 return hexdec(substr(md5($key),0,8)) & 0x7fffffff;
838 * Perform increment/decriment on $key
840 * @param string $cmd Command to perform
841 * @param string $key Key to perform it on
842 * @param integer $amt Amount to adjust
844 * @return integer New value of $key
847 function _incrdecr ($cmd, $key, $amt=1)
852 $sock = $this->get_sock($key);
853 if (!is_resource($sock))
856 $key = is_array($key) ?
$key[1] : $key;
857 @$this->stats
[$cmd]++
;
858 if (!$this->_safe_fwrite($sock, "$cmd $key $amt\r\n"))
859 return $this->_dead_sock($sock);
861 stream_set_timeout($sock, 1, 0);
862 $line = fgets($sock);
864 if (!preg_match('/^(\d+)/', $line, $match))
873 * Load items into $ret from $sock
875 * @param resource $sock Socket to read from
876 * @param array $ret Returned values
880 function _load_items ($sock, &$ret)
884 $decl = fgets($sock);
885 if ($decl == "END\r\n")
888 } elseif (preg_match('/^VALUE (\S+) (\d+) (\d+)\r\n$/', $decl, $match))
890 list($rkey, $flags, $len) = array($match[1], $match[2], $match[3]);
896 $data = fread($sock, $bneed);
902 @$ret[$rkey] .= $data;
905 if ($offset != $len+
2)
907 // Something is borked!
909 $this->_debugprint(sprintf("Something is borked! key %s expecting %d got %d length\n", $rkey, $len+
2, $offset));
912 $this->_close_sock($sock);
916 if ($this->_have_zlib
&& $flags & memcached
::COMPRESSED
)
917 $ret[$rkey] = gzuncompress($ret[$rkey]);
919 $ret[$rkey] = rtrim($ret[$rkey]);
921 if ($flags & memcached
::SERIALIZED
)
922 $ret[$rkey] = unserialize($ret[$rkey]);
926 $this->_debugprint("Error parsing memcached response\n");
936 * Performs the requested storage operation to the memcache server
938 * @param string $cmd Command to perform
939 * @param string $key Key to act on
940 * @param mixed $val What we need to store
941 * @param integer $exp When it should expire
946 function _set ($cmd, $key, $val, $exp)
951 $sock = $this->get_sock($key);
952 if (!is_resource($sock))
955 @$this->stats
[$cmd]++
;
959 if (!is_scalar($val))
961 $val = serialize($val);
962 $flags |
= memcached
::SERIALIZED
;
964 $this->_debugprint(sprintf("client: serializing data as it is not scalar\n"));
969 if ($this->_have_zlib
&& $this->_compress_enable
&&
970 $this->_compress_threshold
&& $len >= $this->_compress_threshold
)
972 $c_val = gzcompress($val, 9);
973 $c_len = strlen($c_val);
975 if ($c_len < $len*(1 - memcached
::COMPRESSION_SAVINGS
))
978 $this->_debugprint(sprintf("client: compressing data; was %d bytes is now %d bytes\n", $len, $c_len));
981 $flags |
= memcached
::COMPRESSED
;
984 if (!$this->_safe_fwrite($sock, "$cmd $key $flags $exp $len\r\n$val\r\n"))
985 return $this->_dead_sock($sock);
987 $line = trim(fgets($sock));
991 $this->_debugprint(sprintf("%s %s (%s)\n", $cmd, $key, $line));
993 if ($line == "STORED")
999 // {{{ sock_to_host()
1002 * Returns the socket for the host
1004 * @param string $host Host:IP to get socket for
1006 * @return mixed IO Stream or false
1009 function sock_to_host ($host)
1011 if (isset($this->_cache_sock
[$host]))
1012 return $this->_cache_sock
[$host];
1016 list ($ip, /* $port */) = explode (":", $host);
1017 if (isset($this->_host_dead
[$host]) && $this->_host_dead
[$host] > $now ||
1018 isset($this->_host_dead
[$ip]) && $this->_host_dead
[$ip] > $now)
1021 if (!$this->_connect_sock($sock, $host))
1022 return $this->_dead_sock($host);
1024 // Do not buffer writes
1025 stream_set_write_buffer($sock, 0);
1027 $this->_cache_sock
[$host] = $sock;
1029 return $this->_cache_sock
[$host];
1032 function _debugprint($str){
1037 * Write to a stream, timing out after the correct amount of time
1039 * @return bool false on failure, true on success
1042 function _safe_fwrite($f, $buf, $len = false) {
1043 stream_set_blocking($f, 0);
1045 if ($len === false) {
1046 wfDebug("Writing " . strlen( $buf ) . " bytes\n");
1047 $bytesWritten = fwrite($f, $buf);
1049 wfDebug("Writing $len bytes\n");
1050 $bytesWritten = fwrite($f, $buf, $len);
1052 $n = stream_select($r=NULL, $w = array($f), $e = NULL, 10, 0);
1053 # $this->_timeout_seconds, $this->_timeout_microseconds);
1055 wfDebug("stream_select returned $n\n");
1056 stream_set_blocking($f, 1);
1058 return $bytesWritten;
1062 * Original behaviour
1064 function _safe_fwrite($f, $buf, $len = false) {
1065 if ($len === false) {
1066 $bytesWritten = fwrite($f, $buf);
1068 $bytesWritten = fwrite($f, $buf, $len);
1070 return $bytesWritten;
1074 * Flush the read buffer of a stream
1076 function _flush_read_buffer($f) {
1077 if (!is_resource($f)) {
1080 $n = stream_select($r=array($f), $w = NULL, $e = NULL, 0, 0);
1081 while ($n == 1 && !feof($f)) {
1083 $n = stream_select($r=array($f), $w = NULL, $e = NULL, 0, 0);
1092 // vim: sts=3 sw=3 et